Reputation: 33
I don't understand why when the user enters "0" the loop won't exit.
def floatInput():
done = False
while not done:
integerIn = input("Please enter an integer < 0 to finish >: ")
try:
integerIn = int(integerIn)
except:
print("I was expecting an integer number, please try again...")
import sys
sys.exit()
if integerIn == "0":
done = True
else:
integers.append(integerIn)
return integers
Upvotes: 2
Views: 114
Reputation: 69
def floatInput():
done = False
while not done:
integerIn = input("Please enter an integer < 0 to finish >: ")
try:
integerIn = int(integerIn)
except:
print("I was expecting an integer number, please try again...")
import sys
sys.exit()
Everything above here is fine, but as soon as you got to the comparison, you forgot that you've casted the input to an int.
if integerIn == "0":
Should be
if integerIn == 0:
Upvotes: 2
Reputation: 71
EDIT: screw the advice about using input
or raw_input
. Just saw you python 3.x tag, but decided to leave it for future readers.
You have few problems there...
First, in this line:
integers.append(integerIn)
where is integers
to begin with? unless it's a global name you must define it in your function.
Second, in this line:
if integerIn == "0":
you're comparing integer to string here, and here's a thing: in python (using python 2.7 here) a string will be bigger than any number if you're doing a comparison, so integerIn == "0"
will evaluate to False
, always.
Fix it with this:
if integerIn == 0:
Finally, I should tell you this... your code the way it looks like will throws NameError
instead of executing what you've done in your except
statement.
Try it with the following test cases and try to explain the behavior yourself :)
Please enter an integer < 0 to finish >: test
Please enter an integer < 0 to finish >: "test"
To avoid such problem next time, use raw_input
instead of input
. So this line:
integerIn = input("Please enter an integer < 0 to finish >: ")
should be like this:
integerIn = raw_input("Please enter an integer < 0 to finish >: ")
NOTICE: I'm not sure but I think raw_input
doesn't exist in python 3.x, instead input
there will do exactly the same. please correct if I'm wrong.
However, If you're using python 3 then I think you should have no problem.
Here's input
vs raw_input()
in python 2.x:
input
will evaluate the user input then return it.
raw_input
will return the user input as string.
so:
# python 2.x
foo = input("input something") # input 3 + 5
print foo # prints 8
bar = raw_input("input something") # input 3 + 5
print bar # prints "3 + 5"
Upvotes: 1
Reputation: 25
The reason is because integerIn
is an integer and you are treating it like a string in if integerIn=="0"
. Replace it with integerIN==0
will do the job.
Upvotes: 2
Reputation: 11615
You're converting to an integer and then checking for equality with the string "0".
Upvotes: 1