By the end of this lesson, you will be able to:
:information_source: Function is a block of organized and reusable code that performs a specific task. It only runs when you call it.
Functions help programmers simplify the coding process. They create organized, reusable code that can perform specific actions whenever you need them.
Python has two categories of functions:
You've already used many built-in functions:
print()
- Shows output on screeninput()
- Gets input from userint()
- Converts to integerstr()
- Converts to string:bulb: Want to explore more built-in functions? Check out: Python Built-in Functions Reference
Creating Your Own Functions
Sometimes you need to customize your own function for specific tasks. That's when you create user-defined functions.
When you create a function, you give it a meaningful name. Then, instead of typing the entire block of code repeatedly, you just type the function name!
:sparkles: Advantages of Functions
- Avoids repetition - Write once, use many times!
- Increases readability - Makes your program easier to understand
:books: Key Terms to Remember
Before using functions, let's learn these important terms:
- Call - Using a function (running it)
- Define - Creating a function using the
def
keyword- Parameter - A variable in the function that receives a value
- Argument - The actual value you pass to the function
- Return value - Data that the function sends back using the
return
keyword:emoji: Two Important Phases
1️⃣ Define/Create Phase
python
def function_name(parameters): # Block of code to execute return value # (optional)
2️⃣ Call Phase
pythonfunction_name(arguments)
Function Syntax
The picture below shows the syntax used to create and call a function.
:emoji: Real-Life Example
Think of a function like a recipe for baking a cake! Here's how it works:
python
def recipe(ingredients): mix the ingredients add milk bake the cake in oven return cake
Graphical Representation:
:emoji: What We'll Learn
We'll explore three types of functions:
- Function with no parameter - Simple functions that don't need input
- Function with parameter - Functions that accept input values
- Function with return value - Functions that give back results
1️⃣ Function with No Parameter
The simplest function doesn't need any parameters. You just define it with a name and the code to execute. Then call it without any arguments!
python
def greet(): print("Hello, world") greet()
Expected output:
outputHello, world
note This function always does the same thing every time you call it.
Sometimes you need to pass values into a function to get different results. Here's how to create a function with parameters:
def greet(name):
print("Hello, ", name)
greet("Chong Wei")
Expected output:
Hello, Chong Wei
You can give parameters default values. If you don't provide an argument, the function uses the default value! Code:
def greet(name="World"):
print("Hello, ", name)
greet()
Expected output:
Hello, World
Code:
greet("Sharvin")
Expected output:
Hello, Sharvin
Functions can have two or more parameters:
def greet(name, age):
print("Hello,", name)
print("You are", age, "years old")
greet("Chong Wei", "18")
Expected output:
Hello, Chong Wei
You are 18 years old
Don't want to remember the parameter order? Use keyword arguments!
def greet(name, age):
print("Hello,", name)
print("You are", age, "years old")
greet(age="12", name="Sharvin")
Expected output:
Hello, Sharvin
You are 12 years old
:bulb: Keyword arguments let you specify which parameter gets which value, regardless of order!
3️⃣ Function with Return Value
Sometimes you need to get a value back from a function. Use the
return
keyword to send data back to your main code!python
def add(num1, num2): return num1 + num2 total = add(2,3) print(total)
Expected output:
output5 ```note
The return value can be stored in a variable for later use!
Functions are powerful tools that:
Remember the two phases: Define (create) and Call (use)!
Code with AI: Try using AI to create and learn about functions and modules.
Prompts:
Try these exercises to master functions: