繁体   English   中英

如果是python中的Elif语句

[英]If Elif statements in python

我写错了程序。

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不存在一样。

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语句?

在第一个程序中, second if覆盖了first if ,它没有被“绕过”。 这就是为什么当你改成elif时它在第二个程序中工作的原因。

在第一个例子双方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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM