You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python elif语法错误求助:编写age_20函数遇SyntaxError

Fixing the SyntaxError in your age_20() function

Hey there! Let's break down what's causing that stubborn SyntaxError and get your code working properly step by step.

The main issues in your code:

  • Mismatched parentheses in return statements: Both of your return lines have extra nested parentheses that throw off Python's parser. For example, (int(current_age) - 20,("years old...")) adds an unnecessary set of brackets around the string—this breaks the tuple structure Python expects.
  • Redundant int() conversions: You already convert the input to an integer with current_age = int(input(...)), so you don't need to wrap current_age in int() every time you use it.
  • Unnecessary parentheses around the function call: The final line (age_20()) has extra brackets that serve no purpose—just calling age_20() directly works fine.
  • Minor logic overlap: When current_age is exactly 20, both >=20 and <=20 conditions are true. Python will run the first matching condition (subtracting 20), but using an else clause here makes the logic cleaner and avoids ambiguity.

Corrected code (aligned with your task requirements)

If you want the function to return a tuple and then generate the formatted statement:

# [ ] complete age_20()
def age_20():
    current_age = int(input("Enter your current age: "))
    if current_age >= 20:
        return (current_age - 20, "years old, 20 years difference from now")
    else:
        return (current_age + 20, "years old, 20 years in the future")

# Call the function and format the output statement
calculated_age, description = age_20()
print(f"{calculated_age} {description}")

Or if you prefer the function to handle the full statement formatting directly:

# [ ] complete age_20()
def age_20():
    current_age = int(input("Enter your current age: "))
    if current_age >= 20:
        return f"{current_age - 20} years old, 20 years difference from now"
    else:
        return f"{current_age + 20} years old, 20 years in the future"

# Call the function and print the result
print(age_20())

Both versions fix the syntax error, simplify your code, and produce the exact output format your task specifies.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:35:46