0

I wasn't really sure how to title my question, but my issue is this; I have my program set up to guess a number and handle exceptions. The program loops until the number is guessed, but when the program exits, my exception message shows at the same time. How can I fix this?

num = None
while num != 31:
    try:
        num = int(input("What is the age of my creator? \n"))
        if num < 31:
            print("Higher! Guess again! \n")
        elif num > 31:
            print("Lower! Guess again! \n")
        elif num == 31:
            print("Good Guess!")
            exit()
    except:
        print("Numbers only! \n")

This is my output:

What is the age of my creator? 31 Good Guess! Numbers only!

Process finished with exit code 0

1 Answer 1

1

If you want to keep the exception message, I would recommend a break instead of exit, for a more natural exit from your program. Try this:

try:
    ...
    elif num == 31:
        print("Good Guess!")
        break
except ValueError:
    print("Numbers only! \n")

Also, you should catch a specific error rather than a catch-all bare except.


If you want to silence any error messages, you should use pass instead. From the docs:

The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action.

try:
    ...
except ValueError:
    pass

pass is an innocuous placeholder statement that does nothing.


Sign up to request clarification or add additional context in comments.

8 Comments

I tried it. It changes nothing. This is my output: What is the age of my creator? 31 Good Guess! Numbers only! Process finished with exit code 0
@OrphaMortimer 1. No print statement after pass. 2. Save your file.
Also, I recommend break inside try, rather than exit.
I removed the print statement. The output looks better, but how could I do the same while keeping the exception print statement?
@OrphaMortimer Like I said, use a break instead of exit.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.