Home > Software engineering >  Python: How to increment the inner loop along with outer loop in nested for loop
Python: How to increment the inner loop along with outer loop in nested for loop

Time:09-03

I want to calculate the value of y by using values x and z. It is given that x ranges from 1-5 and z is in between 2-6. It is also to be noted that the x controls the outer loop. The problem with my code is that the inner for loop doesn't iterate.

x = 1
for x in range(1, 6, 1):
    for z in range(2, 6, 1):
        if(x==z):
           print("Function undefined")
        else:
           y =(float)(x*z)/(x-z)    
        print("When x = ",x ,", z =",z , "then y =",y)
        break        

CodePudding user response:

Your code is actually nearly there.

All you need to do is to remove the break statement which exits the inner z loop on the first iteration (at 2 every time).

So the result will look like this:

When x =  1 , z = 2 then y = -2.0
When x =  1 , z = 3 then y = -1.5
When x =  1 , z = 4 then y = -1.3333333333333333
When x =  1 , z = 5 then y = -1.25
Function undefined
When x =  2 , z = 2 then y = -1.25
When x =  2 , z = 3 then y = -6.0
When x =  2 , z = 4 then y = -4.0
When x =  2 , z = 5 then y = -3.3333333333333335
When x =  3 , z = 2 then y = 6.0
Function undefined
When x =  3 , z = 3 then y = 6.0
When x =  3 , z = 4 then y = -12.0
When x =  3 , z = 5 then y = -7.5
When x =  4 , z = 2 then y = 4.0
When x =  4 , z = 3 then y = 12.0
Function undefined
When x =  4 , z = 4 then y = 12.0
When x =  4 , z = 5 then y = -20.0
When x =  5 , z = 2 then y = 3.3333333333333335
When x =  5 , z = 3 then y = 7.5
When x =  5 , z = 4 then y = 20.0
Function undefined
When x =  5 , z = 5 then y = 20.0

CodePudding user response:

Offered as an alternative, if you don't actually need to print "Function undefined" except perhaps for debugging we can iterate over a generator expression which creates all of the x, y, z numbers.

>>> for x, y, z in ((x, y, z) for x in range(1, 6, 1)
...                           for z in range(2, 6, 1)
...                           if x != z
...                           for y in [(x*z) / (x-z)]):
...   print(f"When x = {x}, z = {z}, then y = {y}")
... 
When x = 1, z = 2, then y = -2.0
When x = 1, z = 3, then y = -1.5
When x = 1, z = 4, then y = -1.3333333333333333
When x = 1, z = 5, then y = -1.25
When x = 2, z = 3, then y = -6.0
When x = 2, z = 4, then y = -4.0
When x = 2, z = 5, then y = -3.3333333333333335
When x = 3, z = 2, then y = 6.0
When x = 3, z = 4, then y = -12.0
When x = 3, z = 5, then y = -7.5
When x = 4, z = 2, then y = 4.0
When x = 4, z = 3, then y = 12.0
When x = 4, z = 5, then y = -20.0
When x = 5, z = 2, then y = 3.3333333333333335
When x = 5, z = 3, then y = 7.5
When x = 5, z = 4, then y = 20.0
  • Related