You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何正确使用两个if语句与一个else语句?Python年龄判断分支逻辑执行异常求助

Fixing Your Age Check Conditional Logic

Ah, I spot the issue right away! The problem comes from how you’ve structured your if statements. Let’s break down what’s happening when someone enters an age less than 13:

  1. The first if age <13 condition is true, so it prints the "sorry young warrior..." message.
  2. Then the code moves to the second if age>20 condition. Since the age isn’t greater than 20, this condition fails, so it triggers the else block and prints "Welcome to the clan!"—that’s why you’re seeing both messages.

The fix is to chain your conditions together using if-elif-else so only one branch executes. Here’s the corrected code:

# Example with user input (adjust if you're getting age from another source)
age = int(input("What's your age? "))

if age < 13:
    print("sorry young warrior but you shall not pass.")
elif age > 20:
    print("Why are you here you old geezer.")
else:
    print("Welcome to the clan!")

Why this works:

  • If the age is under 13, the first block runs and the rest are skipped.
  • If not, it checks the elif condition (age over 20) next. If that’s true, it runs that message.
  • If neither condition is met (so age is between 13 and 20, inclusive), the else block triggers and welcomes the user.

This structure ensures only one message is printed for any valid age input.

内容的提问来源于stack exchange,提问作者SpoiledCocoMilk

火山引擎 最新活动