Functions (Definition · Parameters · Return Values)
What Is a Function?
Definition: A reusable bundle of code that performs a specific task
Why use functions?
- You don't need to write the same code over and over
- Code becomes more readable and easier to maintain
- You can solve complex problems by breaking them into small units
Defining and Calling Functions
Basic structure
python
def function_name(parameter):
# what the function does
return return_valueExample
python
# Define the function
def add(a, b):
result = a + b
return result
# Call the function
answer = add(3, 5)
print(answer) # output: 8Parameters and Return Values
- Parameter: a value the function receives as input
- Return value: a value the function outputs
python
# 2 parameters, 1 return value
def multiply(a, b):
return a * b
result = multiply(4, 5)
print(result) # output: 20
# When there is no return value
def greet(name):
print(f"Hello, {name}!")
greet("Jo") # output: Hello, Jo!
# When there are no parameters
def get_today():
return "January 15, 2024"
print(get_today()) # output: January 15, 2024Setting Default Values
If you give a parameter a default value, you can leave that value out when calling the function.
python
def introduce(name, age=20):
print(f"Hi, I'm {name} and I'm {age} years old")
introduce("Jo") # output: Hi, I'm Jo and I'm 20 years old
introduce("Amy", 25) # output: Hi, I'm Amy and I'm 25 years oldSummary
| Concept | Summary |
|---|---|
| Function | A reusable bundle of code → increases code reuse |
| Parameter | A value the function receives as input → run the same function with different values |
| Return value | The result the function gives back → store it in a variable and use it again |
Reference: personal Notion study notes (onboarding course)
