我的程序写错了。
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
条件,即使第一个 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
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/