python - 循环直到正确输入
问题描述
我是 Python 新手,必须为学校项目编写此代码。
当用户说“否”时,意味着他们不是美国的,我希望程序退出。当用户没有输入任何内容时,我希望它说“请输入 y 或 n”并继续显示此消息,直到他们正确响应。
while location == "":
location = input("Are you based in the US? Y/N ")
if location.upper().strip() == "Y" or location.upper().strip() == "YES":
print("Great to know you're based here in the states")
elif location.upper().strip() == "N" or location.upper().strip() == "NO": #when input is N or No display not eligible
print("Sorry to be our supplier you must be based in the US!")
quit() #stops program
else:
location = "" #if NZ based variable is not Y or N set NZ based variable to nothing
print("Type Y or N") #displays to user To type Y or N
解决方案
这里的基本思想是创建一个无限循环,只有在你得到你想要的输入时才打破它。正如您将要调用的那样upper
,strip
每次比较输入时,只要在获得输入时调用它们一次就足够了。
import sys
while True:
location = input("Are you based in the US? Y/N ").upper().strip()
if location in {"Y", "YES"}:
print("Great to know you're based here in the states")
break
elif location in {"N", "NO"}:
print("Sorry, to be our supplier you must be based in the US!")
sys.exit() # no need to `break` here as the program quits
else:
print("Type Y or N")
推荐阅读
- amazon-web-services - kibana 仪表板问题
- github - Bitbucket 到 github 的现有存储库迁移
- javascript - 如何设置 webpack 将资产路径转换为另一个路径?
- java - 如何使用 Java 中的 xmlet / XsdParser 验证 XML 是否与 XSD 匹配
- reactjs - 如何使用 muidatatable 的删除按钮?
- django - 向前端发送用户拥有的权限
- javascript - Nodejs:合并连接多个文件
- c# - System.Globalization.CultureInfo.CurrentUICulture 和 System.Threading.Thread.CurrentUICulture 有什么区别
- java - 关于 Hibernate bean 验证
- javascript - html5画布没有输出文本怎么办?