0

This is my first post in this community and I am a beginner of course. I look forward to the day I can help others out. Anyway, this is the a simple code and I would like it so that there is an error if the user enters a string. Unfortunately, it does not execute the way I'd like to, here's the code:

number = 1

guess = int(input('Guess this number: '))

while True:
    try:
        if guess > number:
            print("Number is too high, go lower, try again")
            guess = int(input('Guess this number: '))
        elif guess < number:
            print("Too low, go higher, try again")
            guess = int(input('Guess this number: '))
        else:
            print("That is correct")
            break
    except (SyntaxError, ValueError):
            print("You can only enetr numbers, try again")

When the program gets executed, and it asks me to "Guess this number: ", when I write any string e.g. "d", it gives the error:

Guess this number: d
Traceback (most recent call last):
  File "Numberguess.py", line 5, in <module>
    guess = int(input('Guess this number: '))
ValueError: invalid literal for int() with base 10: 'd'

Thank you for your time and support.

Lateralus
  • 792
  • 9
  • 19
  • Does this answer your question? [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – quamrana May 08 '20 at 18:08
  • int function expects an expression so that it is a valid integer and since is not a valid number it throws an error. If you want an ascii then use ord() function. – Harsh Prakash Agarwal May 08 '20 at 18:11

4 Answers4

0

I would just use .isdigit(). The string would be validated at that point and then you would turn it into an int if validation works.

guess = input('Guess this number: ')
if guess.isdigit():
    guess = int(guess)
else:
    print("You can only enter numbers, try again")

Also worth to mention that try/excepts are cool and they get the job done, but it's a good habit to try to reduce them to zero, instead of catching errors, validate data beforehand.

The next example would do it:

number = 1

while True:

    # Step 1, validate the user choice
    guess = input('Guess this number: ')
    if guess.isdigit():
        guess = int(guess)
    else:
        print("You can only enter numbers, try again")
        continue

    # Step 2, play the guess game
    if guess > number:
        print("Number is too high, go lower, try again")
    elif guess < number:
        print("Too low, go higher, try again")
    else:
        print("That is correct")
        break
Saelyth
  • 1,694
  • 2
  • 25
  • 42
0

Take a look at this line:

guess = int(input('Guess this number: '))

You try to convert string to int, it's possible, but only if the string represents a number.

That's why you got the error. The except didn't worked for you, because you get the input for the variable out of "try".

By the way, there is no reason to input in the if, so your code should look like this:

number = 1

while True:
    try:
        guess = int(input('Guess this number: '))

        if guess > number:
            print("Number is too high, go lower, try again")
        elif guess < number:
            print("Too low, go higher, try again")
        else:
            print("That is correct")
            break
    except (SyntaxError, ValueError):
            print("You can only enetr numbers, try again")

Deftera
  • 98
  • 1
  • 6
0

Welcome to Stack Overflow! Everyone needs to start somewhere

Take a look at the code below:

# import random to generate a random number within a range
from random import randrange


def main():
    low = 1
    high = 100

    # gen rand number
    number = gen_number(low, high)

    # get initial user input
    guess = get_input()

    # if user did not guess correct than keep asking them to guess
    while guess != number:
        if guess > number:
            print("You guessed too high!")
            guess = get_input()
        if guess < number:
            print("You guess too low!")
            guess = get_input()
    # let the user know they guess correct
    print(f"You guessed {guess} and are correct!")


def gen_number(low, high):
    return randrange(low, high)


# function to get input from user
def get_input():

    guess = input(f"Guess a number (q to quit): ")
    if guess == 'q':
        exit()

    # check to make sure user input is a number otherwise ask the user to guess again
    try:
        guess = int(guess)
    except ValueError:
        print("Not a valid number")
        get_input()

    # return guess if it is a valid number
    return guess


# Main program
if __name__ == '__main__':
    main()

This was a great opportunity to include Python's random module to generate a random number within a range. There is also a nice example of recursion to keep asking the user to guess until they provide valid input. Please mark this answer as correct if this works and feel free to leave comments if you have any questions.

Happy Coding!!!

Lateralus
  • 792
  • 9
  • 19
  • Using recursion to repeatedly ask for input is not one of the best ideas. In fact, it's a bad idea. A very bad idea. – Matthias May 08 '20 at 22:23
  • After `if __name__ == '__main__':` there should only be a call to a function`main` where the rest of the code should be. With your approach you add too much names to the global namespace. – Matthias May 08 '20 at 22:27
  • Kickin_Wing, thank you for your time and consideration of keepin the code simple. This community is great. I wish you a nice weekend! – chasetheidea May 08 '20 at 22:55
  • @chasetheidea Your most welcome! Best of luck to you, Python is a great language to learn. Have a nice weekend as well. – Lateralus May 08 '20 at 22:57
-1

the problem is in the first line. when you convert the input from the user directly to int, when a user inputs a letter, the letter cannot be converted to int, which causes the error message you get. to solve this you need to do

guess = input('Guess this number: ')
if not guess.isdigit():
    raise ValueError("input must be of type int")
Gal
  • 504
  • 4
  • 11
  • And what do you achieve with this code? `input` returns a string so `isinstance(guess, str)` will always be `True`. – Matthias May 08 '20 at 22:25