【发布时间】:2013-05-14 03:48:00
【问题描述】:
所以我搜索了“字符串”、“python”、“验证”、“用户输入”等单词的几乎所有排列,但我还没有找到适合我的解决方案.
我的目标是提示用户是否要使用字符串“yes”和“no”开始另一个事务,我认为字符串比较在 Python 中将是一个相当简单的过程,但有些东西只是工作不正常。我使用的是 Python 3.X,所以据我所知,输入应该是一个字符串而不使用原始输入。
即使输入'yes'或'no',程序总是会回退无效输入,但真正奇怪的是,每次我输入一个长度> 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
我也试过
while userInput != 'yes' or userInput != 'no':
我将不胜感激,不仅可以帮助我解决我的问题,而且如果有人有任何关于 Python 如何处理字符串的额外信息,那将是非常棒的。
如果其他人已经问过这样的问题,请提前抱歉,但我已尽力搜索。
谢谢大家!
~戴夫
【问题讨论】:
标签: python string validation input