【问题标题】:If else error "IndentationError: unexpected indent"如果其他错误“IndentationError:意外缩进”
【发布时间】:2020-12-26 03:55:22
【问题描述】:

我正在尝试学习 Python 并且正在运行代码:

for car in cars:
 if car == 'bmw':
   print(car.upper())
 else:
   print(car.title())

但我收到此错误:

for car in cars: ... if car == 'bmw': ... print(car.upper()) ... else: File "<stdin>", line 4 else: ^ IndentationError: unexpected indent

知道如何改进代码吗?

【问题讨论】:

  • 欢迎来到 StackOverflow。请使用反引号来格式化您的代码。

标签: python-2.7


【解决方案1】:

我希望这会有所帮助。

cars = ['audi', 'bmw']
for car in cars:
    if car == 'bmw':
        print(car.upper())
    else:
        print(car.title())

另外,缩进代码时不要混用制表符和空格。这可能是您收到错误的原因。

【讨论】:

    【解决方案2】:

    正如错误所暗示的,问题在于 else 语句的缩进。它应该与 for 循环中的if 语句处于相同的缩进级别。

    if...:
        .....
    else:
        .....
    

    【讨论】:

      猜你喜欢
      • 2011-04-24
      • 1970-01-01
      • 2020-12-17
      • 1970-01-01
      • 1970-01-01
      • 2018-02-04
      • 2022-08-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多