使用试试"如果"行蟒蛇

时间:2014-04-19 09:17:49

标签: python if-statement

我无法弄清楚如何做到这一点。

我想在“if”语句的行中添加“try”语句,但只是在第一个语句中,我尝试了这个,但是它不起作用:

try:
   if something1 == something22:
except:
     break
if something2 == something3: #this line must not be called if first if inside try is not True
   if something4234 == something65543:
       #and so on

总而言之,我想检查是否有东西= = 22,如果是真的,那么代码会继续,如果它是假的,它会停止......

编辑:

以下是更好的解释:

http://pastebin.com/MyMr3Byr

提前致谢!

3 个答案:

答案 0 :(得分:1)

当你这样做时:

try:
    if this or that or the_other:
except:

你得到一个错误,因为Python期望if语句之后的缩进块,正如你通常所拥有的那样:

if it_works:
    print("yay") # indented block

此外,如果您尚未进入循环,则无法break。在一个循环中,break会跳到循环的末尾,但是如果你不在循环中那么代码应该去哪里?

如果比较有时失败,你可以这样做:

try:
    if something1.attr != something2.attr:
        pass # do nothing if they don't match
except AttributeError: # guard against specific error
    pass # do nothing if the comparison fails
else:
    # continue otherwise
    ...

此处else阻止只会在以下情况下运行:

  1. 比较没有错误;和
  2. 比较评估为True
  3. 如果发生完全意外的事情(即不是AttributeError),那么该错误仍然会在堆栈中传递,因此我们会发现它。

答案 1 :(得分:1)

如果你想执行一个IF语句,并想在出现问题时退出代码片段:

try:
    if something1 == something2:
        # your code goes here
        pass
except:
    write("Somting wong in ze cod")
    write("continuing the program...")

你在excpet之后不需要一个break语句...你通常用它来打破while或for循环。根据您的要求,我建议跳过try子句,只需使用

if statement1==statement2:
    #code goes here
    pass

除非你预先评估if或#code在这里发表声明时可能会发生错误

答案 2 :(得分:0)

通过嵌套的if

进行规范的方法
if something1 == something22:
    if something2 == something3:
        if something4234 == something65543:
            do_something()

忘记try / catch来排除if,除非您明确要raise例外:

if something1 != something22:
    raise MyException

或者,除非某些比较容易导致异常,在这种情况下只需将try / catch放在整个事物之外:

try:
    if something1 == something22:
        if something2 == something3:
            if something4234 == something65543:
                do_something()
catch:
    handle_exception()