【问题标题】:Python throws a syntax error for else: statementPython 抛出 else: 语句的语法错误
【发布时间】:2020-12-09 07:44:48
【问题描述】:
def ask():
    while True:
        try:
            num = int(input("Enter an integer:"))
        except:  
            print('Not a number, please try again')
        continue
        else:
            print('Thats a valid number!')
            break
        finally:
            print('All done')

我收到此错误 - 我检查并重新检查了缩进,但仍然无法正常工作

File "<ipython-input-46-ff8c841c59c4>", line 8
    else:
       ^
SyntaxError: invalid syntax

【问题讨论】:

  • 再次检查缩进。 elsecontinue 之后无效。
  • 顺便说一句,欢迎来到 SO!查看tour。以后需要提供minimal reproducible example。在这种情况下,函数和循环与问题无关,因此删除它会有所帮助,使问题对您和我们更加明显。顺便说一句,bare except is bad practice。使用您期望的特定异常,ValueError

标签: python if-statement syntax-error


【解决方案1】:

你的语法错误

def ask(): 
    while True: 
        try: 
            num = int(input("Enter an integer:")) 
        except ValueError:
            print('Not a number, please try again') 
            continue 
        except: 
            print('Thats a valid number!') 
            break 
        finally: 
            print('All done')

【讨论】:

  • 这将有助于解释如何它是错误的,以及你修复了什么。我注意到您还添加了except ValueError,这肯定需要解释,因为它不是问题的一部分。如果您愿意,可以使用这个 sn-p:a [bare `except` is bad practice](https://stackoverflow.com/q/54948548/4518341). use the specific exception you're expecting, `ValueError`.
【解决方案2】:

这里不需要你的 else 语句 :) 试试这个:

def ask(): 
    while True: 
        try: 
            num = int(input("Enter an integer:")) 
            print('Thats a valid number!') 
            break 
        except:
            print('Not a number, please try again') 
            continue 
        finally: 
            print('All done')

【讨论】:

  • 这不是必需的,但这是更好的做法,因为您应该尽可能少地在 try 语句中添加。此外,这并没有解决导致语法错误的原因。
猜你喜欢
  • 2015-01-05
  • 1970-01-01
  • 1970-01-01
  • 2015-05-29
  • 1970-01-01
  • 1970-01-01
  • 2018-08-30
  • 1970-01-01
  • 2022-11-30
相关资源
最近更新 更多