请求正确的输入,直到用python给出为止

请求正确的输入,直到用python给出为止,python,Python,我有一个代码,询问用户是否想玩游戏,他们要么按Y,要么按N。如果他们按Y,它会要求他们选择1到10之间的数字,如果他们按N,它会说哦,好的 但是我希望它再次询问用户输入是不是y或n。如果他们不按y或n,它会一次又一次地询问,直到他们按y或n #!/usr/bin/env python3 import random number = random.randint(1, 10) tries = 0 win = False # setting a win flag to false name

我有一个代码,询问用户是否想玩游戏,他们要么按Y,要么按N。如果他们按Y,它会要求他们选择1到10之间的数字,如果他们按N,它会说哦,好的

但是我希望它再次询问用户输入是不是y或n。如果他们不按y或n,它会一次又一次地询问,直到他们按y或n

#!/usr/bin/env python3

import random

number = random.randint(1, 10)
tries = 0
win = False # setting a win flag to false


name = input("Hello, What is your username?")

print("Hello" + name + "." )


question = input("Would you like to play a game? [Y/N] ")
if question.lower() == "n": #in case of capital letters is entered
    print("oh..okay")
    exit()
if question.lower() == "y":
    print("I'm thinking of a number between 1 & 10")


while not win:  # while the win is not true, run the while loop. We set win to false at the start therefore this will always run
    guess = int(input("Have a guess: "))
    tries = tries + 1
    if guess == number:
        win = True    # set win to true when the user guesses correctly.
    elif guess < number:
        print("Guess Higher")
    elif guess > number:
        print("Guess Lower")
# if win is true then output message
print("Congrats, you guessed correctly. The number was indeed {}".format(number))
print("it had taken you {} tries".format(tries))
#/usr/bin/env蟒蛇3
随机输入
number=random.randint(1,10)
尝试=0
win=False#将win标志设置为False
name=input(“您好,您的用户名是什么?”)
打印(“你好”+姓名+”)
问题=输入(“您想玩游戏吗?[Y/N]”)
如果question.lower()
打印(“哦……好的”)
退出()
如果问题.lower()=“y”:
打印(“我想的是一个介于1和10之间的数字”)
不赢时:#赢时不赢时,运行while循环。我们在开始时将win设置为false,因此这将始终运行
guess=int(输入(“有一个猜测:”)
尝试=尝试+1
如果guess==数字:
win=True#当用户正确猜测时,将win设置为True。
elif guess<数字:
打印(“猜测更高”)
elif guess>数字:
打印(“猜低”)
#如果win为真,则输出消息
打印(“恭喜,你猜对了。数字确实是{}”。格式(数字))
打印(“它花费了你{}次尝试”。格式化(尝试))

尝试将问题代码放入函数中。像这样:

def ask():
    question = input("Would you like to play a game? [Y/N] ")
    if question.lower() == "n": #in case of capital letters is entered
        print("oh..okay")
        exit()
    elif question.lower() == "y":
        print("I'm thinking of a number between 1 & 10")
    else:
        ask()

添加while循环以确保他们选择其中一个:

[..]
question = ''
while question.lower() not in ['n', 'y']:
    question = input("Would you like to play a game? [Y/N] ")

if question.lower() == "n": #in case of capital letters is entered
    print("oh..okay")
    exit()

# No need of else or elif here because 'n' answers will exit code.
print("I'm thinking of a number between 1 & 10")

[..]

对不起,压痕太差了。我相信你明白了。你可以编辑你的答案来修正它,而不是要求修正它,我修正了它。