想求最大值,为什么运行结果老是零啊?
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)
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)因为函数内部的局部值掩盖了函数外部的全局值 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) 你没有搞清楚全局变量 和 局部变量的区别。
函数内容加一个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]