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
returnlines 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 withcurrent_age = int(input(...)), so you don't need to wrapcurrent_ageinint()every time you use it. - Unnecessary parentheses around the function call: The final line
(age_20())has extra brackets that serve no purpose—just callingage_20()directly works fine. - Minor logic overlap: When
current_ageis exactly 20, both>=20and<=20conditions are true. Python will run the first matching condition (subtracting 20), but using anelseclause 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
相关产品推荐
相关产品推荐

