Functions in Python

Functions are named blocks of code that are designed to do one specific job. When you want to perform a particular task that you’ve defined in a function, you call the name of the function responsible for it. If you need to perform that task multiple times throughout your program, you don’t need to type all the code for the same task again and again; you just call the function dedicated to handling that task, and the call tells Python to run the code inside the function.

In Python, you define a function using the def keyword. Here is an example:

def greet_user():
“””Display a simple greeting.”””
print(“Hello!”)

The first line that ends in a colon is known as the function definition. The indented lines that follow the function definition make up the function body.

The second line of code is know as a docstring. A docstring is a comment, which in this example describes what the function does. Docstrings are enclosed in triple quotes, which Python looks for when it generates
documentation for the functions in your programs.

When you want to use this function, you call it. A function call tells Python to execute the code in the function. To call a function, you write the name of the function, followed by any necessary information in
parentheses, as shown below:

greet_user()

The call to the greet_user() function prints Hello!

Here is the complete code (function definition along with function call):

def greet_user():
“””Display a simple greeting.”””
print(“Hello!”)

greet_user()

Leave a Reply

Your email address will not be published. Required fields are marked *