2013-07-07 143 views
4

我写错了一个程序。如果Python中的Elif语句为

def changeByThirds(pic): 
    w= getWidth (pic) 
    h = getHeight(pic) 

    newPic = makeEmptyPicture(w,h) 
    for x in range (0,w): 
    for y in range (0,h): 
     pxl = getPixel(pic, x, y) 

     if (y<h/3): 
#some code 

     if (y>(h*2/3)): 
#some code 

     else: 
#some code 

    return (newPic) 

当我执行这个计划,第一个if语句if (y<h/3):被忽略,所以它运行,就好像第一,如果是不存在的。

if (y>(h*2/3)): 
#some code 

     else: 
#some code 

我发现写的代码正确的方法是这样的:

def changeByThirds(pic): 
    w= getWidth (pic) 
    h = getHeight(pic) 

    newPic = makeEmptyPicture(w,h) 
    for x in range (0,w): 
    for y in range (0,h): 
     pxl = getPixel(pic, x, y) 

     if (y<h/3): 
#some code 

     elif (y>(h*2/3)): 
#some code 

     else: 
#some code 

    return (newPic) 

不过,我的问题是;

在第一个代码 - 为什么它绕过第一个if语句?

+0

你的问题还不清楚。据我了解,第一个if语句的处理不应该有所不同,它不应该被“用其他”处理。我建议你给出一个例子说明这个问题的输入/输出。 – Marcin

回答

5

在第一示例中两个if条件会甚至进行检查,如果第一ifFalse

因此,第一个实际上是这样的:


if (y<h/3): 
    #some code 

if (y>(h*2/3)): 
     #some code 
    else: 
     #some code 

例子:

>>> x = 2 

if x == 2: 
    x += 1  
if x == 3:  #due to the modification done by previous if, this condition 
       #also becomes True, and you modify x again 
    x += 1 
else:  
    x+=100 
>>> x    
4 

但是在if-elif-else区块中,如果它们中的任何一个是True那么代码就会出现,并且不会检查下一个条件。


if (y<h/3): 
     #some code 
    elif (y>(h*2/3)): 
     #some code 
    else: 
    #some code 

例子:

>>> x = 2 
if x == 2: 
    x += 1 
elif x == 3:  
    x += 1 
else:  
    x+=100 
...  
>>> x    # only the first-if changed the value of x, rest of them 
        # were not checked 
3 
+0

不,“else”连接到第二个“if”而不是第一个。 –

+0

@ Yve - 首先你有两个'if' *套房*。第一个是if,第二个是if和else。第一个是条件为True时运行,第二个将运行if或者运行else。 ... –

+2

@yve如果条件评估为True,它将运行。可能发生的事情是,你正在分配给新图像,第二个“if”会覆盖新像素,或者如果第二个如果没有这样做,那么如果“else”子句会这样做 - 清除第一个“if”的效果。尝试打印'打印'MARKER''作为您条件的第一行,并向您证明这一点...... –

5

在第一个程序中,second if覆盖了first if中所做的操作,但未被“绕过”。这就是为什么当你更改为elif时,它在第二个程序中起作用。

+0

但是当你在另一个之后使用一个'if'时,可能会发生第二个将被评估并且用所有编程语言覆盖第一个,取决于你的代码。这就是为什么你应该使用'if-elif-else'块的情况下,只有一个条件必须是'真' –

+0

@你知道在python.org有官方文档,对吧?有教程,库说明和官方语言参考。 – Marcin