Reputation: 1191
I am totally going insane over this function I wrote, the while loop wont work for the love of god
while (something something):
print("at anytime enter 0 for both origin and destination to exit the game")
o=input("Enter origin stool's index (Must be int) ")
d=input("Enter destination stool's index (Must be int) ")
if isinstance(o,int) and isinstance(d,int):#if input d,o are int
#do bla bla
elif o==0 and d==0:#to exit manually
print("Exiting Manually...")
break
elif not (isinstance(o,int) and isinstance(d,int)):
print ("Invalid entry, exiting...")
break
The code should exit when o
AND d
are 0, and it should also exit when o
OR d
is not an int
However it seems that it doesn't matter what I enter, (i tried 0,0 and 0,1) it returns invalid entry, exiting...
Whats wrong with the conditions?
Upvotes: 0
Views: 97
Reputation: 17168
In Python 3, the input
function always returns a string. It doesn't eval
the user input like it used to do in Python 2. As a result, o
and d
are both strings, not integers. You need to wrap your input
calls with int(input('...'))
in order to turn them into ints, so your conditionals have a chance of success.
In this case, if the user inputs values that aren't numbers, the int
call should fail with a ValueError
. The standard way to deal with this is to wrap any calls to user input with a try
-except
block, to deal with users who provide bad input. So the relevant part of your code might look something like this:
try:
o=int(input("Enter origin stool's index (Must be int) "))
d=int(input("Enter destination stool's index (Must be int) "))
except ValueError:
print("Invalid entry, exiting...")
break
As a side note, your logic in the conditionals is kind of weird/broken. Your first conditional checks whether a
and d
are both ints, and then does processing. Then your next conditional (the first elif
block) tries to compare those to 0
, which will always fail since if you get to that test, that means the first conditional failed, so they weren't both ints and therefore can never be equal to 0
.
Upvotes: 4
Reputation: 1541
Your first "if" will pass when o and d are ints regardless of their values. Only if that condition fails will it continue through to the next "elif".
Try something more like:
if isinstance(o,int) and isinstance(d,int) and (o != 0 or d != 0):
#Conditions met, carry on
else:
break
Upvotes: 0