所以我几乎搜索了“字符串”、“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 如何处理字符串的任何其他信息,那将是非常好的。
如果其他人已经问过这样的问题,请提前道歉,但我已尽力搜索。
谢谢大家!
~戴夫
最佳答案
您正在测试用户输入是否是 yes
或 no
.添加 not
:
while userInput not in ['yes', 'no']:
稍微快一点,更接近你的意图,使用一组:
while userInput not in {'yes', 'no'}:
你用的是userInput in ['yes', 'no']
,即 True
如果userInput
等于'yes'
或 'no'
.
接下来,使用 bool 值设置endProgram
:
endProgram = userInput == 'no'
因为您已经验证了 userInput
是 yes
或 no
, 不需要测试 yes
或 no
再次设置您的标志变量。
关于python - 在 Python 中验证用户输入的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16635073/