A function that always does the same is not very useful. With parameters, you can give it different data each time.
Parameters
def greet(name):
print(f"Hello {name}")
greet("Ana") # Hello Ana
greet("Luis") # Hello Luis
name is the parameter: a variable that exists inside the function. What you write when calling it ("Ana") is the argument, the concrete value that is passed to it.
Several parameters
def power(base, exponent):
print(base ** exponent)
power(2, 10) # 1024
power(10, 2) # 100
Arguments are assigned by position: the first one to base, the second to exponent. The number must match, or Python raises TypeError:
power(2)
# TypeError: power() missing 1 required positional argument: 'exponent'
Keyword arguments
power(exponent=3, base=2) # 8 (the order no longer matters)
Default values
A parameter can have a value that is used if no other is given:
def greet(name, greeting="Hello"):
print(f"{greeting} {name}")
greet("Ana") # Hello Ana
greet("Ana", "Welcome") # Welcome Ana
Parameters with a default value always go at the end.
What can be passed
Any value: numbers, texts, lists… And you can pass the result of another expression:
def count(text):
print(len(text))
count(input()) # the result of input() is the argument
count("hi" * 4) # 8
Practice with Greet and bid farewell with parameters and Function to calculate the power of a number.