简体   繁体   中英

I think my if else statement is not working

This is the Code

Age = int(input("Enter Your Age: "))
    if (Age > 18):
        print("Your are 18+")
        pass
    if (Age == 18):
        print("Your are 18")
        pass
    else:
        print("You are below 18")

This is the Output

Enter Your Age: 20
Your are 18+
You are below 18
  1. When Age > 18 it should print "Your are 18+"
  2. When Age == 18 it should print "Your are 18"
  3. When Age < 18 it should print "Your are below 18" What is happening here?

Use if elif else ladder. Don't use pass . pass is when you do nothing inside a branching condition.

In your code,

  1. Given input 20, the first if gets evaluated. As it's true, the print statement gets executed.
  2. Second if will get executed. As it's false , the condition is false, it won't go inside the if block.
  3. Next it will go to else block. Because the else is tied with the second if the context for this is only second if
    Age = int(input("Enter Your Age: "))
    if (Age > 18):
        print("Your are 18+")
        
    elif (Age == 18):
        print("Your are 18")
        
    else:
        print("You are below 18")

If you want to do with if/else only

Age = int(input("Enter Your Age: "))
if (Age > 18):
    print("Your are 18+")
else:
    if (Age == 18):
        print("Your are 18")    
    else:
        if (Age < 18):
            print("You are below 18")

change your second if statement to elif. It doesn't work currently because else is comparing to your second if condition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM