[英]How to exit a while-loop with the value of an input which is inside another while-loop?
[英]Input combined with a while-loop
我为自己创建了很多简单的函数和程序; 这是我喜欢使用的功能之一,因为它很简单。
answer = True
while answer:
user = input ("name: ")
if user == "John":
answer = False
else:
print ("who are you ?")
该函数完成了我需要它做的一切。 while 循环一直持续到给出正确答案。 由于我仍然是初学者,我想知道这是否是好的编码风格,或者是否有更优雅的方式来做到这一点。
任何意见或提示将不胜感激。
谢谢。
您可以通过尝试实现相同的功能:
while True:
user = input ("name: ")
if user == "John":
break
else:
print ("who are you ?")
你也可以试试这个:
while True:
user = input ("name: ")
if user != "John":
print ("who are you ?")
else:
break
在这两种实现中, while True:
用于运行无限循环,如果满足指定条件,则使用break
退出循环。
您可以通过键入break
语句来实现您想要做的事情, break
将中断循环并继续。
尝试这个:
while True:
user = input ("name: ")
if user == "John":
break
else:
print ("who are you ?")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.