-1

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?

Marievi
  • 4,951
  • 1
  • 16
  • 33

2 Answers2

3

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'>
Blender
  • 289,723
  • 53
  • 439
  • 496
2

You need to cast it to int -

 num = int(raw_input("Enter the number :"))

As raw_input read line and converts it to string .

ameyCU
  • 16,489
  • 2
  • 26
  • 41
  • Just of of curiosity, why is this not an error? I can't think of a scenario where it makes sense to compare a string to a number. – Carcigenicate Apr 30 '16 at 16:24
  • 1
    @Carcigenicate You can find more details about this here: [How does Python compare string and int?](http://stackoverflow.com/questions/3270680/how-does-python-compare-string-and-int) – AKS Apr 30 '16 at 16:28
  • 1
    @Carcigenicate That generates an error in Python 3 and above versions. – ameyCU Apr 30 '16 at 16:29