Skip to content

Python Programming · Week 7

Functions

Step 1 of 4

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:

def function_name(): # Function body # Code to be executed

Here's a breakdown of the function structure:

  • def: Keyword used to define a function
  • function_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

def greet(): print("Hello, World!") # Calling the function greet()

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:

  1. Define a function called my_function
  2. Inside the function, print a message of your choice
  3. Call the function to see the output

Hint: Remember to use the def keyword to define your function, and don't forget to call it after defining!
Starter code
# Define your function here
def my_function():
    print("Welcome to the world of functions!")

# Call your function here
my_function()

Write your code here