Jk wall Jk wall - 1 month ago 4
Python Question

Why we use parameters in function when we can define variables in body of function?

I am confuse at this point , We use parameter in python suppose this program:

method 1



def f(x,y):
z=x+y
print(z)

f(1,2)


and if we don't pass parameter and do calculation like this :

method 2



def f():
x=1
y=2
z=x+y
print(z)

f()


What is difference ,and Which one is good and why we pass parameter when we can use second method.

Answer

One simple way of looking at it is how it will affect the size of your codebase. Consider needing to calculate f(1,2), f(3,4) and f(5,6) then you would need just one instance of your method 1 (called three times) or three instances of method 2 (also called three times). So using method 1 saves the amount of code you need.