use*_*870 2 python string validation input
所以我几乎搜索了"字符串","python","验证","用户输入"等字样的每个排列,但我还没有找到适合我的解决方案.
我的目标是提示用户是否想要使用字符串"yes"和"no"启动另一个事务,我认为字符串比较在Python中是一个相当简单的过程,但是有些东西不起作用对.我正在使用Python 3.X,因此据我所知,输入应该在不使用原始输入的情况下接受字符串.
即使输入"是"或"否",程序也会始终回放无效输入,但真正奇怪的是,每次输入一个字符串> 4个字符的长度或一个int值时,它会将其检查为有效的正值输入并重新启动程序.我还没有找到获得有效负输入的方法.
endProgram = 0;
while endProgram != 1:
#Prompt for a new transaction
userInput = input("Would you like to start a new transaction?: ");
userInput = userInput.lower();
#Validate input
while userInput in ['yes', 'no']:
print ("Invalid input. Please try again.")
userInput = input("Would you like to start a new transaction?: ")
userInput = userInput.lower()
if userInput == 'yes':
endProgram = 0
if userInput == 'no':
endProgram = 1
Run Code Online (Sandbox Code Playgroud)
我也试过了
while userInput != 'yes' or userInput != 'no':
Run Code Online (Sandbox Code Playgroud)
我非常感谢不仅帮助解决我的问题,而且如果有人有关于Python如何处理字符串的任何其他信息,那将是非常好的.
如果其他人已经问过这样的问题,请提前抱歉,但我尽力搜索.
谢谢大家!
〜戴夫
您正在测试,如果用户输入是 yes或no.添加一个not:
while userInput not in ['yes', 'no']:
Run Code Online (Sandbox Code Playgroud)
如此快一点,更接近你的意图,使用一套:
while userInput not in {'yes', 'no'}:
Run Code Online (Sandbox Code Playgroud)
你使用的是userInput in ['yes', 'no'],True如果userInput等于'yes'或等于'no'.
接下来,使用布尔值来设置endProgram:
endProgram = userInput == 'no'
Run Code Online (Sandbox Code Playgroud)
因为您已经验证了它userInput是yes或者no,所以不需要测试yes或no再次设置标志变量.
| 归档时间: |
|
| 查看次数: |
32414 次 |
| 最近记录: |