有没有办法在一个函数中声明两个返回值


Code 1:
total = 0
tot = 0
for i in range(0, 101):
if i % 2:
total += i
elif i % 5:
tot += i
print(total)
print(tot)
output:
2500
2000
Code 2:
total = 0
tot = 0
def function():
for i in range(0, 101):
if i % 2:
total += i
elif i % 5:
tot += i
return(total)
return(tot)
a = function()
print(a)
output:
UnboundLocalError: local variable 'total' referenced before assignment

我想把第一个代码作为一个函数(就像我在代码2中尝试的那样(

问题1:有没有办法在一个函数中使用两个返回值?

问题2:如果没有,是否有其他方法可以使代码2工作?

感谢您抽出时间!

(很抱歉,如果我的提问模式不合适,因为我正在努力熟悉Stack Overflow(

您可以通过return total, tot来完成。这里有一个例子:

total = 0
tot = 0
def function():
global total
global tot
for i in range(0, 101):
if i % 2:
total += i
elif i % 5:
tot += i
return total, tot
a = function()
print(a)

这将给你CCD_ 2。

最新更新