4. Functions, Dictionaries & Data Drills
Functions: Reusable Code, return & Scope
Stop repeating code: learn how to create your own commands with def, pass inputs into parameters, understand return vs print(), and see how local variables stay separate.
- Create reusable commands with def and pass inputs via parameters
- Know why return hands values back to code while print() only displays text
- Keep function variables safe and private using local scope
Suppose you are building an online store, and in 5 different places you need to add 10% tax to a price. If you copy-paste the same calculation 5 times—and later tax changes to 8%—you have to hunt down and fix all 5 places!
Instead, you can teach Python a brand-new command of your own using a function.
Creating Your First Function (def)
Think of a function like a coffee machine:
- You put inputs in (beans and water).
- It follows a recipe inside.
- It hands back a finished cup (
return).
Here is how to define (create) and call (run) a simple function:
def greet(name):
print(f"Hello, {name}! Welcome back.")
greet("Alex")
greet("Maya")Let's read each part:
defis short for define.greetis the command name we chose.(name)is a parameter—an input placeholder that receives"Alex"the first time and"Maya"the second time.- Notice
def greet(name):does nothing by itself! It only saves the recipe. The code inside runs only when you callgreet("Alex").
Sending an Answer Back (return vs print)
Parameters take inputs in; `return` hands the calculated result back so your variable can store it.
This is one of the most important lessons in Python, so read it slowly:
print()only displays text on the screen for human eyes, then forgets it!returnhands the calculated result back to your Python code so you can save it in a variable and keep using it!
Look at what happens when we use return:
def add_tax(price):
total = price * 1.10
return total
shirt_total = add_tax(20)
hat_total = add_tax(10)
print(f"Shirt: ${shirt_total}, Hat: ${hat_total}")
print(f"Both together: ${shirt_total + hat_total}")If add_tax had used print(total) instead of return total, then shirt_total would hold None (nothing!)—and shirt_total + hat_total would crash!
Also remember: return exits the function immediately. Any lines below return inside the same branch will not run.
Default Values (Optional Inputs)
Sometimes an input usually has the same value unless the caller wants to override it. Give a parameter a default value with =:
def apply_discount(price, percent=10):
savings = price * (percent / 100)
return price - savings
print(apply_discount(100)) # Uses default 10% -> 90.0
print(apply_discount(100, 25)) # Overrides with 25% -> 75.0Variables Inside Functions Stay Private ("Scope")
Any variable you create inside a function lives only while that function is running—it cannot accidentally mess up variables with the same name outside the function:
bonus = 50 # Outside variable
def test():
bonus = 999 # Separate temporary variable inside test()
print("Inside:", bonus)
test() # Prints: Inside: 999
print("Outside:", bonus) # Prints: Outside: 50 (untouched!)Try It Yourself in the Playground
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: Write a function to_fahrenheit(celsius) that returns (celsius * 9 / 5) + 32, then call it for 0 and 25 and print the returned values.
Quick Checkpoints
If a function uses print(x + 1) without a return statement, what does result = my_func(5) store in result?
Why did print('Outside:', bonus) still print 50 even after test() set bonus = 999 inside?