Issue
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!
Solution
There's two ways to go about this:
- You prevent the exception. In your case that can be done with the
.isdigit()
string method, which returnsTrue
if all characters in the string are digits and there is at least one character,False
otherwise. - You handle the exception with try-except.
Answered By - Adrien Levert Answer Checked By - Mildred Charles (PHPFixing Admin)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.