If Elif statements in python

I wrote the program incorrectly.

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) 

When I run this program, the first if if (y<h/3): ignored, so it works as if the first, if not at all.

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

I found that the correct way to write code was this:

 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) 

However my question is:

In the first code. Why does it bypass the first if statement?

+4
source share
2 answers

In the first example, both if conditions will be checked, even if the first if was False .

So the first one looks like this:


  if (y<h/3): #some code 

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

Example:

 >>> 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 

But in the if-elif-else block, if any of them is True , then the code breaks, and the following conditions are not checked.


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

Example:

 >>> 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 
+5
source

In the first second if program, there was a rewrite of what was done in the first if , it was not "bypassed". That's why it worked in the second program when you changed to elif .

+5
source

Source: https://habr.com/ru/post/1490122/


All Articles