python - if python 中的 Elif 语句

标签 python jython if-statement

我的程序写错了。

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

最佳答案

在第一个示例中,将检查两个 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 block 中,如果其中任何一个为 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

关于python - if python 中的 Elif 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17511652/

相关文章:

python - 在不验证固定宽度模式的情况下,正则表达式模式无法使用后视功能

python - 优化Python在三迭代语句中的计数

python - jython 中字符函数参数的最大长度是多少?

MySQL 条件 select else 聚合语句

MySQL If Date 语句?

python - C和Python之间的套接字通信

java - Jython 和 python 模块

java - nio解析xml文件时出错

if-statement - 如何在jmeter的if Controller 中使用属性变量

python - Django : how to display images from database in template?