mutilenka
mutilenka

Reputation: 11

How to fix this guessing game loop problem?

The first round of the game works fine but once you reply with "Y" the computer's guess stays the same. It also doesn't stop the loop when you respond with "N". And also whenI recently started learning sorry if I have trouble understanding explanations. :)

from random import randint
comp_num = randint(1,10)
while True:
    guess = int(input("Pick a number 1-10 "))
    if comp_num == guess:
        print(f"You won, it was {comp_num}")
        b = input("Do you want to keep playing? Y/N")
        if b == "N":
            break
        elif b == "Y":
            comp_num = randint(1,10)
    elif guess < comp_num:
        print("too low try again")
    elif guess > comp_num:
        print("too high try again")

Pick a number 1-10 3
You won it was 3
Do you want to keep playing? Y/Ny
Pick a number 1-10 3
You won it was 3       it still remains 3 after the 100th try
Do you want to keep playing? Y/Nn
Pick a number 1-10     it continues to ask for input

Upvotes: 1

Views: 103

Answers (2)

Roland Weber
Roland Weber

Reputation: 3675

Try to enter Y instead of y. You only check for uppercase letters, and keep running an endless loop if input is neither Y nor N.

Upvotes: 2

blackbrandt
blackbrandt

Reputation: 2095

from random import randint
comp_num = randint(1,10)
while True:
    guess = int(input("Pick a number 1-10 "))
    if comp_num == guess:
        print(f"You won, it was {comp_num}")
        b = input("Do you want to keep playing? Y/N").lower() ## <<<<---- See here
        if b == "n":
            break
        elif b == "y":
            comp_num = randint(1,10)
        else:
            print("Not a valid choice!")
    elif guess < comp_num:
        print("too low try again")
    elif guess > comp_num:
        print("too high try again")

Change the input to lowercase, and compare to lowercase. Now you won't have the case issue.

Upvotes: 1

Related Questions