← Back to Functions
πŸ“–

Functions β€” What & Why

1 of 6

Functions β€” What & Why

Functions are reusable blocks of code you give a name to, so you can run them whenever you want without rewriting the same code.


Without a Function (Repetitive)

print("Welcome, Alex!") print("Your adventure begins!") print("Welcome, Sam!") print("Your adventure begins!") print("Welcome, Jordan!") print("Your adventure begins!")

That's a lot of copy-paste! What if you want to change the message? You'd have to edit it 3 times.

With a Function (Reusable)

def welcome(name): print(f"Welcome, {name}!") print("Your adventure begins!") welcome("Alex") welcome("Sam") welcome("Jordan")

Now if you want to change the message, you only change it once inside the function.


Anatomy of a Function

def function_name(parameter1, parameter2): # code goes here (indented!) return result
  • def β€” keyword that says "I'm creating a function"
  • Function name β€” what you call it (use snake_case)
  • Parameters β€” inputs the function receives (in parentheses)
  • Body β€” the indented code that runs when you call it
  • return β€” sends a value back (optional)

Return vs Print

This is the most important thing to understand:

# This function PRINTS (shows text, but gives back nothing) def greet(name): print(f"Hi {name}!") # This function RETURNS (gives back a value you can use) def double(number): return number * 2

Why does it matter?

# With return β€” you can save and use the result result = double(5) print(result) # 10 print(double(5) + 3) # 13 # With print β€” the value is gone after printing result = greet("Alex") # Prints "Hi Alex!" but... print(result) # None! There's nothing to save

Rule of thumb:

  • Use print when you just want to display something
  • Use return when you need to use the answer later

Calling a Function

def add(a, b): return a + b # Calling the function: answer = add(3, 5) print(answer) # 8 # You can also use it directly: print(add(10, 20)) # 30

The values you pass in (3, 5) are called arguments. They get matched to the parameters (a, b) in order.

πŸ’»

Try it yourself

Code: Functions β€” What & Why

Loading Python runtime…
Python …
Loading...
Output
Click "Run" to execute your code...
ℹ️ About this Python environment

βœ… Standard library: heapq, collections, itertools, math, random, functools, datetime, bisect

βœ… Functions, classes, recursion, print()

❌ No file system, subprocess, OS access, or network requests

❌ No pip install (all supported modules are pre-loaded)

⏱️ 5 second execution time limit