Skip to content Skip to sidebar Skip to footer

Python Input Does Not Compare Properly

I did this on test today and came back to test it. I know better ways to do this but why is this not working? def f(): e=raw_input('enter number') if e in range (12):

Solution 1:

e is a string and you compare it to an int

do

def f():
    e=int(raw_input('enter number'))
    if e in range (12):
        print 'co'
    elif e in range (12,20):
        print 'co2'
    elif e in range (-10,0,1):
        print 'co3'

f()

instead


Solution 2:

e=raw_input('enter number') should be e=int(raw_input('enter number')) Unlike input(), raw_input() simply returns the input as a string, irrespective of what the input is. Since range(12) consists of the integers 0-11 inclusive but e is not an integer, e will never be in range(12). Thus e needs to be converted into an integer. Fortunately, there is a built-in function for that: int().


Post a Comment for "Python Input Does Not Compare Properly"