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

求助:以下Python代码中的Indentation Error(缩进错误)是什么?

Python缩进错误分析与修正

错误具体表现

这段代码存在多处缩进问题:

  • while True: 之后的try语句没有缩进,未被识别为while循环的代码块
  • try块内的代码、except块的print语句,以及循环结束后的日期计算代码,均未遵循Python的缩进规则,导致解释器无法识别代码层级
  • 额外问题:代码中使用了未定义的变量birth_day,正确变量名应为birthday

错误原因

Python是依赖缩进划分代码块的语言,while、try、except这类控制流关键字后的代码必须通过缩进(通常为4个空格)来表示从属关系。没有缩进或缩进错误时,解释器无法判断代码的归属层级,直接抛出IndentationError。

修正后的代码

# We first import the datetime module
import datetime
while True:
    try:
        birthday = input("Enter your Date of Birth(eg. December 25 2005):")
        birthday = datetime.datetime.strptime(birthday, '%B %d %Y')
        break
    except:
        print("Please put in the Format 'Month Day Year' without any initial space")
tday = datetime.datetime.today()
delta = (tday - birthday).total_seconds()
print("You are", delta, "seconds old")

修正说明:

  • 给while循环内的try语句添加4个空格缩进
  • try块内的两行代码、except块内的print语句分别缩进4个空格,明确归属关系
  • 修正变量名错误:将birth_day改为birthday

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 01:35:28