CodeBlanks Logo Icon CodeBlanks

def

Learn to define functions with def.

Defining functions with def

A function is a reusable block of code. It is defined with the def keyword:

def greet():
    print("Welcome")

The function body is indented; this is how Python marks a block. The function is called with greet().

Functions prevent code repetition and split a program into parts. This improves both readability and maintainability.

Calling a function

A defined function is run by calling its name with parentheses:

def greet():
    print("Welcome")

greet()   # Welcome

Without parentheses, greet just refers to the function object; it does not call it. This is a common mistake.

You can call a function as many times as you like; this prevents code repetition.

Practice Write a welcome function

Define a function called greet that prints print("Welcome"). Then call it with greet().

Starter code

main.py
# Define the greet function

Sample solution

main.py
def greet():
    print("Welcome")
greet()

Expected output

Welcome

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is a valid function definition?

  • def greet(): ... Correct answer
  • function greet(): ...
  • greet = def(): ...
  • func greet(): ...

Explanation: It is defined as def greet():.

2 Complete the function call

Question
greet____
Answer
greet()

Explanation: greet() calls the function.

3 Match the function parts

Term Meaning
def Definition keyword
greet Function name
() Call parentheses
: Body start

All lessons in Beginner