0

I'm working through a beginners python tutorial and i'm attempting to do a little bit more than the tutorial asks for by adding conditions to the options

elif option == "2":
    print "Choose a number for opt 2"
    var_in = raw_input("> ")

    if  0 < var_in < 5 or 1 <= var_in < 5:
        print "between 1-5"
    elif var_in == "0": #works
        print "Zero"
    else:
        print "Greater than 5!" #works

If i enter anything other than 0 for var_in i get the message "Greater than 5!".

I also tried using:

elif option == "2":
    print "Choose a number for opt 2"
    var_in = raw_input("> ")

    if  var_in in range(1, 5):
        print "between 1-5"
    elif var_in == "0": #works
        print "Zero"
    else:
        print "Greater than 5!" #works

Which had the same results as above.

Any assistance would be much appreciated. Thanks!

NULLZ
  • 121
  • 2
  • 8
  • Why do you test both `0 < var_in < 5` and `1 <= var_in < 5`? It's redundant. (Also, once you fix the string/int comparison bug, you're going to have a program that claims that 5 is greater than 5.) – user2357112 Jul 23 '13 at 01:31

2 Answers2

1

var_in is a string, not an integer. You shoud do it as:

try:
    var_in = int(raw_input("> "))
except:
    print "Incorrect input."
else:
    if  0 < var_in <= 5 :
        print "between 1-5"
    elif var_in == 0: #works
        print "Zero"
    else:
        print "Greater than 5!" #works
Sheng
  • 3,467
  • 1
  • 17
  • 21
  • I haven't used 'try' and 'except' before. I assume that means that if an int is not entered it'l fail with the error? – NULLZ Jul 23 '13 at 01:36
  • Instead of using a blanket `except`, might I recommend `except ValueError`? It is better practice to only catch the exceptions you are anticipating. – SethMMorton Jul 23 '13 at 01:37
  • @D3C4FF If your string cannot be converted to an `int`, Python raises a `ValueError`. A `try: except:` block can be used to catch this error and provide an alternate execution path. – SethMMorton Jul 23 '13 at 01:38
  • @SethMMorton Yes, except ValueError is more accurate. The only "except" catch all kinds of excpetions. – Sheng Jul 23 '13 at 01:42
  • 1
    @D3C4FF: If the system fails to convert the input into integer, the except block would be executed. – Sheng Jul 23 '13 at 01:43
1

raw_input returns a string. You can't meaningfully compare strings with numbers; Python 2 will give you a meaningless result, and Python 3 will TypeError. Turn it into an int before you do the comparisons:

user_input = int(raw_input('> '))
user2357112
  • 260,549
  • 28
  • 431
  • 505