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

如何在Python的if/else语句中执行多条命令?解决缩进错误

解决Python if/else多命令缩进错误问题

你的错误出在else分支里的print语句缩进不对——它比同分支的colourlist.append(colour)多缩进了一级,导致Python无法识别它所属的代码块,因此抛出IndentationError。

要在if/else中执行多条命令,只需把这些命令保持相同的缩进级别,和对应的if/else语句对齐即可。Python靠缩进区分代码块,同一分支下的所有语句必须缩进一致,且不能混合使用空格和制表符(VSCode可设置自动统一为空格,避免这类问题)。

修正后的代码如下:

colourlist = ['blue', 'red', 'white', 'black', 'green', 'yellow', 'brown', 'red', 'white', 'grey']

colour = input('Give me a colour!	')

if colour in colourlist:
    print('The colour you have given is in the list'+ str(colourlist.count(colour)) +' time/s.')
else:
    colourlist.append(colour)
    print('The given colour is not in the list.')  # 和上一行缩进保持一致
print('The colours of the list:')
for colour in colourlist:
    print(colour, end=', ')

关键注意点:

  • 同一代码块内的所有语句缩进量必须完全相同,比如统一用4个空格(Python官方推荐标准)。
  • 禁止同时混用空格和制表符缩进,VSCode可开启「编辑器: 检测缩进」功能自动适配,或手动设置缩进为4空格。
  • 所有属于if/else分支的语句,都要缩进一层,和分支的条件语句(if/else)拉开层级。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 06:25:12