木隐 发表于 2021-3-25 14:27:35

想求最大值,为什么运行结果老是零啊?

def compare(x,y):
    return x if x > y else y
def max_value(*list_data):
    value = list_data
    for x in range(1,len(list_data)):
      value = compare(list_data,value)
value = 0
max_value(42323,457,4245,6,3,5463,6,7,45,725,723,7,3,46,86,7,56,8,567,5,5745,26,34,63,412,35,4,76585,67,3,45,4,5,34,5,47,5686)
print(value)

纸老虎和兔子 发表于 2021-4-6 21:44:25

def compare(x,y):
    return x if x > y else y
def max_value(*list_data):
    global value
    value = list_data
    for x in range(1,len(list_data)):
      value = compare(list_data,value)
value = 0
max_value(42323,457,4245,6,3,5463,6,7,45,725,723,7,3,46,86,7,56,8,567,5,5745,26,34,63,412,35,4,76585,67,3,45,4,5,34,5,47,5686)
print(value)因为函数内部的局部值掩盖了函数外部的全局值

情參似塰 发表于 2021-4-17 16:18:20

def compare(x,y):
    return x if x > y else y
def max_value(*list_data):
    value = list_data
    for x in range(1,len(list_data)):
      value = compare(list_data,value)
    return value
value = max_value(42323,457,4245,6,3,5463,6,7,45,725,723,7,3,46,86,7,56,8,567,5,5745,26,34,63,412,35,4,76585,67,3,45,4,5,34,5,47,5686)
print(value)

维护和平天使 发表于 2021-4-27 10:47:03

你没有搞清楚全局变量 和 局部变量的区别。
函数内容加一个return 返回值就可以。
def compare(x, y):
    return x if x > y else y


def max_value(*list_data):
    value = list_data
    for x in range(1, len(list_data)):
      value = compare(list_data, value)
    return value

value = max_value(42323,457,4245,6,3,5463,6,7,45,725,723,7,3,46,86,7,56,8,567,5,5745,26,34,63,412,35,4,76585,67,3,45,4,5,34,5,47,5686)
print(value)
页: [1]
查看完整版本: 想求最大值,为什么运行结果老是零啊?