首页 > 解决方案 > 如何验证输入

问题描述

你好,我是使用 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 循环,如果可以的话。

标签: python-3.xperformancevalidation

解决方案


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

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)

推荐阅读