0

I'd like someone to help me figure out why the "if guess == 'exit' break" line is ignored in my code. It is supposed to break if the value entered is exit. The following is my code:

import random
#initializing random class

number = random.randint(1, 9)
print("Welcome to the Guessing Game!")

#asking user to write there preferred username

name = input("What is your name? ")

# asking the player to decide if they want to play the game or not by choosing yes/no

play = input("{}, Would you like to play the guessing game? (Enter Yes/No) ".format(name))

loop starts here. If the user selected a yes, the loop runs

while play.lower() != "no":
    try:
        guess = 0
        count = 0

        while guess != number and guess != "exit":
            guess = input("{}, What is your guess? ".format(name))
            # this block is supposed to run if the user enters exit as the guessed number

            if guess == "exit":
                break
     # Converting user input to an integer and incrementing count
            guess = int(guess)
            count += 1
  # this section evaluates the number guessed to either greater than, less than or equal to the 
     number
            if guess < number:
                print("Your guess is too Low {}, please try again".format(name))
            elif guess > number:
                print("Your guess is too High {}, please try again".format(name))
            else:
                print("Congrats {}! You guessed the correct number".format(name))
                print("And it took you ", count, " tries")
# captures value errors

    except ValueError as err:
        print("Oh no! The value you entered is out of range")
        print("({})".format(err))

# runs if the user selects no

else:
    print("Please try again later")

1 Answers1

0

You can use another break from the outer loop if guess is exit since the object guess is available to the outer loop.

while play.lower() != "no":
    try:
        guess = 0
        count = 0

        while guess != number and guess != "exit":
            # remove content of while loop for brevity 

        # another exit in the outer loop
        if guess == "exit":
            break

    except ValueError as err:
        print("Oh no! The value you entered is out of range")
        print("({})".format(err))

# runs if the user selects no

else:
    print("Please try again later")

Ideally, you should try to refactor your code to write code in functions and use return statement.

Krishna Chaurasia
  • 8,924
  • 6
  • 22
  • 35