for 循环用于针对集合中每个元素的一个代码块,而while循环不断地运行,直到指定的条件不满足为止。
例如:
prompt = "\n Tell me something,and i will repeat it back to you." prompt += "\n Enter 'quit' to end the pragram:" message = "" while message != 'quit': message=input(prompt) print(message)执行结果:
在前一个实例中,我们让程序在满足指定条件时就执行特定地任务。但是在更复杂的程序中,很多不同的事件都会导致程序停止运行,此时,需要定义一个变量,用于判断整个程序是否处于活动状态,整个变量被称为标志。
例如:
prompt = "\n Tell me something,and i will repeat it back to you." prompt += "\n Enter 'quit' to end the pragram:" active = True while active: message=input(prompt) if message == 'quit': active = False else: print(message)输出结果:
可使用while循环提示用户输入任意数量的信息。下面创建一个调查程序,其中的循环每次执行时都提示输入被调查的名字和回答。
例如:
responses ={} #设置一个标志,指出调查是否继续 active = True while active: #提示输入被调查者的名字和回答 name = input("\n请输入您的名字:") location = input("\n请输入您的住址:") #将答案存储在字典中 responses[name] = location #看看是否还有人继续调查 repeat = input("\n would any other people respond:") if repeat == 'no': active = False #调查结果结束 print("\n-----------调查结果---------------") for name,location in responses.items(): print(name+"的住址是:"+location)输出结果:
