查找 python 列表中最大数字的函数

Function for finding the biggest number in a list in python

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


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

high()

print(z)

我想要一个 returns 列表中最高数字的函数,而不使用 max() 内置 python 函数。每当我尝试 运行 时,我都会收到此错误:

line 6, in high
    if num > z:
UnboundLocalError: local variable 'z' referenced before assignment

你不能在没有定义变量的情况下使用它,所以你需要定义 z = x[0]

第二个问题是 print(z) z 是一个局部变量,你不能这样调用它,你需要先在变量中保存任何 high() returns 然后打印它

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)

您需要在使用该变量之前始终声明任何变量。

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)

感谢您与我们联系。首先,你的函数中没有定义 z 。我们定义 z 并将其设置为整数 0。代码

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

首先你需要在全局使用该变量之前声明一个变量,使用 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)