【问题标题】:Try if Statement Breaks my print str试试如果语句破坏了我的打印 str
【发布时间】:2014-10-23 16:28:26
【问题描述】:

我正在努力做到这一点,所以如果用户输入任何字母,它不会给出任何错误。它只会重新启动程序。

x = int(input())
try:
    if x == (a, b, c): # Entering letters in the x integer will restart the program.
        displayStart()
        return
print('')      

我有这个,在我输入这个“try:”语句后,底部的打印语句变为无效语法。关于如何修复它的任何建议?

【问题讨论】:

  • 你需要在try之后阻止except
  • 看起来需要一个关于python异常的教程。
  • 一定要选择最有帮助的答案:)

标签: python python-3.x printing try-catch


【解决方案1】:

try 套件需要有一个except 和/或finally 子句。你两个都没有。例如

try:
    do_something()
except SomeExceptionName:
    do_something_because_some_exception_name_was_raised_in_do_something()

或者:

try:
    do_something()
finally:
    do_something_even_if_exception_was_raised()     

您可能还想看看python tutorial

如果您考虑一下,您的try 套件应该在这里做什么?如果引发异常,如果您无法处理它(通过except)或执行清理操作(通过finally),会发生什么与正常情况不同的情况?


来自pythongrammer specification

try_stmt: ('try' ':' suite
           ((except_clause ':' suite)+
            ['else' ':' suite]
            ['finally' ':' suite] |
           'finally' ':' suite))

【讨论】:

  • 如果 OP 不知道如何使用 try/except,我怀疑他会理解你刚刚粘贴的内容。
  • @Paco -- 可能不是,但参考资料在那里。这不是难以理解。 . .有try,然后是一组命令,然后是带有更多命令的除子句,可选的else和finally,或者有一个finally。不管怎样,我在第一句话中已经用文字很清楚地解释了它(我认为......)
【解决方案2】:

这是一个 try 语句的示例:

try:
   print("this will actually print, because its trying to execute the statements in the tryblock")
   assert(1==0) #a blatently false statement that will throw exception
   print("This will never print, because once it gets to the assert statement, it will throw an exception")
except:
   print("after exception this is printed , because the assert line threw an exception")

如果断言语句是assert(1==1),它永远不会抛出异常,那么它会打印“This will never print”行,而不是“after exception”行

当然还有更多的东西,比如finallyelse,但是这个try: except: 的例子应该足以让你开始

【讨论】:

    【解决方案3】:

    您需要在 try 语句中添加一个 except 部分。像这样:

    x = int(input())
    try:
        if x == (a, b, c):
            displayStart()
            return
    except Exception as e:
        print('An exception occurred: ', e)
    
    print('')
    

    一个try 需要有它对应的except。 请注意,像我一样捕获所有异常并不是很好的做法。通常您会指定您期望的特定异常,而不是 Exception。例如,如果我期待一个 ValueError,我会做到:

    try:
        ...
    except ValueError as ve:
        print('A Value Error occurred: ', ve)
    

    此外,您通常希望在 try-except 块中放置尽可能少的代码。

    【讨论】:

    • 现在,我认为语法except Exception as e 是首选。
    • 我尝试了您发布的第一个建议。我在“异常”之后的逗号上收到了无效的语法。
    • 这里,改成使用@mgilson 的推荐。尝试将其更改为except Exception as e:
    • “这些日子”是 2008 年 10 月 1 日,即 Python 2.6 的发布日期。
    猜你喜欢
    • 1970-01-01
    • 2018-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-05
    • 1970-01-01
    相关资源
    最近更新 更多