0
x = [5 ,8 , 3 ,29, 445, 54]


def high():
    for num in x:
        if num > z:
            z = num
    return z

high()

print(z)

I want a function that returns the highest number from a list without using the max() inbuilt python function. Whenever I try and run this, i get this error:

line 6, in high
    if num > z:
UnboundLocalError: local variable 'z' referenced before assignment
1
  • you told python to do something when num is larger than z, but what is z? Commented Jun 25, 2020 at 0:58

4 Answers 4

3

You can't use a variable without defining it first so you need to define z = x[0]

The second problem is with print(z) z is a local variable you can't call it like that you need to save whatever high() returns first in a variable then print it

x = [5 ,8 , 3 ,29, 445, 54]


def high():
    z = x[0]
    for num in x:
        if num > z:
            z = num
    return z

z = high()

print(z)
Sign up to request clarification or add additional context in comments.

4 Comments

Having defined z = x[0] it makes more sense to start processing the list at x[1] i.e. for num in x[1:]:
I know, you are right. I intended to keep it simple for him/her to know what i added without confusion. I think it's all about learning not answering the best thing
@Nick Logically that's true, but using x[1:] would cause the entire list to be copied (minus the first element), which in general would be way slower than checking the first element. That optimization would only make sense if it used an index to access the list elements, avoiding the copy, but that would probably be slower as well.
@TomKarzes interesting. I would have expected that in a context like num in x[1:] the interpreter would have been smart enough to realise it didn't need a copy. Thanks for letting me know, I'll try to avoid that construct.
0

You need to declare always any variable before using that variable.

x = [5 ,8 , 3 ,29, 445, 54]

def high(x):
    z = 0    # add this line and..
    for num in x:
        if num > z:
            z = num
    return z

z = high(x)  # ..this line 

print(z)

Comments

0

Thanks for reaching out. First of all, z was not defined in your function. We define z and set it to an integer of 0. The code

x = [5 ,8 , 3 ,29, 445, 54]

def high(list_of_numbers):
    z = 0
    for num in x:

        if num > z:
            z = num
    return z

print(high(x))

Comments

0

first you need to declare a varriable before using that varriable globally using global keyword.like z=x[0]

x=[5,8,3,29,445,54]
def high():
    global z
    z=x[0]
    for num in x:
        if(num>z):
            z=num
    return z
high()
print(z)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.