Functions are reusable blocks of code that perform specific tasks. They help in breaking down complex problems into smaller, manageable pieces, making your code more organized and easier to understand.
Key Concept: Functions
Functions allow you to write code once and use it multiple times, promoting code reusability and reducing redundancy.
Anatomy of a Function:
Here's a breakdown of the function structure:
def: Keyword used to define a functionfunction_name: The name you give to your function(): Parentheses for parameters (empty in this case):: Colon to start the function body- Indented code block: The actual code of the function
Example: Simple Greeting Function
In this example, greet is the function name. When called, it prints "Hello, World!".
Guided Exercise: Create Your Own Function
Now, let's create a function that prints a custom message. Follow these steps:
- Define a function called
my_function - Inside the function, print a message of your choice
- Call the function to see the output
def keyword to define your function, and don't forget to call it after defining!
# Define your function here
def my_function():
print("Welcome to the world of functions!")
# Call your function here
my_function()