Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

Lesson 4 - Functions

4.1 Defining Functions

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.