我有一个代码询问用户是否要玩游戏,请按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))
答案 0 :(得分:0)
添加一个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")
[..]
答案 1 :(得分:-1)
尝试将您的问题代码放入函数中。像这样:
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()