About Lesson
Functions in Python are reusable blocks of code that perform specific tasks. They help organize code, reduce repetition, and make programs more modular and easier to maintain.
1. What is a Function?
A function is a block of organized, reusable code designed to perform a single, related action. Python provides two types of functions:
- Built-in functions: Predefined functions like
print()
,len()
, etc. - User-defined functions: Functions that you define yourself using the
def
keyword.
2. Why Use Functions?
- Code Reusability: Write once, and reuse multiple times.
- Improved Readability: Simplify complex programs by breaking them into smaller, understandable parts.
- Maintainability: Easier to debug and modify.
- Avoid Redundancy: Reduce repetitive code.
3. Creating a Function
Syntax
def function_name(parameters):
"""
Optional docstring: Explains what the function does.
"""
# Function body
return output # Optional
def
: Keyword used to define a function.function_name
: Name of the function, which follows Python’s naming conventions.parameters
: Variables passed into the function (optional).return
: Specifies the output of the function (optional).
Examples of Functions
Example 1: A Simple Function
def welcome():
print("Hello, welcome to Python!")
# Calling the function
welcome()
Example 2: Function with Parameters
def welcome_user(name):
print(f"Hello, {name}! Welcome to Python!")
# Calling the function with an argument
welcome_user("Infovistar")
5. Function with Return Value
A function can return a result using the return
statement.
def add_numbers(a, b):
return a + b
# Call the function and store the result
result = add_numbers(5, 3)
print("The sum is:", result)
By mastering functions, you’ll write cleaner, more efficient, and more scalable Python programs!