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

使用datetime模块编写年龄计算器时遇类型错误求助

Fixing the TypeError in Your Age Calculator

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

  1. 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: "))
    
  2. Fix the Typo
    Replace every instance of rok with year to avoid referencing an undefined variable.

  3. 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() with int() 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:04:47