如果变量是全局声明的,那么在 python 函数中传递参数的必要性是什么?

What is the need of passing the arguments in python functions if the variables are declared globally?

a = 13
b = 12

def add():
    return a + b

def add2(a, b):    # why to pass a and b?
    return a + b

print(add())   # result 25
print(add2(a, b))    #result 25

如果我们可以使用 values/variables 而无需将参数传递给函数,为什么我们需要将参数传递给 python 函数?

在你的情况下,没有必要传递参数,因为你总是添加相同的两个变量。但是,如果您想要一个可以添加任意两个变量的函数,该函数如何知道要添加哪两个变量呢?在下面的示例中,我有三个变量和一个将其中两个相加的函数:

def add():
    return a + b

a = 5
b = 7
c = 10

print(add())  # 12
# No way to add a + c or b + c

问题是,如果我想将 c 添加到其他变量之一,我无法做到这一点。我们可以定义一个带有两个参数的函数来解决这个问题:

def add(n1, n2):
    return n1 + n2

a = 5
b = 7
c = 10

print(add(a, b))  # 12
print(add(a, c))  # 15
print(add(b, c))  # 17

所以,简而言之,如果您不确定函数需要哪些全局变量,您只需要将参数传递给函数