#### Lecture 4 ### # Michelle Szucs # To download as a Python file, right-click the link # and select "Save link as..." # Comment out code you don't want to run, or put # assert False # (uncommented) to stop code execution after that point. ############# import statements ######################## import math sin90 = math.sin(math.pi/2) print "sin90:", sin90 # You can also change the name you use to call the module # by using the "as" keyword. # You might do this to shorten a module name or make sure # the module name doesn't duplicate the name of one of your # variables. import math as totallyNotMath sin90 = totallyNotMath.sin(totallyNotMath.pi/2) print "sin90:", sin90 ############# while loops - the right way #################### isDone = False # Boolean variable - "inital condition" ##def enterNames(name): ## do stuff - dummy function to pretend we do things while not isDone: # this loop will run if isDone is False newName = raw_input("Please enter a name. ") #enterNames(newName) # dummy function call done = None # need to create the variable # Now we want to force the user to enter a valid input. while not (done == "no" or done == "yes"): # https://piazza.com/class#winter2013/6s189/39 done = raw_input("Would you like to enter more names? Please enter yes or no. ") if done == "no": # The next time the while statement is checked, # not isDone evaluates to False, and the loop # doesn't run again. isDone = True ########### while loops - the less right way ############## # You *can* use while loops in this manner, but it's better # to use a for loop. i = 0 while i < 10: print "Bad while loop:", i i+=1 # i = i+1 ################ Composite operators ###################### # See tutor problem Wk 2.1.3: Composite Operators # Composite operators make variable assignemnts. # i += 1 is the same as i = i + 1. # That means that the left-hand side of the equation needs # to be a variable name. ##################### for loops ########################### # Using range - equivalent to previous while loop # The variable i - which is automatically created when we # use it in the for loop - takes on the values 0, 1, 2, 3, # 4, 5, 6, 7, 8, and 9 for i in range(10): # for i in range(0, 10, 1) print "for loop 1:", i # Iterating over a string name = "Michelle" # letter takes on the values "M", "i", "c", etc. for letter in name: print "for loop 2:", letter # Another to do the same thing for letter in "Michelle": print "for loop 3:", letter # Iterating over a string with a while loop - uncomment to run ##i = 0 ##while i < 8: ## print name[i] ## i += 1 # Iterating over a tuple for letter in ("M","i","c","h","e","l","l","e"): print "for loop 4:", letter