-
概述
接收用户输入是程序的一个重要功能,而while循环可以让程序不断运行,直到判断条件不满足为止。
通过获取用户输入并学会控制程序的运行时间,可编写除交互式程序。 -
input()
##--------input() get string
message=input("Tell me something,and I will repeat it back to you: ")
print(message)
##--------input() get value
question="How old are you? "
age = input(question)
print(age)

可以将提示存储到变量中,再讲该变量传递给input()函数。
- while()
for循环用于处理集合中的每个元素,而while循环不断地运行,直到判断条件不满足为止。
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
prompt = "\nTell me something,and I will repeat it back to you: "
prompt += "\nEnter 'quit' to end the program.\n"
message = ""
while message != 'quit':#until to Not-meet
message =input(prompt)
print(message)

美中不足的是把quit也打印出来了,可以通过一个if判断修复这个问题。
prompt = "\nTell me something,and I will repeat it back to you: "
prompt += "\nEnter 'quit' to end the program.\n"
message = ""
while message != 'quit':#until to Not-meet
message =input(prompt)
if message !="quit":
print(message)
- break VS continue
break:立刻退出循环,不再运行循环中余下的代码,不管条件判断结果如何都退出整个循环。
任何python循环都可以使用break语句。
continue:返回到循环开头,并根据条件判断结果决定是否运行。
##==break
prompt = "\nTell me something,and I will repeat it back to you: "
prompt += "\nEnter 'quit' to end the program.\n"
while True:
city=input(prompt)
if(city=='quit'):
break
else:
print("I'd love to go to "+city.title()+" !")
##==continue
current_number=0
while current_number<10:
current_number+=1;
if current_number%2==0:
continue
else:
print(current_number)

while语句需要有停止运行的条件(如果需要停止的话),务必对每个 while循环进行测试。
如果程序陷入无限循环,按Ctrl+C可以停止,关机也好使。
- 使用while()
##==use while to get infomation
responses={}#dict
polling_active=True
while polling_active:
name=input("What's your name?\n")
response=input("Which mountain would you like to climb someday?\n")
responses[name]=response
repeat=input("Would you like to let another person respond?(yes/no)\n")
if repeat=='no':
polling_active=False

使用while进行调查,获取信息。
pets=['dog','cat','dog','goldfish','cat','rabbit','cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
删除包含特定值的列表元素。while一直等到pets中没有cat才退出。
就酱!
本文深入探讨了Python中while循环和input函数的应用,包括如何利用它们创建交互式程序,处理用户输入,以及如何通过break和continue控制循环流程。此外,还介绍了如何使用while循环进行数据收集和列表操作。
892

被折叠的 条评论
为什么被折叠?



