Week 2- Introduction to Python #1.pdf

Full Transcript

INTRODUCTION TO PYTHON PROGRAMMING American University of Sharjah Prepared by Dr. Jamal A. Abdalla, CVE Revised by Dr. Tamer Shanableh, CSE Computer Software 2 Operating System - Provides an interface with the user Unix, Windows, Linux, iOS,.. Software Applications Word processors (Microsoft Word,.....

INTRODUCTION TO PYTHON PROGRAMMING American University of Sharjah Prepared by Dr. Jamal A. Abdalla, CVE Revised by Dr. Tamer Shanableh, CSE Computer Software 2 Operating System - Provides an interface with the user Unix, Windows, Linux, iOS,.. Software Applications Word processors (Microsoft Word,...) Spreadsheet programs (Excel,...) Mathematical computation tools (MATLAB, MathCAD,...) Computer Languages Machine language Assembly language High level Structured languages (C, Fortran, Basic) High level Object-Oriented languages (C++, Java, Python) Internet Browsers Chrome, Edge, Firefox, …. Apps WhatsApp, Instagram, Twitter, ….. Machine Languages 3 Machine Languages (sequence of 1s and 0s) It is the only language understood directly by computers Defined by computer’s hardware design Machine-dependent (different languages for Windows, Linus, Mac,…) Languages specific to particular computers Difficult to understand for human readers Streams of numbers, ultimately reduced to 0s and 1s (Binary code) Instruct most elementary of operations (ex. copy a number from memory to the CPU) Tedious and error-prone Lead to Assembly Languages Assembly Languages 4 Assembly Languages English-like abbreviations Represent elementary operations of computer Translated to machine language before running them Assemblers convert to Assembly language into machine language High-speed conversion Clearer to human readers than machine language Still tedious to use Many instructions for simple tasks Lead to High-Level Languages Example Example Assembly line to copy from Memory@42 to CPU@eax location: mov eax, 42 Same code in machine language: 10111000 00101010 00000000 00000000 00000000 High Level Languages 5 High-Level Languages Single statements accomplish substantial tasks (like printing out a variable of type dictionary) Translated to machine language Compilers convert to assembly then Conversion takes time to machine language High-level languages has Code Instructions understandable to humans Looks mostly like everyday English (ex. print([1,2,3,4]) Contain common mathematical notation (ex. rst = x / y) Used in development environment (ex. colab) Compiled versus Interpreted Languages Compilation vs. Interpretation: A compiler takes the entire source code of a program and translates it into machine code all at once. This machine code is saved as an executable file, and the program can be run multiple times without recompilation. (Example C++) An interpreter, on the other hand, processes the source code line by line or statement by statement at runtime. It translates each line or statement into machine code and immediately executes it. (Example Python) Object-Oriented Programming 7 Object-Oriented Programming (OOP) Modeled after items in the real world (can create new variable types like Students, Course,…variables of these types are called objects) Uses objects as a reusable software components (we use Lists without implementing them ourselves) In OOP, Programs are more understandable by humans Therefore, programs are easier to correct, modify and maintain C, C++, Java, Python 8 C Developed by Dennis Ritchie at Bell Laboratory (1972) Gained recognition as language of UNIX It is a widely used language for developing operating systems Was used to create Python Lead to the development of C++ C++ Developed by Bjarne Stroustrup at Bell Laboratory (1980s) Extension of C with elements from a Simulation programming language (Simula 67) It is a structured and object-oriented programming language Java It is a product of Sun Microsystems corporate research project (1991) Based on C and C++, but it is OS-independent, so the same code runs on windows, mac and linux Intended for intelligent consumer-electronic devices Gained popularity with the emergence of WWW Widely used for enhancing functionality of WWW servers Python 9 Python is a popular structured and object-oriented programming language. It was created by Guido van Rossum and released in 1991. It is used for: Machine Learning and Data Science Software development in general Web development (server-side) and web applications Performing complex mathematics Handling big data Rapid prototyping and for production-ready software development System scripting (Example: Write code to Automate moving, copying, renaming, and deleting files and directories). Why Python? 10 Python has many features that are not available in a single language Works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc). Has a simple syntax that is readable and like the English language. Has a compact syntax that allows developers to write shorter programs. Runs on an interpreter system for immediate execution and quick prototyping. It is a structured and an object-oriented programming language. It is the widely used programming language for Data Science and Machine Learning Google Colab Notebook 11 What is Colab? Colab, or "Colaboratory", allows the user to write and execute Python programs in the browser, with zero configuration required. It gives the user access to GPUs and facilitates easy sharing. Google Colab Notebook 12 Cells A notebook is a list of cells. Cells contain either explanatory text or executable code and its output. Code cells Command for the Code cell: Type Cmd/Ctrl+Enter to run the cell in place; Type Shift+Enter to run the cell and move focus to the next cell (adding one if none exists); or Type Alt+Enter to run the cell and insert a new code cell immediately below it. There are additional options for running some or all cells in the Runtime menu. Text cells This is a text cell. You can double-click to edit this cell. Text cells use markdown syntax. Adding and moving cells You can add new cells by using the + CODE and +TEXT buttons that show when you hover between cells. You can move a cell by selecting it and clicking Cell Up or Cell Down in the top toolbar. 13 The First Program 14 Use Colab to write and execute the following expressions/statement/programs print(‘Hello World!’ ) #Print your 1st Python String counter = 100 # Creates an integer variable miles = 1000.0 # Creates a floating point variable name = "Zara Ali" # Creates a string variable print (counter) Output: Hello World! print (miles) 100 1000.0 print (name) Zara Ali The print() function #Use single quotation for printing text print('Welcome to NGN112!') #may enclose a string in double quotes (") print("Welcome to NGN112!") output: Welcome to NGN112! #Printing a List of Items (comma-separated): print('Welcome', 'to', 'NGN112!') output: Welcome to NGN112! #Printing the Value of an Expression (do not use quotations for expression): print('Sum = ', 1 + 2) output: Sum = 3 Variables, Data types, Input and Output 16 Python supports five basic data types and five compound data types. Each data type has its own operations. Basic Data Types Integer (int) Float (float) Complex (complex) Boolean (bool) String (str) Compound data Types List (list) Tuple (tuple) Set (set) Dictionary (dict) Range (range) Data Types Description and Examples 17 Python Operations 18 ❑ Arithmetic operators ❑ Assignment operators (ex. x = y) ❑ Comparison operators (ex. x > y) ❑ Logical operators (ex. x and y) ❑ Identity operators (ex. x is y) ❑ Membership operators (ex. x in y) ❑ Bitwise operators (ex. x & y) (ex. x + y) Variable Names Rules 19 Variable names can be as long as you like. They can contain both letters and numbers (ex. fall23). They can’t begin with a number. (ex 23fall is not allowed) Uppercase letters are not allowed. (ex. Fall23 is not allowed). Keywords cannot be used as variable names. (ex. print) The underscore character, _, can appear in a variable name. (ex fall_23) If you give a variable an illegal name, you get a syntax error: >>> 1sum = ‘sum of grades of section 1‘ #do not start with a number SyntaxError: invalid syntax >>> more@ = 1000000 # @ is not allowed SyntaxError: invalid syntax >>> class = 'Advanced Theoretical stuff‘ #class is a keyword SyntaxError: invalid syntax Assignments 20 An assignment statement creates a new variable and gives it a value: >>> message = 'And now for something completely different' >>> n = 17 >>> pi = 3.141592653589793 This example makes three assignments. The first assigns a string (str) to a new variable named message. The second gives the integer (int) 17 to n. The third assigns a float value which is the (approximate) value of π to pi. Ref. Allen B. Downey, Think Python Expression and Statement 21 An expression is a combination of values, variables, and operators. A value all by itself is considered an expression, and so is a variable, so the following are all legal expressions: >>> n = 17 >>> n + 25 >>> 42 >>> n # # # # assignment operator arithmetic operator a single value a variable When you type an expression at the prompt, the interpreter evaluates it, which means that it finds the value of the expression. In this example, n has the value 17 and n + 25 has the value 42. Expression and Statement, cont. 22 A statement is a unit of code that has an effect, like creating a variable or displaying a value. >>> n = 17 >>> print(n) The first line is an assignment statement that gives a value to n. The second line is a print statement that displays the value of n. When you type a statement, the interpreter executes it, which means that it does whatever the statement says. In general, statements don’t have values. int type and its Operations 23 Type int represents integers (whole number) positive or negative Example: x=–100, x=–50, x=0, x=1, x=1000, …(no commas or periods) Integer numbers (literals) look like this: 1, 82, 256 (no commas or periods) Integer operations: +, –, *, //, %, **, unary – x+y x-y x*y x//y # divide x/y and round down the answer x**y #to the power of -x int type and its Operations 24 Operations on int values must yield an int Integer Division (//): 1 // 2 rounds result down to 0 and 7 // 2 is 3 Remainder (%): (% companion operation to //) 5 % 2 evaluates to 1, remainder when dividing 5 by 2 8 % 3 evaluates to 2 and 10 % 5 evaluates to 0 Operator / is not an int operation in Python 3, it generates fractions Operator examples - 1 x=12345 print(x%10) print(x%100) print(x%1000) #reminder of division by 10 = 5 #reminder of division by 100 = 45 #reminder of division by 100 = 345 print(x / 10) # regular division = 1234.5 print(x // 10) # floor division = 1234 print(x / 100) # regular division = 123.45 print(x // 100) # floor division = 123 Operator examples - 2 #access one x=12345 print(x%10) x = x // 10 print(x%10) x = x // 10 print(x%10) x = x // 10 print(x%10) x = x // 10 print(x%10) digit at a time #reminder of division by 10 = 5 #12345 // 10 = 1234 (floor division) # = 4 # = 123 # = 3 # = 12 # = 2 # = 1 # = 1 #Find if a number is odd or even x = 101 if x%2==0: print('x = ', x, ' is even') else: print('x = ', x, ' is odd') float type and its Operations 27 Type float (floating point) represents real numbers Values: distinguished from integers by decimal points In Python a number with a “.” is a float literal (e.g. 12.0) Without a decimal a number is an int literal (e.g. 12) Operations: +, –, *, /,**, unary – Notice that float has a different division operator Example: 5.0/2.0 evaluates to 2.5 Exponent notation which is used for large (or small) values 24.3e5 is 24.3 *105 or 2430000 48.62e–3 is 48.62*10–3 or 0.04862 Arithmetic Operations for int and float Arithmetic operators are used with numeric values to perform common mathematical operations 28 Operator Name Example + Addition x+y - Subtraction x-y * Multiplication x*y / Division x/y % Modulus x%y ** Exponentiation x ** y // Floor division x // y (a.k.a. int division) Precedence of Arithmetic Operations 29 () Exponentiation: ** Unary operators: + – # ex. -x or +x Binary arithmetic: * / % Binary arithmetic: + – # ex. x-y Comparisons: < > = Equality relations: == != # (x==y) means is x equal to y Logical not # found=false | ex. !found means NOT found Logical and # found=true and first=false | ex. (found and first) is false Logical or # found=true and first=false | ex. (found or first) is true Precedence goes downwards The operations in the same have the same precedence, left first Example: Example: 6/2*3 is (6/2)*3 3*(2+4) = Example: 4+6*5 = 4+(6*5) = 34 3*2 + 4 = Example of Arithmetic precedence-1 30 Step 1. y = 2 * 5 * 5 + 3 * 5 + 7; 2 * 5 is 10 Step 2. y = 10 * 5 + 3 * 5 + 7; 10 * 5 is 50 Step 3. Step 4. y = 50 + 3 * 5 + 7; 3 * 5 is 15 (Multiplication before addition) (Leftmost addition) y = 65 + 7; 65 + 7 is 72 Step 6. (Leftmost multiplication) y = 50 + 15 + 7; 50 + 15 is 65 Step 5. (Leftmost multiplication) y = 72; (Last addition) (Last operation—place 72 into y) Example of Arithmetic precedence-2 31 What is the value of this expression? rst = 2 * 32 + 49 % 10 rst = 2 * (9) + 49 % 10 rst = 2 * 9 + 49 % 10 rst = (18) + 49 % 10 rst = 18 + (9) = 27 Write it in Python and evaluate it to verify your answer Precedence: () Exponentiation: ** Unary operators: + – Binary arithmetic: * / % Binary arithmetic: + – Comparisons: < > = Equality relations: == != Logical not Logical and Logical or bool type and its Operations 32 Type boolean or bool represents logical statements Values: True, False Boolean literals are just True and False (have to be capitalized) Operations: logical operators: not, and, or not b: True if b is false and False if b is true b and c: True if both b and c are true; False otherwise b or c: True if b is true or c is true; False otherwise Often come from comparing int or float values (ex. (x>y) ) Comparison operators: i < j, i = j, i > j Equality/inequality operators: i == j, i != j Important note: x=y is called assignment x==y is called equality, you are asking if they are equal bool type and its Operations 33 Logical operators are used to combine conditional statements Operator Description Example and Returns True if both statements are true x < 5 and x < 10 or Returns True if one of the statements is true x < 5 or x < 4 not Reverse the result, returns False if the result is true and returns True if the result is false not(x < 5 and x < 10) Summary of Logical Operators (and, or, not) 34 A True True False False B True False True False A and B True False False False A True True False False B True False True False A or B True True True False A True False not A False True bool type Equality and Comparison Operators 35 Equality and comparison operators are used to compare two values Operator Name Example == Equal x == y != Not equal x != y > Greater than x>y < Less than x= Greater than or equal to x >= y