1
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?

General Grievance
5,12039 gold badges40 silver badges60 bronze badges
asked Sep 2, 2020 at 11:58
2
  • 3
    Code works fine for me. I'd suggest you don't compare strings for ages and use numbers Commented Sep 2, 2020 at 12:03
  • i understand your advice but I want to compare ages Commented Sep 3, 2020 at 14:51

1 Answer 1

6

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:
answered Sep 2, 2020 at 12:01
Sign up to request clarification or add additional context in comments.

1 Comment

THANKS A LOT.I understood what I did wrong then @ShadowRanger

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.