Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

Defining Functions

14 min 25 XP
Study loop Read Predict Run Tweak Prove Review
Lesson 1 of 6 · View course roadmap
Step 1

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 parameter
  • return sends a value back to the caller (and ends the function)
  • A function without return returns None
  • print shows a value; return hands 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() * 2 breaks.
  • Code after return never 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.

Step 2

Watch how it runs — line by line


        

Press play to watch Python execute this code, one line at a time.

Step 3

Try it yourself

Blank · autosaved

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”.

PYexample.py
+ Enter to run
Output appears here…
Step 4

Pass the challenge +25 XP

Blank · autosaved

Write a function celsius_to_fahrenheit(c) that returns c * 9 / 5 + 32. Then print the result of converting 0, 25 and 100.

Target output
32.0
77.0
212.0
PYchallenge.py
Run your code to check it…
Step 5

Check your understanding

1. What does a function return if it has no return statement?
2. What's the difference between print and return?
Last step

Your notes (saved on this device)

Tip: use and to move between lessons, K to search everything.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path