Write Python. Understand every error.

Starting Python in your browser…

Python basics · topic 14 of 25

Functions

A function is a named block of code that you can run whenever you need it. You define it with def, give it parameters in brackets, and send a result back with return.

def square(n):
    return n * n

print(square(7))   # 49

Defining a function does not run it. The code inside runs only when you call it, as in square(7).

return and print are different. print shows a value on the screen; return hands the value back to the caller, who can store it or use it in a calculation. A function without return gives back None.

Parameters can have default values, used when the caller leaves them out: def greet(name, greeting="Hello"):.

  • def name(parameters): then an indented body
  • return value sends a result back
  • Variables created inside a function exist only inside it
  • Test a function by calling it with different values

Key takeaways

  • def name(parameters): starts a function, and the indented lines below are what it runs.
  • return sends a result back. A function without return gives back None.
  • Variables created inside a function exist only inside it.
  • Test a function by calling it with different values, including unusual ones such as 0 or an empty list.

Common mistakes

Practise with these programs

Share this page:

Ctrl + Enter to run
Line 1, column 1Tab indents 4 spaces. Press Esc then Tab to leave the editor.