Search code examples
pythonfunctionfor-loopmax

Function does not output correct maximum value


I would like to find the maximum value z and find its i and j values at z maximum.

I tried the code using def function and did not get the correct maximum z value and its i and j values.

Below is my code:

maxi = 0
def i_j ():
    global maxi
    for i in range (1, 5):
        for j in range (1, 5):
            z = i + j
            print(z)
            if z > maxi:
                maxi = z
                return i, j
            j += 1
        i += 1
print ("Maximum: {}".format(maxi))
x, y = i_j()
print ("i at max:", x)
print ("j at max:", y)

The output of the Python code:

Maximum: 0
2
i at max: 1
j at max: 1

Kindly help me, many thanks.


Solution

  • You are returning too early, this means you leave the function the first time that z>maxi is true, which means in the very first iteration.

    Also, there are other mistakes that commenters pointed out:

    • maxi doesn't make much sense to print before calling the function
    • the for loop automatically increases the loop variables (or rather, iterates through the list that is range(1,5,1) and thus the incrementation doesn't actually do anything because it gets overwritten in the next step)

    This is how it should look:

    def i_j ():
        maxi = 0
        maxi_i = 0
        maxi_j = 0
        for i in range (1, 5, 1):
            for j in range (1, 5, 1):
                z = i+j
                print ("{}".format(z))
                if z > maxi:
                    maxi = z
                    maxi_i = i
                    maxi_j = j
        return (maxi, maxi_i, maxi_j)
    
    maxi, x, y = i_j ()
    print ("Maximum: {}".format(maxi))
    print ("i at max: {}".format(x))
    print ("j at max: {}".format(y))