Python 如果语句破坏了我的打印字符串,请重试

Python 如果语句破坏了我的打印字符串,请重试,python,python-3.x,printing,try-catch,Python,Python 3.x,Printing,Try Catch,我正在尝试这样做,如果用户输入任何字母,它将不会给出任何错误。它将重新启动程序 x = int(input()) try: if x == (a, b, c): # Entering letters in the x integer will restart the program. displayStart() return print('') 在我输入了这个“try:”语句之后,底部的print语句变成了无效语法。关于如何修复它有什么建议

我正在尝试这样做,如果用户输入任何字母,它将不会给出任何错误。它将重新启动程序

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

在我输入了这个“try:”语句之后,底部的print语句变成了无效语法。关于如何修复它有什么建议吗?

try
套件需要有一个
除外的
和/或
finally
子句。你两个都没有。e、 g

try:
    do_something()
except SomeExceptionName:
    do_something_because_some_exception_name_was_raised_in_do_something()
或:

您可能还想看一下

如果您仔细想想,您的
套件应该在这里做什么?如果引发异常,如果您无法处理它(通过
除了
)或执行清理操作(通过
最后执行
),会发生什么不同于正常的情况


从python中:


您需要在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。 值得注意的是,像我这样捕获所有异常并不是很好的做法。通常,您会指定预期的特定异常,而不是异常。例如,如果我期望出现ValueError,我会:

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

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

这是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语句是
assert(1==1)
它将永远不会抛出异常,那么它将打印“thiswillnever print”行,而不是“after exception”行


当然,还有更多的事情,比如
最终
其他
,但是这个
try:
except:
示例应该足以让您开始您需要
except
块,在
try
之后需要一个关于python异常的教程。您应该。请确保选择一个最有帮助的答案:)如果OP不知道如何使用try/except,我怀疑他会理解你刚才粘贴的内容。@Paco--可能不会,但参考资料就在那里。这不难理解。有
try
,然后是一组命令,然后是包含更多命令的and和except子句,可选else和FINAL,或者有一个FINAL。不管怎么说,我在第一句话(我想…)中用词解释得非常清楚。这些天来,我认为语法
(e
除外)是首选。我尝试了你发布的第一个建议。我在“Exception”后面的逗号上收到了一个无效语法。在这里,我将它改为使用@mgilson的建议。尝试将其更改为
,例外情况除外,因为e:
“这些天”是2008年10月1日,即Python 2.6的发布日期。
try:
    ...
except ValueError as ve:
    print('A Value Error occurred: ', ve)
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")