Function Arguments and Return Values
Functions often need inputs to work with. These inputs are called arguments. You can also make functions return values, which you can reuse elsewhere.
1. Positional Arguments
These are the most common. You pass values in the order the function expects them.
Positional Arguments
def multiply(x, y):
print("Product:", x * y)
multiply(2, 4)
x
gets2
,y
gets4
- The result printed is
Product: 8
Instead of just printing, functions can send a value back using return
.
Return Values
def multiply(x, y):
return x * y
result = multiply(2, 4)
print("Result:", result)
- The function calculates the product and returns it.
- We store the result in a variable and print it later.
2. Keyword Arguments
You can also pass values by name, which is more flexible.
Keyword Arguments
def introduce(name, age):
print(name, "is", age, "years old.")
introduce(age=12, name="Liam")
- You do not need to follow order if you use names.
- This improves clarity and avoids mistakes.
3. Default Values
Set a default value in the function definition to make arguments optional.
Default Values
def greet(name="friend"):
print("Hello,", name)
greet()
greet("Sophie")
- The first call uses the default ("friend").
- The second call overrides it with "Sophie".
Summary
Concept | Description |
---|---|
Positional arguments | Passed in order; e.g., func(2, 3) |
Keyword arguments | Passed by name; e.g., func(x=2, y=3) |
Default arguments | Optional values in the function definition |
return | Sends a value back to the caller |
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.