Introduction to Python خانه ریاضیات اصفهان فرزانه کاظمی زمستان 93 1
Why Python? Python is free. Python easy to lean and use. Reduce time and length of coding. Huge standard library Simple (Python code is typically 3-5 times shorter than equivalent Java code, it is often 5-10 times shorter than equivalent C++ code) 2
Why Python? GitHub Archive data reveals that Python repositories, on average, receive the most pull requests of any programming language 3
Python Histrory Python is a high-level, interpreted, interactive and object-oriented scripting language. Python was developed by Guido Van Rossum Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk and Unix shell and other scripting languages. 4
Python Features Interpreted languages compiled languages Interactive mode and script mode Easy to lean and use A board standard library Portable Extendable Support OOP, Databases, GUI Programming 5
Installation of Python Python Official Website : http://www.python.org/ Windows and unix installation Set up Path Environment variables IDE for Python: IDLE 6
Notes Indentation Multiple statements on the single line Semicolon ( ; ) Multi-line statement Continuation character (\) Exception: {}, (), [] Example: total = a + \ b + \ c Comment (#) 7
Variables Definition Name Type Value Scope Life Time Location 8
Python Identifiers Identifiers: A name used to identify a variable, function, class, module or other object. How to select name: Start with a letter a to z or an underscore followed by zero or more letters, underscores and digits (0 to 9). Punctuation Case sensitive Reserved Words: Such as: Class, def, if, while,. 9
Data Type Standard Data Type: Number Boolean String List Tuple Dictionary 10
Numbers Numbers: Integer: 23, -3, -0x260 Long: 51924361L, 0x122L Float: 32.3+e18, -90.0, 1.2 Complex: 3.14j, 3e+26J Using Python as a Calculator >>> 2+2 4 11
String String: set of characters in between quotation marks. Quotation marks: Single, Double, Triple str2 = 'Hello World!' str1 = ''Hello World!'' longstr = """This is a paragraph. It is made up of multiple lines and sentences.""" Slice operator: [] or [:] 12
String Slice operator: [] or [:] print str # Prints complete string print str[0] # Prints first character of the string print str[2:5] # Prints characters starting from 3rd to 5th print str[2:] # Prints string starting from 3rd character print str * 2 # Prints string two times print str + "TEST" # Prints concatenated string 13
LIST List: A sequence data type. It is similar to array but all items can be of different data type. Mylist = [ 'abc', 86, 0.23, python', 73.2 ] list2 = [ 1, 2] print Mylist # Prints complete list print Mylist[0] # Prints first element of the list print Mylist[1:3] # Prints elements starting from 2nd till 3rd print Mylist[2:] # Prints elements starting from 3rd element print list2 * 2 # Prints list two times print Mylist + list2 # Prints concatenated lists 14
Tuple Tuple: A sequence data type. It is similar to list but Tuple cannot be updated. MyTuple = ('abc', 86, 0.23, python', 73.2 ) tuple2 = (1, 2) print MyTuple # Prints complete tuple print MyTuple[0] # Prints first element of the tuple print MyTuple[1:3] # Prints elements starting from 2nd till 3rd print MyTuple[2:] # Prints elements starting from 3rd element print tuple2 * 2 # Prints tuple two times print MyTuple + tuple2 # Prints concatenated tuples 15
Dictionary Dictionary: It is a kind of hash table type. dict = {} dict['one'] = "This is one" dict[2] = "This is two tinydict = {'name': 'john','code':6734, 'dept': 'sales'} print dict['one'] print dict[2] print tinydict print tinydict.keys() print tinydict.values() # Prints value for 'one' key # Prints value for 2 key # Prints complete dictionary # Prints all the keys # Prints all the values # Prints concatenated tuples 16
Basic Operators Different types of operators: Arithmetic Operators Comparison (i.e., Relational) Operators Assignment Operators Logical Operators Bitwise Operators Membership Operators Identity Operators 17
Operator Precedence Operator Description ** Exponentiation (raise to the power) ~ + - Complement, unary plus and minus * / % // Multiply, divide, modulo and floor division + - Addition and subtraction >> << Right and left bitwise shift & Bitwise 'AND' ^ Bitwise exclusive `OR' and regular `OR' <= < > >= Comparison operators <> ==!= Equality operators = %= /= //= -= += *= **= Assignment operators is, is not in, not in Not, or, and Identity operators Membership operators Logical operators 18
Decision Making True:. any non-zero and non-null values False:. zero or null If statement If else statement Nested if statement 19
If Statement if expression: statement(s) var1 = 100 if var1: print "1 - Got a true expression value" print var1 var2 = 0 if var2: print "2 - Got a true expression value" print var2 print "Good bye!" 20
If else Statement if expression: statement(s) else: statement(s) var1 = 100 if var1: print "true expression value" print var1 else: print " false expression value" print var1 21
elif Statement if expression1: statement(s) elif expression2: statement(s) else: statement(s) 22 var = 100 if var == 200: print "1 - Got a true expression value" print var elif var == 150: print "2 - Got a true expression value" print var2 elif var == 100: print "3 - Got a true expression value" print var else: print "4 - Got a false expression value" print var print "Good bye!"
Nested If Statement if expression1: statement(s) if expression2: statement(s) elif expression3: statement(s) else: statement(s) elif expression4: statement(s) else: statement(s) var = 100 if var < 200: print "Expression value is less than 200" if var == 150: print "Which is 150" elif var == 100: print "Which is 100" elif var == 50: print "Which is 50" elif var < 50: print "Expression value is less than 50 else: print "Could not find true expression" print "Good bye!" 23
LOOP While Loop For Loop Nested Loop 24
While Loop while expression: statement(s) count = 0 while (count < 9): print 'The count is:', count count = count + 1 print "Good bye!" 25
For Loop for iterating_var in sequence: statements(s) for letter in 'Python': # First Example print 'Current Letter :', letter fruits = ['banana', 'apple', 'mango'] for fruit in fruits: # Second Example print 'Current fruit :', fruit print "Good bye!" 26
Using ELSE with loop else statement is used with a for loop else statement is used with a while loop count = 0 while count < 5: print count, " is less than 5" count = count + 1 else: print count, " is not less than 5" 27
Nested Loop for iterating_var in sequence: for iterating_var in sequence: statements(s) statements(s) while expression: while expression: statement(s) statement(s) 28
Loop Control Statement Break Continue Pass 29
Break for letter in 'Python': # First Example if letter == 'h': break print 'Current Letter :', letter var = 10 # Second Example while var > 0: print 'Current variable value :', var var = var -1 if var == 5: break print "Good bye!" 30
Continue for letter in 'Python': # First Example if letter == 'h': continue print 'Current Letter :', letter var = 10 # Second Example while var > 0: var = var -1 if var == 5: continue print 'Current variable value :', var print "Good bye!" 31
Scape Characters Backslash Notation Description \a Bell or alert \\ Backslash \ Double quote \n Newline \r Carriage return \ Single quote \t Tab 32
String String Operators: +, *, [], [:], IN, Not IN, r/r, % Example: print r"\n" print "My name is %s and weight is %d kg!" % ('Zara', 21) Formatting symbol: %c character %i signed decimal integer %d signed decimal integer %f %E floating point real number exponential notation (with UPPERcase 'E') 33
String >>> pi = 3.14159 >>> print(" pi = %1.2f " % pi) pi = 3.14 >>> print(" pi = %d " % pi) pi = 3 >>> print(" pi = %E " % pi) pi= 3.141590E+00 34
String s Methods find(str, beg=0 end=len(string)) index(str, beg=0, end=len(string)) islower() isupper() capitalize() replace(old, new [, count]) rfind(str, beg=0,end=len(string)) rindex( str, beg=0, end=len(string)) join(seq) str = "-"; seq = ("a", "b", "c"); print str.join( seq ); 35
Function Benefit of using function Bulit-in Function User Define Function Defining a Function def functionname([param1,[param2, ]]) : body return [expression] Calling a Function Parameters & arguments Order of Parameters & arguments 36
Function Define a Function: def printme( str ): print < +str+ > return Calling a Function: printme( Hello ) printme( Book ): 37
Passing Parameters Call by Value Call by Reference Call by object Call by Object Reference Call by Sharing 38
Examples (Parameters) # Function definition def changeme( mylist ): mylist = [1,2,3,4]; print "Values inside the function: ", mylist return # Now you can call changeme function mylist = [10,20,30]; changeme( mylist ); print "Values outside the function: ", mylist 39
Examples (Parameters) # Function definition def changeme( mylist ): mylist.append([1,2,3,4]); print "Values inside the function: ", mylist return # Now you can call changeme function mylist = [10,20,30]; changeme( mylist ); print "Values outside the function: ", mylist 40
Passing Parameters Call by object Immutable String, Integer, Tuple Call by Value (They can't be changed within the function) Mutable Call by object Two cases: Can be Changed Unchanged 41
Examples (Parameters) # Function definition def r_demo(x): print "x=",x," id=",id(x) x=42 print "x=",x," id=",id(x) # Now you can call r_demo function >>> x = 9 >>> id(x) 41902552 >>> r_demo(x) x= 9 id= 41902552 x= 42 id= 41903752 >>> id(x) 41902552 42