Functions
A Function is a named block of code that executes only when it is called.
Functions allow programmers to divide large programs into smaller and manageable parts.
What is a Function?
A function is a group of instructions that works together to complete a task.
-
Reusable: You can use the same function 100 times without typing the code again.
-
Organized: It breaks big, scary programs into small, easy-to-manage pieces.
-
Efficient: It saves time and helps you avoid making mistakes.
Why Functions are Important
Functions play a major role in software development.
They help:
- reduce code duplication
- improve readability
- simplify debugging
- increase code reusability
- make programs more organized
Real-World Function Scenarios
-
Calculator: When you press the "+" button, a function runs to add the numbers.
-
YouTube Search: When you type a word, a function finds the videos for you.
-
Food App: When you click "Order," a function sends your request to the restaurant.
-
Video Games: A function controls how high your character jumps every time you press a button.
Syntax
To make a function, you use the def keyword (which is short for "define").
The Pattern:
def function_name():
# Write your instructions here
Example: Making a Greeting Machine
def greet():
print("Welcome to Python")
# This is called 'calling' the function
greet()
Output
Welcome to Python
Advantages of Functions
| Advantage | Description |
|---|---|
| Code Reusability | Write once and use many times |
| Easy Maintenance | Easy to modify code |
| Better Organization | Programs become structured |
| Reduced Errors | Less duplicate code |
| Faster Development | Saves time and effort |
Important Terms in Functions
| Term | Meaning |
|---|---|
| Function Definition | Creating a function |
| Function Call | Executing a function |
| Parameter | Input sent to function |
| Return Value | Output returned by function |
Summary
-
Don't Repeat Yourself: Functions help you avoid writing the same code over and over.
-
Teamwork: In big companies, different coders work on different functions at the same time.
-
Input & Output: Functions can take information (parameters) and give back results