Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using in range(..) in an if-else statment

Tags:

python

python 2.7

Is it possible to do this:

print "Enter a number between 1 and 10:"
number = raw_input("> ")

if number in range(1, 5):
    print "You entered a number in the range of 1 to 5"
elif number in range(6, 10):
    print "You entered a number in the range of 6 to 10"
else:
    print "Your number wasn't in the correct range"

I find if I put a number between 1 to 10 it always falls to the else statement.

Is this an incorrect use of in range in an if-else statement?

Many thanks in advance,

like image 292
ant2009 Avatar asked Sep 02 '25 13:09

ant2009


2 Answers

It is because the input data is string. So it flows to else. Convert it into integer then all will be fine.

>>> number = raw_input("> ")
>>> type(number)
<type 'str'>
int(number) converts to <type 'int'>

Please use:

if int(number) in range(1, 6):
    print "You entered a number in the range of 1 to 5"
elif int(number) in range(6, 11):
    print "You entered a number in the range of 6 to 10"
else:
    print "Your number wasn't in the correct range"
like image 52
thegauraw Avatar answered Sep 05 '25 01:09

thegauraw


>>> number = raw_input()
3
>>> type(number)
<type 'str'>
>>> "3" in range(1,5)
False


number = int(raw_input())
like image 40
Karoly Horvath Avatar answered Sep 05 '25 01:09

Karoly Horvath