Functions: Reusable Code Blocks 🧩
A function is a reusable block of code that performs a specific task.
Defining a Function
def greet():
print("Hello!")
# Call the function
greet() # Output: Hello!
Why Use Functions?
- Reusability: Write once, use many times
- Organization: Break complex programs into smaller pieces
- Readability: Give meaningful names to operations
- Testing: Easier to test individual parts
Function Anatomy
def function_name():
# Code block (indented)
# This runs when function is called
pass
Key Points:
- Start with
def
keyword
- Give it a descriptive name
- Don't forget the colon
:
- Indent the body (4 spaces)