Lesson 26 of 4065%
(Progress persistence is disabled until Phase 9)
Python
Beginner
Functions
Create reusable blocks of code.
Functions
What You’ll Learn
A function is a block of code which only runs when it is called. You’ll learn how to define and execute them.
Defining a Function
In Python, a function is defined using the def keyword.
def my_function():
print("Hello from a function!")
Calling a Function
To call a function, use the function name followed by parenthesis.
def my_function():
print("Hello from a function!")
# Call it!
my_function()
my_function()
Expected Output:
Hello from a function!
Hello from a function!
Why use Functions?
Functions allow you to reuse code instead of rewriting it. If you need to fix a bug or change behavior, you only have to update the code inside the function, and it applies everywhere the function is called!