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

Python新手遇else语法错误:年龄判断代码运行失败求助

问题分析与解决

你的代码报错是因为Python要求代码块必须缩进,if和else关键字后面的执行语句没有缩进,导致解释器无法识别它们属于哪个条件分支,所以抛出无效语法错误。

修正后的代码:

Question = int(input("How old are you?"))
p = "Maybe"
if Question < 18: 
    print(p) 
else: 
    print("Wow! You're an adult!")

要点说明:

  • if条件判断后,下一行的print(p)需要缩进4个空格(或1个制表符),表示这是if分支的执行代码
  • else关键字单独占一行,后面的print语句同样需要缩进,属于else分支的执行代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 15:05:55