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,
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"
>>> number = raw_input()
3
>>> type(number)
<type 'str'>
>>> "3" in range(1,5)
False
number = int(raw_input())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With