User-defined functions allow you to write reusable blocks of code, making your programs modular, organized, and easier to maintain.
1) Introduction
A function is a named block of code that performs a specific task. Python has built-in functions, but you can also create your own user-defined functions to reuse code wherever needed.
Benefits of user-defined functions:
- Reduces repetition in code
- Makes code modular and organized
- Makes debugging and testing easier
- Enhances readability and maintainability
2) Defining a Function
Use the def keyword followed by the function name, parentheses, and a colon. The function body is indented.
# Defining a simple function
def greet():
"""Prints a greeting message"""
print("Hello, welcome to Python!")
# Defining a function with parameters
def greet_person(name):
"""Greets the person by name"""
print("Hello,", name, "!")
Common Mistakes:
- Forgetting the colon (
:) after the function definition →SyntaxError - Not indenting the function body properly →
IndentationError - Using invalid characters or starting function name with a number →
SyntaxError
3) Calling a Function
To execute the function, use its name followed by parentheses. Pass arguments if required.
# Calling functions
greet() # Output: Hello, welcome to Python!
greet_person("Alice") # Output: Hello, Alice!
# Calling a function multiple times
for name in ["Bob", "Charlie"]:
greet_person(name)
Common Mistakes:
- Forgetting parentheses while calling → prints function object instead of executing
- Passing wrong number of arguments →
TypeError - Calling function before it is defined →
NameError
💡 Try It Yourself
- Define a function to print your name and call it.
- Define a function that takes two numbers and prints their sum.
- Call the function multiple times with different arguments.
- Try defining a function without colon or wrong indentation to see the error.
No comments:
Post a Comment