[英]Validating user input strings in Python
因此,我几乎搜索了单词“ string”,“ python”,“ validate”,“ user input”等的每个排列,但是还没有找到适合我的解决方案。
我的目标是提示用户是否要使用字符串“ 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']
userInput
,如果userInput
等于'yes'
或'no'
则为True
。
接下来,使用布尔值设置endProgram
:
endProgram = userInput == 'no'
因为您已经验证了userInput
是yes
或no
,所以不需要再次测试yes
或no
来设置您的标志变量。
def transaction():
print("Do the transaction here")
def getuserinput():
userInput = "";
print("Start")
while "no" not in userInput:
#Prompt for a new transaction
userInput = input("Would you like to start a new transaction?")
userInput = userInput.lower()
if "no" not in userInput and "yes" not in userInput:
print("yes or no please")
if "yes" in userInput:
transaction()
print("Good bye")
#Main program
getuserinput()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.