User Defined Functions
Introduction to Functions
Functions are reusable blocks of code that perform specific tasks. While Python has many built-in functions like print() and len(), creating your own functions allows you to organize code, avoid repetition, and make programs more modular and easier to maintain.
Functions help you write cleaner, more organized code by grouping related operations together and allowing you to call them whenever needed.
Defining Your First Function
To create a function, use the def keyword followed by the function name, parentheses, and a colon. The function body is indented below the definition.
💡 Key Points
• Function definition uses def keyword
• Function name follows Python naming conventions (lowercase with underscores)
• Empty parentheses () mean the function takes no parameters
• Function code is indented
Functions with Parameters
Parameters allow functions to accept input values. When you define a function, you specify parameters inside the parentheses. When you call the function, you provide arguments (the actual values).
Why Use Functions?
Functions provide several important benefits:
- Code Reusability - Write once, use many times
- Organization - Group related code together
- Maintainability - Fix bugs in one place
- Readability - Descriptive function names explain purpose
- Modularity - Break complex problems into smaller parts
Function Examples
Here are practical examples of useful functions:
Best Practices
✅ Function Naming Tips
• Use descriptive names that explain what the function does
• Use lowercase letters and underscores (snake_case)
• Start with a verb: calculate, display, check
• Keep names concise but clear
💡 Important Notes
• Functions must be defined before they're called
• Parameters are local variables that only exist inside the function
• You can call a function as many times as needed