【问题标题】:How do I fix "Unexpected unindent" error with try/except/else syntax如何使用 try/except/else 语法修复“Unexpected unindent”错误
【发布时间】:2019-02-16 20:52:36
【问题描述】:

while not 语句中 else 之后的任何内容都存在缩进问题,我确定这是因为我的格式不正确。正确的写法是什么?

我尝试过移动语句,但无法弄清楚

valid_data = 假

while not valid_data:


    try:
        qty = int(input("How many would you like? (1-10)> "))
    except Exception as detail:
        print("Error: ", detail)
    else:
        try:
            if qty >= 1 and qty <= 10:
                valid_data = True
    finally:
        print("valid entry")

实际结果是将 qty 设置为 1 到 10 之间的用户输入,而不会出现无效输入,例如,如果用户输入字符串,则代码不会崩溃。对于这个作业,我必须使用 try/except 语法。

【问题讨论】:

  • 您的嵌套尝试缺少 except 或 finally。
  • 第二个try 没有except。我不确定你为什么有try,因为比较整数时不会出错。
  • 基本上你有混合制表符和空格。复制到编辑器并将所有选项卡更改为 4 个空格

标签: python compiler-errors indentation except try-except


【解决方案1】:

你搞砸了缩进:你的 finally 声明和它下面的 print 是 缺少额外的 4 个缩进空格。如果需要,您可以复制并粘贴固定版本:

while not valid_data:
    try:
        qty = int(input("How many would you like? (1-10)> "))
    except Exception as detail:
        print("Error: ", detail)
    else:
        try:
            if qty >= 1 and qty <= 10:
                valid_data = True
        finally:
            print("valid entry")

【讨论】:

    猜你喜欢
    • 2018-06-18
    • 1970-01-01
    • 2012-07-22
    • 1970-01-01
    • 2019-10-22
    • 1970-01-01
    • 2012-11-06
    • 1970-01-01
    • 2020-11-20
    相关资源
    最近更新 更多