0

In the below python code

    var=input("Enter a number between 1 to 10:")
    if (var==1 or var==2 or var==3 or var==4 or var==5):
          print ('the entered number is between 1 to 5')
    elif (var==6 or var==7 or var==8 or var==9 or var==10):
          print ('The entered number is between 5 to 10')
    else:
          print ('Wrong value exiting!!')

When i run it in terminal~$ python name.py

Enter a number between 1 to 10:3

the entered number is between 1 to 5

when i run it in terminal~$ python3 name.py

Enter a number between 1 to 10:3

Wrong value exiting!!

What makes the difference ? & what i have to change in order to get the correct output when i compile with python3`?


is there any simpler way of comparison instead of using "or" for every number ?

2 Answers 2

4

In Python 2:

var=input("Enter a number between 1 to 10:")

The above evaluates the expression, so it ends up with var potentially equalling a number. (And as a note should really be avoided)

In Python 3, input is the equiv. of raw_input in Python 2, so it returns a string - if you expect it to be a number you need to do var = int( input("...") ) and be aware of any conversion errors that may occur:

There is the in operator:

if var in (1, 2, 3, 4, 5):
    pass
elif var in (6, 7, 8):
    pass
else:
    pass

Or, if you want a between operation, you can make use of the Python logic system:

if 1 <= var <= 5:
    pass
Sign up to request clarification or add additional context in comments.

Comments

2

I believe this is due to your use of input - in Python 3.x, it is the same as raw_input in Python 2.x, meaning that it is turning it into a string as opposed to an integer. As for your comparison, you could try using range:

var=int(input("Enter a number between 1 to 10:"))

if var in range(1, 6):
      print ('the entered number is between 1 to 5')
elif var in range(6,11):
      print ('The entered number is between 5 to 10')
else:
      print ('Wrong value exiting!!')

5 Comments

To get the old behavior of input(), you can use eval(input())
@PaoloMoretti For gods sake, don't give OP ideas!
@MarkusUnterwaditzer Haha, after all of the warnings against eval I've seen on this site, I'm afraid to even type it.
At the very least - ast.literal_eval(input())
@Markus You are rigth, I was just quoting the official py3k release notes. Using eval() is really a bad practice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.