9/24/14 ¡ CSCI 1101A Introduction to Python Ch. 2 to 5 [Guttag] Mohammad T . Irfan 9/9/14 – 9/25/14 Questions u When are the readings “doings” due? u When will be the in-class exams? u First exam: Thursday, 9/18 1 ¡
9/24/14 ¡ Writing a program in IDLE u To start IDLE u Mac: Start terminal first (go to spotlight and type “terminal”); in terminal, type “idle” without the quotes and hit return u Windows: in metro/start menu type “IDLE” u To open editor: File è New Window u Type your program and save it with extension “.py” u To run your program: Run è Run Module Basic Elements of Python 2 ¡
9/24/14 ¡ Statement (or command) u print ‘Welcome to Python’ u print “What’s your name?” u print 2 + 3 * 4 Assignment statement: u x = 2 ** 3 ** 2 Assign a value 2 3^2 to “variable” x More about it later u print x Comments u # Single line comment u ‘‘‘ Multiple lines of comments ’’’ 3 ¡
9/24/14 ¡ Objects u Scalar – 4 types u int (example: -10000, 200, 53) u float (example: -37.59, 28.0) u bool (example: True, False) u None u Non-scalar u String (example: “hello”, “57”) u List (example: [2, 3, 5, 7, 11, “primes”]) u And many other ... (You will define and create your own non-scalar objects later on) u Object types Expressions u Arithmetic u x + y u x – y u x * y u x/y u 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) – it’s called “integer division” u Better practice: Use x//y when x and y are both int // operator specifically means integer division u x % y: remainder of the division x/y for int x & y u x ** y: x raised to the power y u comparison: == (equal), != (not eq), >, >=, <, <= u Precedence – usual 4 ¡
9/24/14 ¡ Expressions u Logical operators (on bool ) u a and b u a or b u not a u Examples u 3 > 2 and 3 > 4 u 3 > 2 or 3 > 4 u not 3 > 4 Variables and assignment u Variable: named storage space pi = 3.14159 r = 10 Remember: Assignment works right to left area = pi * r**2 print area u You don’t need to specify type of a variable – it’s automatically determined u Rules of naming a variable u Must start with a letter (upper or lower case) or _, may contain digits after the first symbol u Use sensible names u Cannot use reserved words 5 ¡
9/24/14 ¡ Conditional Statements if-else u An if block can be optionally associated with an else block x = 10 if x%2 == 0: Note the indentation print x, 'is even' else: print x, 'is odd' 6 ¡
9/24/14 ¡ Spice it up… Can we take x as an input? x = input(“Enter an integer #: ”) if x%2 == 0: print x, 'is even' else: print x, 'is odd' Spice it even more… Use a function More on Parameters Function name functions later Header on ... def oddEven(x): if x%2 == 0: print x, 'is even' Body: Note the else: indentation print x, 'is odd' How to use this function? 7 ¡
9/24/14 ¡ if-elif-else u if block , followed by any number of elif blocks , followed by an optional else block u if statements can be nested u Problem: Print the minimum of three given numbers x, y, and z 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’ Quiz u What will be the output? x = 0 if x >= 0: print "non-negative" elif x <= 0: print "non-positive" 8 ¡
9/24/14 ¡ Exercise (p. 16) u Write a program to find the largest odd number among three given numbers x, y, and z. def largestOdd(x, y, z): if x%2 == 1 and y%2 == 1 and z%2 == 1: if x > y and x > z: print x elif z%2 == 1 and x%2 == 1: elif y > z: if z > x: print y print z else: else: print z print x elif x%2 == 1 and y%2 == 1: elif x%2 == 1: if x > y: print x print x elif y%2 == 1: else: print y print y elif z%2 == 1: elif y%2 == 1 and z%2 == 1: print z if y > z: else: print y print "None is odd" else: print z Iterative Statements/ Loops 9 ¡
9/24/14 ¡ while loop u Problem: Print numbers 1, 2, …, 10, each on a single line def printNumbers(): i = 1 Test while i <= 10: print i Body i = i + 1 while loop (cont…) u Problem: Square a positive integer by addition only def square(x): times = 0 ans = 0 while (times != x): Test ans = ans + x Body times = times + 1 print ans Can you make it work for x <= 0 as well? Hint: Book 10 ¡
9/24/14 ¡ while loop (cont…) u Write a function that takes a positive integer number n as a parameter and calculates the sum 1 + 2 + ... + n def seriesSum(n): Test total = 0 x = 1 while x <= n: total = total + x This line is crucial! x = x + 1 print total for loop u General form (not actual code) u for loop_variable in sequence : body of for loop 11 ¡
9/24/14 ¡ range function u sequence is commonly specified using the built-in range function with 3 parameters: u start (optional, default is 0) u end (must, actually ends before this value) u increment (optional, default is 1) u Examples u range(10, 70, 20) # [10, 30, 50] u range (0, 5, 1) # [0, 1, 2, 3, 4] The range function outputs a list. u range (0, 5) # [0, 1, 2, 3, 4] More coming soon… u range (5) # [0, 1, 2, 3, 4] for loop u Problem: Print numbers 1, 2, …, 10, each on a single line Loop variable Sequence def printNumbers2(): for i in range(1, 11, 1): print i Body – multiple lines allowed 12 ¡
9/24/14 ¡ for loop (cont…) u Problem: Square a positive integer by addition only Alternatives: range(0, x, 1) range (0, x) def square2(x): range (1, x+1, 1) range (1, x+1) ans = 0 for times in range(x): ans = ans + x print ans Can you make it work for x <= 0 as well? for loop (cont…) u Write a function that takes a positive integer number n as a parameter and calculates the sum 1 + 2 + ... + n def seriesSum2(n): total = 0 for x in range(1, n+1): total = total + x print total u HW Problem: Given a number n, calculate the sum 1 + 4 + 7 + 10 + … + (3n+1) 13 ¡
9/24/14 ¡ Nested Loops break statement continue statement Problem: print a pyramid of n lines of numbers u For n = 5, we want 0 1 1 2 2 2 3 3 3 3 4 4 4 4 4 5 5 5 5 5 5 #Prints a pyramid of numbers with n lines #n is given as a parameter def pyramid(n): for line in range(n+1): for times in range(line+1): print line, #Prints the line number followed by a space print #This inserts a new line. Same as: print "" 14 ¡
9/24/14 ¡ Nested loop exercise u What would be the output? def loopDemo(): x = 3 for j in range(x): for i in range(x): print j, i 0 0 0 1 0 2 1 0 1 1 1 2 2 0 2 1 2 2 break statement u Used for early termination of a loop u Only terminates the immediate loop that contains the break statement, not other loops def loopDemo(): x = 3 break can be for j in range(x): used without for i in range(x): nested loops if i > 1: break #will not print any value of i > 1 print j, i 0 0 0 1 1 0 1 1 2 0 2 1 15 ¡
9/24/14 ¡ continue statement u Keeps the loop going, but skips the code after it u Example: want to skip printing some i values in the middle def loopDemo(): 0 0 x = 3 0 2 for j in range(x): continue can be for i in range(x): 1 0 used without 1 2 if i == 1: nested loops 2 0 continue #will skip 1 2 2 print j, i Non-scalar object String 16 ¡
9/24/14 ¡ String u Examples u “Hello and welcome” u “Bowdoin College” u Assignment statement u college = “Bowdoin College” Operations on String u college = “Bowdoin College” u Length of a string u len(college) # 15 u Indexing u college[2] # ‘w’ u college[-1] # ‘e’ u college[-2] # ‘g’ u Slicing u college[0:2] # ‘Bo’ u college[0:len(college)] # ‘Bowdoin College’ u Splitting u college.split() # ['Bowdoin', 'College'] 17 ¡
9/24/14 ¡ Taking a string as input u x = raw_input (‘Enter your name: ’) u y = raw_input (‘How old are you? ’) u Suppose user enters 57 as his/her age u y’s value is “57”, not 57 u if you want to convert string “57” to number 57, u y = int(y) # Can use a different variable name on LHS u Alternative: y = input(‘How old are you? ’) What is the difference between “57” and 57? u Main difference is representation u You can apply all arithmetic operators on 57 u 57 + 2 u 57 * 2 u Arithmetic operations are meaningless for “57” u “57” + 2 # ERROR u “57” * 2 # ‘5757’ 18 ¡
9/24/14 ¡ Non-scalar object List List u Ordered sequence of values u Each value is identified by an index u Example 19 ¡
9/24/14 ¡ More examples of list u A list may contain heterogeneous data myList = [“I did it all”, 4, “love”] for i in myList: print i List vs. string: similar operations u Concatenation 20 ¡
Recommend
More recommend