Home > Software engineering >  What is the need of passing the arguments in python functions if the variables are declared globally
What is the need of passing the arguments in python functions if the variables are declared globally

Time:01-15

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

why do we need to pass the arguments to the python function if we can use the values/variables without passing them to functions?

CodePudding user response:

It is true that you are globally declaring the variables, but there could be more than two variables that are declared globally. Now suppose you want to perform the add function just on the second and third variables how will the compiler understand it if you don't specify the parameters within the function that will do the addition operation?

CodePudding user response:

In your case, it is not necessary to pass arguments because you are always adding the same two variables. But if you wanted to have a function that could add any two variables, how would the function know which two variables to add? In the example below, I have three variables and a function to add two of them:

def add():
    return a   b

a = 5
b = 7
c = 10

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

The problem is that if I want to add c to one of the other variables, I have no way of doing this. We can define a function which takes two arguments to solve this problem:

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

So, in short, you only need to pass arguments to a function if you aren't sure which global variables the function will need

  •  Tags:  
  • Related