как проверить ввод - PullRequest
0 голосов
/ 11 мая 2019

привет, я новичок в программировании на 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 голосов
/ 11 мая 2019

Вы можете определить отдельную функцию для проверки и использовать ее где угодно

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)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...