Introduction to function parameters in Python
Learn how to make your Python functions more flexible and powerful by using parameters to pass data.
So far, we've created very basic functions that consistently perform the same task and return the same value when called. For example:
def square_of_two():
return 2 * 2
print(square_of_two())
square_of_two always returns the square of the value 2. In programming jargon, we would say that the value 2 is hard-coded, meaning it does not change.
To make the function more flexible, we can use function parameters. Parameters enable the function to accept input values and use them within its body.
For instance, rather than hard-coding the number 2, we can define a parameter x and pass a different value whenever the function is invoked.
def square(x):
return x * x
This way we have a more flexible function that will return the square of any number passed as input.
To assign a value to parameter x, we must provide a value when calling the function. These values passed to the function are referred to as arguments. For example:
square(5)
Let's see if that works:
def square(x):
return x * x
print(square(2))
print(square(5))
print(square(11))
What will be the output?
def func(x):
return x * 2
print(func(20))
Functions can receive multiple arguments. To make them accessible, you need to define multiple parameters when declaring the function.
For example, here we declare the function subtract that defines two parameters x and y.
def subtract(x, y):
return x - y
When passing values to the function, you have two options:
Either pass the values in the order of the defined parameters:
subtract(10, 5)
Or assign the values to the parameter names:
subtract(y=5, x=10)
As you can see, both approaches yield the same result:
def subtract(x, y):
return x - y
print(subtract(10, 5))
print(subtract(y=5, x=10))
What will be the output?
def func(x, y):
return (x * 10) + (y * 2)
print(func(2, 10))
What will be the output?
def func(a, b):
return a + b
print(func(b = 'abc', a = 'def'))
Parameters can have any valid Python values such as integers or strings.
You can specify default values when defining parameters:
def func(x='hello'):
print(x)
func('hi')
func()
If we do not pass a value when calling the function, x is assigned the default value hello
.
What will be the output?
def connect(a, b = 'people'):
return a + ' ' + b
print(connect('hello'))
What will be the output?
def func(x, y = 5):
return x + (y * 2)
print(func(2))
What will be the output?
def func(x, y = 5):
return x + (y * 2)
print(func(2, 2))
What will be the output?
def func(x, y = 5):
return x + (y * 2)
print(func(y=4, x=10))