如何正确使用两个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:
- The first
if age <13condition is true, so it prints the "sorry young warrior..." message. - Then the code moves to the second
if age>20condition. Since the age isn’t greater than 20, this condition fails, so it triggers theelseblock 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
elifcondition (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
elseblock triggers and welcomes the user.
This structure ensures only one message is printed for any valid age input.
内容的提问来源于stack exchange,提问作者SpoiledCocoMilk




