Skip to content

Functions in Python

Programming Python Difficulty 1/5

Beginning of the lesson

Functions in Python

Teach Python a new trick once, then reuse it forever

Big Idea: A function is a named block of code that does one job. You define it once with def, then call it whenever you need it — instead of copying the same lines again and again.
By the end you will be able to:
  • define a function with def and call it,
  • send information in with parameters and arguments,
  • send a result back with return,
  • tell a local variable from a global one (scope),
  • explain why functions make code shorter and clearer.

1. What is a function?

A function is like a little machine. You give it something, it does its job, and it can hand something back. A juicer is a good picture: you put in oranges (the input), it squeezes (the work), and out comes juice (the output). You built the juicer once, but you can use it every morning.

In code, a function lets you package a set of steps under one name. Then you run all those steps just by writing the name — this is called calling the function.

2. Defining a function with def

You create a function with the keyword def, a name, round brackets (), and a colon :. The steps inside are indented (usually 4 spaces).

def greet():
    print("Hello!")
    print("Welcome to Python.")

greet()
greet()

Output:

Hello!
Welcome to Python.
Hello!
Welcome to Python.

Notice: writing def greet(): only defines the function — nothing prints yet. The code runs only when you call it with greet(). We called it twice, so the message appears twice.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers