Amr Shawkat
Amr Shawkat

Reputation: 13

Python Elif statements

print("What is your age ?")
myAge = input()
if myAge <= "21" and myAge >= "18":
    print("You are allowed to drive !")
elif myAge > "21":
    print("You are too old to drive !")
elif myAge < "18":
    print("You are too young to drive !")

I wanted to ask whether the above python code has some fault in it? Whenever I type some numbers less than 18, the message "You are too old to drive !" appears although the number is less than 18.

With these lines of code, I want to create a program such that, whenever I type any number less than 18, a message "You are too young to drive !" appears using elif statements in python. Can someone help me in doing this?

Upvotes: 1

Views: 113

Answers (1)

ShadowRanger
ShadowRanger

Reputation: 155438

Strings compare lexicographically, so "2" through "9" are all greater than "18", because only the first character, "1", is being compared with them. You need to convert the user input to int and perform integer comparisons, e.g.:

print("What is your age ?")
myAge = int(input())  # Convert user input to int
if myAge <= 21 and myAge >= 18:
    print("You are allowed to drive !")
elif myAge > 21:
    print("You are too old to drive !")
elif myAge < 18:
    print("You are too young to drive !")

You can also (entirely optional) slightly simplify the first test; Python allows chained comparisons, so it's equivalent, slightly more readable (and infinitesimally faster code) to test:

if 18 <= myAge <= 21:

Upvotes: 6

Related Questions