因此,我搜索了“string”、“python”、“validate”、“user input”等单词的几乎所有排列,但我还没有找到适合我的解决方案。
我的目标是提示用户是否要使用字符串“是”和“否”开始另一个事务,我认为在 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
我也尝试过
while userInput != 'yes' or userInput != 'no':
我不仅非常感谢能帮助解决我的问题,而且如果有人能提供有关 Python 如何处理字符串的任何其他信息,那就太好了。
如果其他人已经问过这样的问题,请提前抱歉,但我已尽力进行搜索。
谢谢大家!
~Dave
您正在测试用户是否输入is yes
or no
. Add a not
:
while userInput not in ['yes', 'no']:
稍微快一点、更接近你的意图,使用一组:
while userInput not in {'yes', 'no'}:
你用的是userInput in ['yes', 'no']
,即True
if userInput
要么等于'yes'
or 'no'
.
接下来,使用布尔值来设置endProgram
:
endProgram = userInput == 'no'
因为你已经验证了userInput
或者是yes
or no
, 无需测试yes
or no
再次设置您的标志变量。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)