Python Functions

Hey friends 👋 welcome back, In the last lesson, we learned about loops, Today, we are going to learn about functions, which are reusable blocks of code that perform a specific task, Functions make programs organized, reduce repetition, and make it easier to debug.

Defining a Function

You can define a function using the def keyword, Example:

def greet(): print("Hello, welcome to Ridfortech!")
  • def tells Python you are defining a function

  • greet() is the name of the function

  • The code inside the function runs when you call it

Calling a Function

After defining a function, you need to call it to execute its code, Example:

def greet(): print("Hello, welcome to Ridfortech!") greet()

Output:

Hello, welcome to Ridfortech!

Functions with Parameters

Functions can take inputs, called parameters, to make them more flexible, Example:

def greet_user(name): print("Hello,", name, "welcome to Ridfortech!") greet_user("Yusuf") greet_user("Adeleke")

Output:

Hello, Yusuf welcome to Ridfortech! Hello, Adeleke welcome to Ridfortech!

Functions with Return Values

Functions can return a value using return, Example:

def add_numbers(a, b): return a + b result = add_numbers(5, 10) print("The sum is", result)

Output:

The sum is 15

Practice Time

Create a Python file called functions.py and try these exercises, 1, Define a function to greet the user with their name, 2, Define a function to calculate the square of a number and return it, 3, Define a function to add three numbers and return the sum, 4, Call your functions with different values and print the results

Great job, You just learned how to organize your code into reusable blocks using Python functions, In the next lesson, we will explore Python Lists, where we will learn how to store multiple values in a single variable, We will soon be launching our YouTube channel, where we are going to post step-by-step video tutorials on Python and other tech skills, These videos will make learning easier and more visual, helping beginners follow along confidently.