5.1 Defining and Calling Functions
We learn how to define and call our own functions, the fundamental blocks for organized and reusable code.
A function is a self-contained, named block of code that performs a specific, well-defined task. Functions are the key to writing organized, readable, and, most importantly, reusable code. They follow the "Don't Repeat Yourself" (DRY) principle, which means that instead of writing the same code over and over, you define it once within a function and call it as many times as needed.
To define a function in Python, you use the `def` keyword, followed by the function name, parentheses `()`, and a colon `:`. Any code that forms the body of the function must be indented.
# Defining a simple function without parameters
def welcome_message():
"""This function prints a welcome message."""
print("Welcome to the world of Python!")
print("We are happy you are here learning to code.")
# Calling the function
print("First call:")
welcome_message()
print("-" * 30)
print("Second call:")
welcome_message()
Tip!
The text inside triple quotes (""") immediately after the function definition is called a docstring. It is a best practice for documenting what the function does.
Explore More with AI
Use AI to generate new examples, delve deeper into theory, or get your questions answered.