Learn Python
Lesson 1 - Introduction To Python
Lesson 2 - Basic Python Syntax
Lesson 3 - Control Flow
Lesson 5 - Basic Data Structures
Lesson 6 - Exception Handling
Lesson 7 - Modules And Packages
Lesson 8 - Basic String Operations
Lesson 9 - Object-Oriented Programming (OOP)
Functions are the most used component in programming. It's a block of reusable code that performs a specific task.
Functions allow you to organize code into logical units, making it easier to read, understand, and maintain.
In Python, functions are defined using the def
keyword followed by the function name and parentheses.
Have a look at the following line of code:
print("Good Morning, Alex");
This will greet your friend Alex.
Now, think you've five friends. How do you greet them?
You might think to write some code as follows,
print("Good Morning, Alex") print("Good Morning, John") print("Good Morning, Devid") print("Good Morning, Felix") print("Good Morning, Ethen")
However, there is a very easy and smart way to do this. Follow the below example:
def greet(name): print("Hello, "+ name); greet("Alex") greet("John") greet("Devid") greet("Felix") greet("Ethen")
In the above example, we declared a function greet()
that takes a name to greet. You don't have to write the line print("Good Morning, Alex")
for each of your friends. All you need is to pass their name to the greet()
function.