Defining Functions
Lesson 1 of 6 · View course roadmap
Learn the idea
A function is a named, reusable block of code. Define with def, hand data in through parameters, get data back with return:
def greet(name):— definition with one parameterreturnsends a value back to the caller (and ends the function)- A function without
returnreturnsNone printshows a value;returnhands it back — they are not the same!
Good functions do one thing and are named with verbs: calculate_total, send_email, is_valid.
Where you'll use this
Every library you'll ever import — requests, pandas, Flask — is a box of functions. Professional codebases enforce small single-purpose functions in code review; it's the #1 readability rule.
Common mistakes
- Confusing print with return: a function that prints but returns None can't be used in further calculations —
total = get_price() * 2breaks. - Code after
returnnever runs. - Calling with the wrong argument count → TypeError telling you exactly what's missing. Read it.
Pro tip
Give every function a one-line docstring — def area(w, h): """Return the area of a w × h rectangle.""" — then help(area) works, and so does your editor's tooltip.
Watch how it runs — line by line
Press play to watch Python execute this code, one line at a time.
Try it yourself
The lesson example is loaded and ready — press Run, then change something and run it again. Breaking it is part of learning. Want a clean slate? Tap “New blank”.
Output appears here…
Pass the challenge +25 XP
Write a function celsius_to_fahrenheit(c) that returns c * 9 / 5 + 32. Then print the result of converting 0, 25 and 100.
32.0 77.0 212.0
Replace pass with a return statement, then call the function inside print().
def celsius_to_fahrenheit(c):
return c * 9 / 5 + 32
print(celsius_to_fahrenheit(0))
print(celsius_to_fahrenheit(25))
print(celsius_to_fahrenheit(100))
Run your code to check it…
Check your understanding
Your notes (saved on this device)
Tip: use ← and → to move between lessons, ⌘K to search everything.