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:
-
deftells 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:
Output:
Functions with Parameters
Functions can take inputs, called parameters, to make them more flexible, Example:
Output:
Functions with Return Values
Functions can return a value using return, Example:
Output:
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.
0 Comments