Python Functions
Conditions and loops describe the steps of a task. When those steps form a useful operation, a function gives that operation a name so it can be called again.
A function is a reusable block of code that performs a specific task. It only runs when called, which helps avoid repeating the same instructions throughout a program. Functions also make code easier to organize and maintain.
Creating a Function
In Python, a function is defined using the def keyword, followed by its name and parentheses ().
def say_hello():
print("Hello, welcome to Python!")This creates a function named say_hello that prints a greeting message. Indentation is here important as it shows which lines belong inside the function.
Calling a Function
To run the function, simply write its name followed by parentheses:
say_hello()Output
Hello, welcome to Python!
You can call it as many times as needed:
say_hello()
say_hello()
say_hello()Output
Hello, welcome to Python!
Hello, welcome to Python!
Hello, welcome to Python!
Functions are one of Python’s most useful tools — they make your code cleaner, shorter, and easier to reuse.