1、举个例子,你可以使用while()循环来数数:
current_number=1
while current_number<=5:
print(current_number)
current_number+=1
从1数到5:
1
2
3
4
5
2、那么如何让用户选择何时退出呢?
prompt="\nTell me something, and I will repeat it back to you:"
prompt+="\nEnter 'quit' to end the program."
message=""
while message!='quit':
message=input(prompt)
print(message)
这里我们定义了一条提示消息,告诉用户他有两个选择:要么输入一条消息,要么输入退出值(这里是quit)
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program.Hello everyone1
Hello everyone1
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program.Hello again
Hello again
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program.quit
quit
Process finished with exit code 0
3、使用bresk退出循环
要立即退出while循环,不再运行循环中的余下代码,也不管条件测试的结果如何,可使用break语句
prompt="\nPlease enter the name of a city you have visited: "
prompt+="\n(Enter 'quit' when you are finished)"
while True:
city=input(prompt)
if city=='quit':
break
else:
print("I'd love to go to "+city.title()+"!")
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished)new york
I'd love to go to New York!
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished)san francisco
I'd love to go to San Francisco!
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished)quit
Process finished with exit code 0
4、在循环中使用continue
要返回到循环的开头,并根据条件测试结果决定是否继续执行循环,可使用continue语句,它不像break语句那样不再执行余下代码并退出整个循环
current_number=0
while current_number<10:
current_number+=1
if current_number%2==0:
continue
print(current_number)
结果:
1
3
5
7
9