2013-05-19 46 views
2

所以我搜索了几乎每个字串“python”,“验证”,“用户输入”等字样的排列,但我还没有碰到一个为我工作的解决方案。验证用户输入字符串在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如何处理字符串,将是巨大的任何其他信息。

对不起,如果其他人已经问过这样的问题,但我尽我所能搜索。

谢谢大家!

〜戴夫

回答

8

您正在测试,如果用户输入yesno。添加not

while userInput not in ['yes', 'no']: 

非常轻微更快,更接近你的意图,使用一组:

while userInput not in {'yes', 'no'}: 

你使用的是什么userInput in ['yes', 'no'],这是True如果userInput或者是等于'yes''no'

接下来,使用一个布尔值来设置endProgram

endProgram = userInput == 'no' 

因为你已经验证了userInput或者是yesno,没有必要来测试yesno重新设置你的标志变量。

+0

哇。这样一个简单的错误。感谢您的及时回复。我想有时你只需要第二双眼睛来发现事物。 – user2398870

+0

作为一个方面说明,你能帮我学习为什么我的原始方法虽然userInput!='yes'或userInput!='no':不起作用吗? – user2398870

+0

@ user2398870:如果'userInput'设置为''yes'',那么'!='no''为真。这不是你想要测试的。 :-)更改'或'为'和'会使该版本正常工作。 –

1
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()