如何验证输入

时间:2019-05-11 17:27:08

标签: python-3.x performance validation

您好,我不熟悉python编程,所以安排了这段代码,以便while循环可以在程序开始时以及对上述变量进行重新评估时验证Gamble变量。我如何才能使程序按原样工作,但无需编写两次?

def gamBling(Gamble):

        while Gamble == 'yes' or Gamble == 'Yes' or Gamble == 'y' or Gamble =='Y': 
             betTing()

             Gamble = input('Do you wish to play again? ')
             while  Gamble != 'yes' and Gamble != 'Yes' and Gamble != 'y' and Gamble != 'Y' and Gamble != 'No' and Gamble != 'no' and Gamble != 'N' and Gamble != 'n': 
                  Gamble = input('Please anwser in either yes or no? ')

        if Gamble == 'No' or Gamble == 'N' or Gamble == 'n' or Gamble == 'no': 
             print('okay, goodbye')
             exit()
print('Any bet you make will be doubled if your number is higher than or equal to 5. Want to play? ' + '(Yes or No)')

Gamble = input() 


while  Gamble != 'yes' and Gamble != 'Yes' and Gamble != 'y' and Gamble != 'Y' and Gamble != 'No' and Gamble != 'no' and Gamble != 'N' and Gamble != 'n': 

        Gamble = input('Please anwser in either yes or no? ')

gamBling(Gamble)

我希望能够以现在的方式运行程序,但如果可以的话,而不必重复while循环。

1 个答案:

答案 0 :(得分:0)

您可以定义一个单独的验证函数,并在需要的任何地方使用

def validate(Gamble):
    while  Gamble != 'yes' and Gamble != 'Yes' and Gamble != 'y' and Gamble != 'Y' and Gamble != 'No' and Gamble != 'no' and Gamble != 'N' and Gamble != 'n': 
        Gamble = input('Please anwser in either yes or no? ')
    return Gamble      

然后您的代码将类似于:

def gamBling(Gamble):

    while Gamble == 'yes' or Gamble == 'Yes' or Gamble == 'y' or Gamble =='Y': 
         betTing()
         Gamble = input('Do you wish to play again? ')
         Gamble = validate(Gamble)

    if Gamble == 'No' or Gamble == 'N' or Gamble == 'n' or Gamble == 'no': 
         print('okay, goodbye')
         exit()

print('Any bet you make will be doubled if your number is higher than or equal to 5. Want to play? ' + '(Yes or No)')
Gamble = input() 
Gamble = validate(Gamble)
gamBling(Gamble)