(This course assumes familiarity with the material presented in Unit 1: Python Syntaxand Unit 2: Strings & Console Output. From here on out, take for granted that each new course assumes knowledge of the material presented in the previous courses.)
You may have noticed that the Python programs we've been writing so far have had sort of one-track minds. They compute the sum of two numbers or print
something
to the console, but they don't have the ability to pick one outcome over another—say, add two numbers if their sum is less than 100, or instead print
the
numbers to the console without adding them if their sum is greater than 100.
Control flow allows us to have these multiple outcomes and to select one based on what's going on in the program. Different outcomes can be produced based on user input or any number of factors in the program's environment. (The environment is the technical name for all the variables—and their values—that exist in the program at a given time.)
'''def clinic(): print "You've just entered the clinic!" print "Do you take the door on the left or the right?" answer = raw_input("Type left or right and hit 'Enter'.").lower() if answer == "left" or answer == "l": print "This is the Verbal Abuse Room, you heap of parrot droppings!" elif answer == "right" or answer == "r": print "Of course this is the Argument Room, I've told you that already!" else: print "You didn't pick left or right! Try again." clinic() ''' ##上面采用的是递归。递归的效率比较低。改为循环 def clinic(): print "You've just entered the clinic!" print "Do you take the door on the left or the right?" while True: answer = raw_input("Type left or right and hit 'Enter'." ).lower() if answer == "left" or answer == "l": print "This is the Verbal Abuse Room, you heap of parrot droppings!" break elif answer == "right" or answer == "r": print "Of course this is the Argument Room, I've told you that already!" break else: print "You didn't pick left or right! Try again." clinic()
有疑问加站长微信联系(非本文作者)