🎓 A1Learner
🔍

Python Functions

A function is a named block of code that can run again and again. One definition holds the steps.

The same lines again and again

Without a function, each greeting repeats the same two print lines.

print("Hello, friend!")
print("Welcome back.")
print("Hello, friend!")
print("Welcome back.")
print("Hello, friend!")
print("Welcome back.")

Make a function

The word def starts the function. The indented line is its block.

def greet():
    print("Hello!")

Call a function

Writing the name with brackets calls the function. Calling means asking it to run.

def greet():
    print("Hello!")

greet()

Call it again

One definition can serve many calls. Each call runs the block again.

def greet():
    print("Hello!")

greet()
greet()

Example

def greet():
    print("Hello, friend!")
    print("Welcome back.")

greet()
greet()
greet()

Key points

  • Function: a named block of code that you can run again and again
  • Use def to make a function
  • Use the function name with round brackets to call it
  • Define a function before you call it

In this example, def makes a function named greet. Its block prints two lines. The first greet() call runs the block once. The second call runs the same block again. The third call runs it one more time. Nothing prints until the first call. The next lesson shows how they work.

Note

A function can take inputs, called parameters.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What does the word def do in Python?