0

I am very knew to Python, so as expected, I'm encountering problems often when scripting and am usually not sure how to fix them.

I'm making a small game where you try and guess a number which the program has randomly chosen. I've gotten pretty far, but I noticed the program simply displayed an error message when I input nothing. I would like the program to display the text "Enter a number." in this situation, and then prompt the "Your guess: " input again, but after a lot of research, I'm really not sure how to successfully implement that feature into my code. My issue, specifically, is the "try and except" section - I don't really know how to write them properly, but I saw another post on here suggesting to use them.

import random

def question():
    print("Guess a number between 1 and 100.")
    randomNumber = random.randint(1, 100)
    found = False

    while not found:
        myNumber = int(input("Your guess: "), 10)
        try:
            myNumber = int(input("Your guess: "), 10)
        except ValueError:
            print("Enter a number.")

        if myNumber == randomNumber:
            print("Correct!")
            found = True
        elif myNumber > randomNumber:
            print("Wrong, guess lower!")
        else:
            print("Wrong, guess higher!")

question()

You should be able to see my intentions in the code I've written, thanks.

4 Answers 4

1

You're almost right. Just continue to the next iteration after handling exception.

import random

def question():
    print("Guess a number between 1 and 100.")
    randomNumber = random.randint(1, 100)
    found = False

    while not found:
        try: 
            myNumber = int(input("Your guess: "), 10)
        except Exception:
            print('Enter a number.')
            continue

        if myNumber == randomNumber:
            print("Correct!")
            found = True
        elif myNumber > randomNumber:
            print("Wrong, guess lower!")
        else:
            print("Wrong, guess higher!")

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

5 Comments

Olexander beat me to it. I would add that you probably need to catch other exceptions (e.g. SyntaxError) to handle the case when an empty line is entered. You could do something like except (ValueError, SyntaxError):. Or to be safe, you can catch any exception by using except Exception:.
I agree here. Catching all exceptions with except Exception might be better in this case. Edited answer.
you know, the questioner is on python 3. So use input() instead raw_input() :)
Thank you so much! It was really frustrating, can't believe the fix was so simple. Also, you mention about using SyntaxError (or Exception) to handle the case when an empty line is entered. However, using both ValueError and SyntaxError/Exception, the program handles entering an empty line in the same way (by following the continue statement). Why is that?
The program handles all exceptions the same way if catching Exception because Exception is superclass for both ValueError and SyntaxError, so no matter what type of exception you catch exactly, they all of Exception class. In real code you shouldn't use general Exception type, since you probably want to handle different errors in a different way, but it works fine if we wan't to catch all exception at once.
0

You can write a function like this:

def input_num(input_string):
    """ This function collects user input

    Args:
        input_string: message for user

    Return:
        user_input: returns user_input if it is a digit
    """

    user_input = raw_input("{}: ".format(input_string))
    if not user_input.isdigit():
        input_num(input_string)
    return int(user_input)

then call this function

user_num = input_num("Enter a number")

It will keep asking a user to provide a valid input until user puts one

Comments

0

I'm confused why you ask for the input twice. You only need to ask them for input once. After that, you need to add a continue to your except statement. Otherwise, it will not repeat and just end the program. This is what your modified while loop should look like.

while not found:
    try:
        myNumber = int(input("Your guess: "), 10)
    except ValueError:
        print("Enter a number.")
        continue

    if myNumber == randomNumber:
        print("Correct!")
        found = True
    elif myNumber > randomNumber:
        print("Wrong, guess lower!")
    else:
        print("Wrong, guess higher!")

Comments

0

Just use the continue keyword in your except to continue the loop.

except ValueError: print('Enter a number') continue

Comments

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.