x = int(input("Guess my favorite number\n"))
y = 69
num = int(x)
if num == y :
print ("CORRECT :BINGOOOO")
if y%2 == 0 :
print('INCORRECT : the number is definitely even')
print ('INCORRECT : the number is f*cking odd')
if num < y :
print("Your number is less than mine")
elif num > y :
print ("Your number is more than mine...")
print ("Enter a number la stupid ass")
Question is why ain’t my code gives out the ERROR as the keyword ‘except’ states? Maybe I don’t understand the concept here, pls help
The conversion to
int on line 1 is outside the
try: except: block.
The second conversion on line 4 is inside and would work, but it never reaches that point.
Why the second conversion doesn’t work? What do you mean by it doesnt ‘reach’ that point? What’s the logic here? (and yes thank you It did work after I pasted it inside the TRY block but now I do wanna understand the logic)
The lines are executed one by one from top to bottom.
The first line is executed first.
There you input something and that input is converted to a number.
If that conversion fails (because you didn’t enter a number) an exception is raised (an error happens).
This means instead of continuing with the next lines it jumps directly to a
except: clause if it is in a
try: block. If it can not find such a
try: except: the program is aborted and some information about the error is printed.
Oh so basically the input needs to be in the try and except block because it detects what we input first then it executes. If its outside such a block then it won’t detect the ‘conversion failure’. I understand, thanks for the information :)))
Your script will crash out, if the user does not enter an integer at the input, so that’s where your
try/except block should start (as Peter has pointed out), but more on that in a moment.
The other way to do this, would be to let the
input() function return whatever the user enters and then try the type conversion.
x? You have the ability to use descriptive names, so why not use such:
user_input = input("Guess my favorite number:> ")
Now, you can try the type conversion, but don’t do a general exception, rather, you should only be catching the
ValueError, so simply do:
number = int(user_input)
print("An integer is required.")
… and keep the logic (the
if/else branch) outside of the
There is a way to continue to ask for the user input, if an integer is not entered, or the guess is not correct, and you could also limit the guesses to so many attempts, but I’ll let you have a go at that, rather than do the work for you; post back if you get stuck.