Functions

Creating Functions

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?

  1. Reusability: Write once, use many times
  2. Organization: Break complex programs into smaller pieces
  3. Readability: Give meaningful names to operations
  4. 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)
Visualizer
function
say_hello()
None (prints to console)

Interactive Visualization

python
Loading...
Output
Run execution to see output...