【问题标题】:If Elif statements in pythonPython中的If Elif语句
【发布时间】:2013-07-07 11:16:38
【问题描述】:

我写错了一个程序。

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&lt;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 语句?

【问题讨论】:

    标签: python jython if-statement


    【解决方案1】:

    在第一个示例中,将检查两个 if 条件,即使第一个 if 是 False。

    所以第一个实际上是这样的:


      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
    

    【讨论】:

      【解决方案2】:

      在第一个程序中,second if 覆盖了first if 中所做的事情,它没有被“绕过”。这就是为什么当您更改为 elif 时它在第二个程序中起作用的原因。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-11-23
        • 2020-10-28
        • 2015-01-16
        • 2017-07-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多