1. Introduction to Functions
1.1 What are Functions?
Functions are self-contained blocks of code that perform specific tasks. They are fundamental building blocks that help organize code, promote reusability, and make programs more modular and maintainable.
Benefits of Functions:
- Code Reusability: Write once, use multiple times
- Modularity: Break complex problems into smaller, manageable pieces
- Maintainability: Easier to debug, test, and modify
- Readability: Makes code more organized and understandable
- Abstraction: Hide implementation details from the caller
1.2 Python vs C Functions Comparison
Aspect | Python | C |
---|---|---|
Declaration | Not required | Function prototype usually required (unless defined before use) |
Definition | def function_name(): |
return_type function_name() { } |
Return Type | Dynamic (any type) | Must be explicitly declared |
Parameters | Dynamic typing | Static typing required |
Call Before Definition | Allowed | Requires prototype |
Multiple Return Values | return a, b |
Use pointers or structures |
Python Example:
def add_numbers(a, b):
return a + b
result = add_numbers(5, 3)
print(result) # Output: 8
C Equivalent:
#include <stdio.h>
// Function declaration (prototype)
int add_numbers(int a, int b);
int main() {
int result = add_numbers(5, 3);
printf("%d\n", result); // Output: 8
return 0;
}
// Function definition
int add_numbers(int a, int b) {
return a + b;
}