Skip to content
Advertisement

if statement loops and while loops

number = int(input("please choose your number: ")) 

while number > number_to_guess: 
    number = int(input("Your guess is wrong it was bigger then the generated number, try again: "))
while number < number_to_guess : 
     number = int(input("Your guess was wrong it was smaller then the generated number, try again: "))

if number == number_to_guess:
    print("Congrats you won")
    restart = input("Do you want to play again? if yes type y, if not you can close the window n")

I’m trying to create a loop and give clues of the number the user has to guess I first tried if statements and it of course didn’t loop and I tried multiple things this was the best I could come up with but it didn’t exactly work it would keep telling me for example: it was smaller but when it became bigger it just stopped and the program didn’t send anything but if I got the number correctly it will say congrats, and also I wanted to make it restart from the beginning after the user wins and type y but I have absolutely no idea of how to do that

Advertisement

Answer

Try in this order

number = int(input("please choose your number: "))
number_to_guess = 5
while number != number_to_guess:
    if number > number_to_guess:
        number = int(input("Your guess is wrong it was bigger then the generated number, try again: "))
        continue
    if number < number_to_guess :
        number = int(input("Your guess was wrong it was smaller then the generated number, try again: "))
        continue
print("Congrats you won")
restart = input("Do you want to play again? if yes type y, if not you can close the window n")

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement