Python Function: Type of Arguments in a Function
Python function arguments are like giving cooking instructions to a helper: use ‘Positional’ for step-by-step, ‘Keyword’ for specific tasks, ‘Default’ for assumptions, ‘Variable-Length’ for flexible groups, and ‘Keyword Variable-Length’ for extras.
In Python, when you create a function, you can use different types of arguments to pass information to the function. Think of arguments like giving instructions to a helper.
Type of Arguments in Python Functions
Here are the types of arguments in a function:
(1) Positional Arguments:
Imagine you’re making a sandwich, and you have a list of ingredients. You tell your helper, “First, put the bread, then the cheese, and finally the lettuce.” This is just like using positional arguments.
Here’s a Python code block to demonstrate this:
def make_sandwich(bread, cheese, lettuce):
print("I'm making a sandwich with the following ingredients:")
print("1. Bread: " + bread)
print("2. Cheese: " + cheese)
print("3. Lettuce: " + lettuce)
# You call the function and give the ingredients in a specific order
make_sandwich("whole wheat", "cheddar", "romaine")
In this code:
- We define a function called
make_sandwich
with three parameters:bread
,cheese
, andlettuce
. - Inside the function, we print out the ingredients in the specific order they were given.
- When we call the
make_sandwich
function, we provide the ingredients in the same order as the parameters (e.g.,"whole wheat"
forbread
,"cheddar"
forcheese
, and"romaine"
forlettuce
).
(2) Keyword Arguments:
Imagine you’re making a special drawing, and you have different colored crayons to use. Instead of just using them in the order you found them, you want to be super specific about which color goes where. You say, “First, I want the blue crayon, then the red one, and finally the green one.” This is just like using keyword arguments.
Here’s a Python code block to show how keyword arguments work:
def make_drawing(first_color, second_color, third_color):
print("I'm drawing with the following colors:")
print("First color:", first_color)
print("Second color:", second_color)
print("Third color:", third_color)
# You can call the function and specify the colors using keywords
make_drawing(first_color="blue", second_color="red", third_color="green")
In this code:
- We define a function called
make_drawing
with three parameters:first_color
,second_color
, andthird_color
. - Inside the function, we print out the colors in the order specified.
- When we call the
make_drawing
function, we use keyword arguments by saying which color should go with each keyword (e.g.,first_color="blue"
). This way, you're being super clear about which color you want in which spot.
(3) Default Arguments:
Imagine you have a friend who makes pizza, and you often order your favorite pizza from them. You always get cheese, tomato sauce, and pepperoni on your pizza, but sometimes you forget to specify what type of cheese you want. However, your friend knows that you usually like mozzarella cheese. So, you can tell your friend to put mozzarella cheese unless you tell them otherwise. This is just like using default arguments.
def make_pizza(topping1="cheese", topping2="tomato sauce", topping3="pepperoni", cheese="mozzarella"):
print("Making a pizza with the following toppings:")
print("- " + topping1)
print("- " + topping2)
print("- " + topping3)
print("- Cheese: " + cheese)
# You can call the function without specifying the cheese, and it will default to mozzarella
make_pizza()
In this code:
- We define a function called
make_pizza
with four parameters:topping1
,topping2
,topping3
, andcheese
. - Inside the function, we print out the toppings and the type of cheese.
- When we call the
make_pizza
function without specifying the cheese (i.e.,make_pizza()
), Python uses the default value of "mozzarella" for the cheese because we told it to do so in the function definition.
(4) Variable-Length Arguments:
Imagine you’re the pizza chef for a big pizza party. You invited your friends, but you don’t know exactly how many will come, so you want to make sure there’s enough pizza for everyone.
Variable-length arguments in Python are like telling your pizza chef, “I want to make pizza for all my friends, no matter how many come. I’ll give you a list of toppings, and you should put all of them on the pizza.”
So, you start listing the toppings you want on the pizza: “cheese,” “tomato sauce,” “pepperoni,” “mushrooms,” “onions,” and “olives.” You don’t have to count how many toppings there are; you just list them all.
Python understands this and puts all the toppings you mentioned on the pizza, whether there are a few or a lot, so that you have enough delicious pizza to share with all your friends at the party!
def make_pizza(*toppings):
print("Making a pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
# You can call the function with any number of toppings
make_pizza("cheese", "tomato sauce", "pepperoni", "mushrooms", "onions", "olives")
In this code:
- We define a function called
make_pizza
that takes*toppings
as a parameter, which means it can accept any number of toppings. - Inside the function, we loop through the
toppings
and print each one. - When we call the
make_pizza
function, we provide a list of toppings. You can add as many toppings as you like, and Python will put them all on the pizza when you make the function call.
(5) Keyword Variable-Length Arguments:
Imagine you’re making a big, special sandwich, and you want to add lots of ingredients to make it super yummy. You have your usual ingredients like bread, cheese, and lettuce, but you also want to add some extra things like pickles, tomatoes, and onions. Now, you don’t want to tell the person making your sandwich exactly how many extras you want every time because it can change depending on how hungry you are.
So, you tell the person, “I’d like my usual sandwich with these extras: pickles, tomatoes, and onions.” You’re using the names of the extras (pickles, tomatoes, and onions) to tell them what you want.
In Python, we can do something similar with functions. We can create a special kind of function that says, “I have my regular stuff, but I also want to add some extra things, and I’ll tell you what those extra things are using their names.”
Example:
def make_special_sandwich(bread, cheese, lettuce, **extras):
print("Regular ingredients:")
print("Bread:", bread)
print("Cheese:", cheese)
print("Lettuce:", lettuce)
print("\nExtra ingredients:")
for ingredient, amount in extras.items():
print(ingredient + ":", amount)
make_special_sandwich("whole wheat", "cheddar", "romaine", pickles=3, tomatoes=2, onions=1)
In this example, **extras
is indeed a dictionary that contains the extra ingredients and their amounts.
(6) ‘Self’ Arguments
Imagine you have a magic toy box, and this toy box can do special things, like jump and spin. But the toy box also needs to remember things about itself, like how many toys are inside or what color it is. To help the toy box remember these things, it has a little label with its name on it. That label is like the “self” in Python.
Here’s a Python code block to show how “self” works:
Example:
class MagicToyBox:
def __init__(self, color):
self.color = color # The toy box remembers its color
self.toys_inside = [] # The toy box remembers the toys inside
def add_toy(self, toy):
self.toys_inside.append(toy) # The toy box adds a toy inside
def show_info(self):
print("This is a", self.color, "toy box.")
print("It has", len(self.toys_inside), "toys inside.")
# Let's create a magic toy box and play with it
my_toy_box = MagicToyBox("blue")
my_toy_box.add_toy("teddy bear")
my_toy_box.add_toy("blocks")
my_toy_box.show_info()
In this code:
- We create a special toy box called
MagicToyBox
. This toy box has a color (like "blue") and can remember the toys inside. - Inside the
__init__
method, we useself
to remember the color and initialize an empty list to remember the toys inside. - We have a method called
add_toy
, and when we useself
inside it, we're telling the toy box to add a toy to its list of toys. - The
show_info
method usesself
to tell us information about the toy box, like its color and how many toys are inside. - Finally, we create a
my_toy_box
, which is an instance of theMagicToyBox
class. We add two toys inside it and then ask it to show us its information.
So, “self” in Python is like the label on a magic toy box that helps the toy box remember things about itself, like its color and what’s inside it.
So, when you create a function in Python, you can use these different types of arguments to make it easier to give instructions to your helper (the function) based on what you need to do.