如果是python中的Elif语句

Yve*_*omb 4 python if-statement jython

我写错了程序.

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)
Run Code Online (Sandbox Code Playgroud)

当我执行这个程序时,第一个if语句if (y<h/3):被忽略,所以它运行就像第一个if不存在一样.

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

      else:
#some code
Run Code Online (Sandbox Code Playgroud)

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

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)
Run Code Online (Sandbox Code Playgroud)

但是,我的问题是;

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

Sau*_*tro 5

在第一个程序second iffirst if,它覆盖了所做的事情,而不是"绕过".这就是为什么当你改为时它在第二个程序中工作的原因elif.


Ash*_*ary 5

在第一个例子两个if条件会即使第一次检查ifFalse.

所以第一个实际上看起来像这样:


  if (y<h/3):
     #some code
Run Code Online (Sandbox Code Playgroud)
  if (y>(h*2/3)):
      #some code
  else:
      #some code
Run Code Online (Sandbox Code Playgroud)

例:

>>> 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
Run Code Online (Sandbox Code Playgroud)

但是在一个if-elif-else块中,如果它们中的任何一个,True则代码中断并且不检查下一个条件.


  if (y<h/3):
      #some code
  elif (y>(h*2/3)):
      #some code
  else:
     #some code
Run Code Online (Sandbox Code Playgroud)

例:

>>> 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
Run Code Online (Sandbox Code Playgroud)