0

I'm a fairly new to python, and I have an assignment to make a random number guesser. I have everything working, but I want to filter out the arguments that break the code, like putting in nothing or letters.

Here's the code.

#import random from python libraries
   from random import randint
#generate random integer
   comp_Num = randint(1, 1000)

#creates an infinite loop
    while True:
#allow user to input number int() turns the str into an int
    user_Num = int(input("Guess a number between 1 and 1000 \n" ))
#if user number bigger than computer number
    if user_Num > comp_Num:
        print("Too high! Guess again")

else:
    #if user number smaller than computer number 
          if user_Num < comp_Num:
              print("Too low! Guess again")

    #if user number equal to computer number
        if user_Num == comp_Num:
              print("Well done!")
              #end loop
              break

Sorry if the questions a bit simple! Thanks for the help!

Hollow
  • 3
  • 2

1 Answers1

0

There's two ways to go about this:

  1. You prevent the exception. In your case that can be done with the .isdigit() string method, which returns True if all characters in the string are digits and there is at least one character, False otherwise.
  2. You handle the exception with try-except.
Adrien Levert
  • 964
  • 6
  • 15
  • How do I use try-except on this particular issue? – Hollow Oct 15 '21 at 21:01
  • The second paragraph of [this link I put in the answer](https://docs.python.org/3/tutorial/errors.html#handling-exceptions) explain it thoroughly, but in a nutshell: you add the `try` around the code that can cause exceptions (here it's the `user_Num` assignment that can cause a ValueError) and then follow it up by `except` where you can print a warning. *If this answered your question don't forget to accept it. – Adrien Levert Oct 15 '21 at 21:12
  • thanks for the help! – Hollow Oct 21 '21 at 16:48