What are Functions #
In programming, writing reusable code is an essential part that helps us work more efficiently. It reduces the time to perform a task, breaks down complex tasks into smaller parts, and reduces the chances of bugs in the program. Writing a function is a way of creating a set of commands that can be called repeatedly without having to rewrite the code every time.
In Python, the functions that come with the program are called built-in functions. We have already used some of them in previous lessons, such as type, which is used to find the data type(), or print(), which is used to display the result.
Creating a New Function #
The syntax for creating a function in Python is to use the def keyword followed by the name of the function you want to create and the (): sign. Then, the code block inside the function will be the code for that gets executed when the function is called. Notice the leading space before the inner code block inside the function. We will explain this in the next lesson.
def function_name():
# code block for the function
Here's an example of creating a function:
def print_hello_world():
print("Hello World!")
print_hello_world()
print_hello_world()
Output:
Hello World!
Hello World!
In this example, we have created a function called print_hello_world that will print the string "Hello World!" when called. We then call the function twice, and each time it prints the same string.
Exercise #
Create your own function and call the function
Tests #
- Create a new function named
say_hi say_hi()should print out the word"Hello World!"once when called.- Call the function once.
Getting Started with Python
Data Types
Python Functions
Statements in Python
Basic Debugging in Python
Basic Algorithm
Object-Oriented Programming
Error Handling
Intermediate Algorithm
Python Modules