2/12/2014 CSCI 1101B Introduction to Python Mohammad T . Irfan New office hours: M 10-12, Th 3-5 2/4/14 Basic Elements of Python 1
2/12/2014 Statement print ‘Welcome to Python’ print “What’s your name?” total = 0 x = [10, 20, 5] for number in x: total = total + number print total Function (example from lab) More on Parameters Function name functions later Header on ... def oddEven(): xStr = raw_input('Enter a number: ') x = int(xStr) if x%2 == 0: print x, 'is even' else: print x, 'is odd' Body – must use indentation 2
2/12/2014 Objects Scalar – 4 types int (example: -10000, 200, 53) float (example: -37.59, 28.0) bool (example: True, False) None Non-scalar String (example: “hello”, “57”) And many other ... (You will define and create your own non-scalar objects later on) Expressions Arithmetic x + y x – y x * y x/y Caution: when x and y are both int, then the result is also int (Python 2.7 truncates all decimal digits after the decimal point) – i t’s called “integer division” Better practice: Use x//y when x and y are both int // operator specifically means integer division x % y: remainder of the division x/y for int x & y x ** y: x raised to the power y comparison: == (equal), != (not eq), >, >=, <, <= Precedence – usual 3
2/12/2014 Expressions Logical operators (on bool ) a and b a or b not a Variables and assignment Variable: named storage space def area(): pi = 3.14159 Note the indentation r = 10 area = pi * r**2 print area You don’t need to specify type of a variable – it’s automatically determined Naming a variable Must start with a letter (upper or lower case) or _, may contain digits Use sensible names. Cannot use reserved words. 4
2/12/2014 Conditional Statements if-else An if block can be optionally associated with an else block def oddEven(): x = int(raw_input('Enter a number: ')) if x%2 == 0: Note the indentation print x, 'is even' else: print x, 'is odd' 5
2/12/2014 if-elif-else if block , followed by any number of elif blocks , followed by an optional else block def showMinimum(x, y, z): if x < y and x < z: print x, 'is min' elif y < z: print y, 'is min' else: print z, 'is min‘ Note: parameter passing to a function To “call” this function from JES, load it first and then enter the following command into the black window showMinimum (20, 30, 5) if statements can be nested Recap 6
2/12/2014 Scalar vs. non-scalar types 34,654.01 12.998 31,364 Floats 12 1.01 Integers 0.01 -12 Bowdoin College Mark 85 5 th Street NW Inside the computer, these are all just bits Strings Quiz What would be the output of the following? print 1/2 7
2/12/2014 Values & names with the same value are interchangeable! >>> print 12 * 3 >>> name = " Mark " 36 >>> print name >>> value = 12 Mark >>> print value >>> print name * 3 12 MarkMarkMark >>> print value * 3 >>> print " Mark " * 3 36 MarkMarkMark Non-scalar Type: String 8
2/12/2014 String Examples “Hello and welcome” “Bowdoin College” Assignment statement college = “Bowdoin College” What is the difference between “57” and 57? Main difference is representation You can apply all arithmetic operators on 57 57 + 2 57 * 2 Arithmetic operations are meaningless for “57” “57” + 2 # ERROR “57” * 2 # ‘5757’ 9
2/12/2014 Operations on String college = “Bowdoin College” Length of a string len(college) # 15 Indexing college[2] # ‘w’ college[-1] # ‘e’ college[-2] # ‘g’ Slicing college[0:2] # ‘Bo’ college[0:len(college)] # ‘Bowdoin College’ Splitting college.split() # ['Bowdoin', 'College'] Taking a string as input x = raw_input (‘Enter your name’) y = raw input (‘How old are you?’) Suppose user enters 20 as his/her age y’s value is “20”, not 20 if you want to convert string “20” to number 20, y = int(y) # Can use a different variable name on LHS 10
2/12/2014 Iterative Statements/ Loops for loop General form (not actual code) for loop_variable in sequence : body of for loop Visualization of for loop Use boxes to replace the for loop 11
2/12/2014 range function sequence is commonly specified using the built-in range function with 3 parameters: start (optional, default is 0) end (must, actually ends before this value) increment (optional, default is 1) Examples range(10, 70, 20) # [10, 30, 50] range (0, 5, 1) # [0, 1, 2, 3, 4] range (0, 5) # [0, 1, 2, 3, 4] range (5) # [0, 1, 2, 3, 4] for loop example: Finding the average – 2 ways average.py Loop variable: Choose any name you want Caution: integer division! Better to write: avg = float(total)/len(x) 12
Recommend
More recommend