-1

I have a code that is asking a user if they wanna play a game they either press Y or N. If they press Y it asks them to choose a number between 1 and 10 if they press N it says oh okay.

But I want it to ask again if the user input is not y or n. and if they dont press y or n it will ask again and again and again untill they press y or 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))
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Snozye
  • 27
  • 4

2 Answers2

0

Add a while loop to make sure they choose one of them:

[..]
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")

[..]
Cheche
  • 1,456
  • 10
  • 27
-1

Try putting your question code in a function. Like this:

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()
Alfe
  • 56,346
  • 20
  • 107
  • 159
Keith Cronin
  • 373
  • 2
  • 9