Marievi Marievi - 7 months ago 10
Python Question

python if-else only goes to else part

I have the following simple code, which checks the user input.

while True:
num = raw_input("Enter the number :")
if (num >= 1 and num <= 5):
break
else:
print "Error! Enter again :"


When I give as input
0
or numbers greater than
5
it works correctly, but then I try to give an input from
1
to
5
and the program still goes to the
else
part. Could you help me to find my error?

Answer

num is a string, not a number. You need to convert the return value of raw_input into a number first with int():

>>> n = raw_input('Type stuff: ')
Type stuff: 123
>>> type(n)
<type 'str'>
>>> n
'123'
>>> int(n)
123
>>> type(int(n))
<type 'int'>
Comments