简体   繁体   English

我认为我的 if else 语句不起作用

[英]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这是 Output

Enter Your Age: 20
Your are 18+
You are below 18
  1. When Age > 18 it should print "Your are 18+"Age > 18时,它应该打印"Your are 18+"
  2. When Age == 18 it should print "Your are 18"Age == 18时,它应该打印"Your are 18"
  3. When Age < 18 it should print "Your are below 18" What is happening here?Age < 18时,它应该打印"Your are below 18"这里发生了什么?

Use if elif else ladder.使用if elif else阶梯。 Don't use pass .不要使用pass pass is when you do nothing inside a branching condition. pass是当你在分支条件内什么都不做的时候。

In your code,在您的代码中,

  1. Given input 20, the first if gets evaluated.给定输入 20,第一个if被评估。 As it's true, the print statement gets executed.确实,打印语句被执行。
  2. Second if will get executed.第二个if将被执行。 As it's false , the condition is false, it won't go inside the if block.因为它是false ,所以条件是 false ,它不会在if块内 go 。
  3. Next it will go to else block.接下来它将 go 到else块。 Because the else is tied with the second if the context for this is only second if因为if this 的上下文仅是第二个if ,则else与第二个相关联
    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如果您只想使用if/else

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.将第二个 if 语句更改为 elif。 It doesn't work currently because else is comparing to your second if condition.它目前不起作用,因为 else 正在与您的第二个 if 条件进行比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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