首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何验证输入

如何验证输入
EN

Stack Overflow用户
提问于 2019-05-12 01:27:08
回答 1查看 29关注 0票数 0

你好,我是用python编程的新手,我安排了这段代码,这样一个while循环就可以在程序的开始和前述变量的重新计算中验证Gamble变量。我如何才能使程序按原样工作,而不需要编写两次?

代码语言:javascript
复制
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循环。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-12 01:41:55

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

代码语言:javascript
复制
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      

然后,您的代码将如下所示:

代码语言:javascript
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56092696

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档