使用datetime模块编写年龄计算器时遇类型错误求助
Hey there, let's break down what's causing that TypeError and fix your age calculator step by step!
The Root of the Problem
The error unsupported operand type(s) for -: 'int' and 'str' happens because you're trying to subtract a string from an integer. Variables like year, day, month (plus the typo rok in your code) are likely coming directly from user input as strings, while current_year/now.year are integers pulled from the datetime module.
Also, quick heads up: rok is a typo for year—that's another spot that would throw off your code!
Step-by-Step Fixes
Convert User Input to Integers
Before doing any math, make sure all birth date values are numeric. For example:year = int(input("Enter your birth year: ")) month = int(input("Enter your birth month: ")) day = int(input("Enter your birth day: "))Fix the Typo
Replace every instance ofrokwithyearto avoid referencing an undefined variable.Simplify and Refine the Logic
Your current conditionals can be streamlined, and we should handle invalid future dates early to avoid calculating an invalid age.
Corrected Full Code
from datetime import datetime # Get and convert user input to integers year = int(input("Enter your birth year: ")) month = int(input("Enter your birth month: ")) day = int(input("Enter your birth day: ")) now = datetime.now() current_year = now.year current_month = now.month current_day = now.day # Handle invalid future dates first if (current_year < year) or (current_year == year and current_month < month) or (current_year == year and current_month == month and current_day < day): print("Be serious, please.") else: # Calculate age based on birthday occurrence if (month == current_month and day <= current_day) or (month < current_month): age = current_year - year else: age = current_year - year - 1 print(f"Your age is: {age}")
Explanation
- Input Conversion: Wrapping
input()withint()ensures we're working with numeric values that can be subtracted without type errors. - Invalid Date Check: We first check if the birth date is in the future (a more thorough check than just year comparison) and show the "Be serious" message immediately.
- Age Calculation: The logic checks if the user's birthday has already happened this year—if yes, we just subtract the birth year from the current year; if not, we subtract an extra 1 to account for the upcoming birthday.
内容的提问来源于stack exchange,提问作者user9773137

