Functions: Parameters
Welcome to the lesson on functions. Now, we'll proceed by discussing function parameters and how they can make our functions more flexible and powerful.
` ˙⋆˖⁺‧₊☽◯☾₊‧⁺˖⋆˙ `
Function Parameters
Parameters allow you to pass information into functions. They act as placeholders for the values that will be provided when the function is called. There are three types of parameters in Python:
- • Positional Parameters
- • Keyword Parameters
- • Default Parameters
Positional Parameters
Positional parameters are the most common type. When you call a function, you provide the arguments in the same order as the parameters are defined.
#Example: Function with positional parameters
def greet(name, age):
print(f"Hello, my name is {name} and I am {age} years old.")
#Calling the function with positional arguments
greet("Harry", 17)
greet("Hermione", 18)
In this example, the greet() function has two positional parameters: name and age. The arguments "Harry" and 17 are passed to the function in that order.
Keyword Parameters
Keyword parameters allow you to specify the arguments by the parameter name, making the function call more readable.
#Example: Function with keyword parameters
def greet(name, age):
print(f"Hello, my name is {name} and I am {age} years old.")
#Calling the function with keyword arguments
greet(name="Harry", age=17)
greet(age=18, name="Hermione")
In this example, the same greet() function is called using keyword arguments. The order of arguments does not matter when using keyword parameters.
Default Parameters
Default parameters allow you to define default values for parameters. If no argument is provided for a default parameter, the default value is used.
#Example: Function with default parameters
def greet(name, age=18):
print(f"Hello, my name is {name} and I am {age} years old.")
#Calling the function with and without the default parameter
greet("Harry", 17) # Both parameters provided
greet("Hermione") # Only the name provided, age defaults to 18
In this example, the greet() function has a default parameter age with a default value of 18. When calling the function, if the age is not provided, it defaults to 18.
Practical Application
Advancing in the Sanctum of Incantations, you will now create functions that accept parameters, allowing you to customize their behavior.
⋆˖⁺‧₊ Create a function that accepts a parameter and prints "Greetings, Mage {name}!", then call it at least twice. ₊‧⁺˖⋆
Sample Output:
Greetings, Mage Aurelia!
Greetings, Mage Yennefer!
Greetings, Mage Triss!