livepython.net
CHAPTER 15Python Functions
15.1  FUNCTIONS

Python Functions: Define and Call Your Own

What Is a Function in Python?

A function is a named block of code that does one job. You write the code once, give it a name, and then run it whenever you want by calling that name.

You already know the idea from chapter 2: print() is a function, a named mini-machine. So are len(), input(), int() and sorted(). They are built-in functions: Python made them for you. In this chapter, you'll build your own.

Think of it like a recipe card. You write the steps for pancakes once and give the card a title. Whenever you want pancakes, you don't write the steps again: you pick up the card called "pancakes" and follow it.

PYTHONedit me
def say_hello():
    print("Hello!")
    print("Welcome to LivePython.")

say_hello()
say_hello()
OUTPUT
Hello!
Welcome to LivePython.
Hello!
Welcome to LivePython.

Two lines of code, written once, printed twice.

Two steps: define, then call

StepWhat you writeWhat happens
Definedef say_hello(): and an indented bodyPython remembers the lines under that name. Nothing prints yet.
Callsay_hello()Python runs those lines, top to bottom.
  • Built-in functions come with Python: print(), len(), input().
  • Your own functions are made with def, then used exactly the same way: the name, then brackets.

Common beginner doubt: "Is a function the same as a loop?" No. A loop repeats lines right where it is, straight away. A function stores lines under a name, and runs them only when, and wherever, you call it.

A function is a named block of code: define it once, call it by its name whenever you need it.

your turnPredict the output

What will this print?

def cheer(): print("Go team!") cheer() print("Done") cheer()
Your turn! What will this code show on the screen?
your turnPick the right idea

Which one is a built-in function?

Think about it, then pick one.

Define a Function with def

You define (create) a function with the keyword def, short for "define". The lines that belong to the function are its body.

Think of it like saving a contact on your phone: you type the name and the number once. Saving it doesn't call anyone. It only means you can call later, by name.

PYTHONedit me
def greet():
    print("Hi, Sunny!")
    print("Nice to see you.")

print("The function is ready.")
OUTPUT
The function is ready.

Only the last line printed! Defining a function stores its body. It doesn't run it.

The five parts

  1. def, the keyword that starts a function.
  2. The name: the same rules as variable names from chapter 4. Small letters, underscores between words, no spaces, no digit at the start.
  3. Brackets (). Empty for now. In the next topic, you'll put values in them.
  4. A colon : at the end of the line, just like an if (chapter 8).
  5. The body: the lines indented by 4 spaces. It ends at the first line that isn't indented.

A good function name is a verb that says the job: greet, show_menu, print_receipt. Leave an empty line after the body, so it's easy to see where the function ends.

Avoid: a missing colon

PYTHONedit me
def greet()
    print("Hi, Sunny!")
OUTPUT
SyntaxError: expected ':'

Avoid: a body that isn't indented

PYTHONedit me
def greet():
print("Hi, Sunny!")
OUTPUT
IndentationError: expected an indented block after function definition on line 1

Don't be scared of these errors! They're the same ones you met with if. Python is telling you exactly what's missing: a colon, or 4 spaces.

def, a name, brackets, a colon, then an indented body. Defining stores the function; it doesn't run it.

your turnFill the gap

Complete the function

? greet(): print("Hi") greet()

It should print: Hi

Which piece makes this code work?
your turnSpot the bug

Which line breaks?

One line stops this program. Tap it.

Call a Function in Python

To call a function means to run it: write its name, then brackets (). Python jumps into the body, runs it from top to bottom, then comes back to the line after the call.

Think of it like a saved song on your phone: saving it plays nothing. Each time you press play, it plays from the start.

PYTHONedit me
def draw_line():
    print("-" * 12)

draw_line()
print("Sunny's Menu")
draw_line()
for dish in ["Tea", "Samosa"]:
    print(dish)
draw_line()
OUTPUT
------------
Sunny's Menu
------------
Tea
Samosa
------------

The rules

  • Write the brackets, even when they're empty: draw_line().
  • Call a function as many times as you like: three calls, three lines above.
  • You can call it anywhere: inside a loop, inside an if, even inside another function.
  • Define first, then call. Python reads your file from top to bottom.

Avoid: calling before the def

PYTHONedit me
say_hi()

def say_hi():
    print("Hi!")
OUTPUT
NameError: name 'say_hi' is not defined

Don't be scared of this error! It's saying Python hasn't met the name say_hi yet. When it reads line 1, the def further down hasn't run. Move the call below the function.

Avoid: forgetting the brackets

PYTHONedit me
def say_hi():
    print("Hi!")

say_hi
OUTPUT

No error, and no output either. say_hi without brackets only names the function, like pointing at the play button without pressing it. The brackets are what press it.

Common beginner doubt: "Where should I put my functions?" At the top of your file, under any comments. Then the main code that calls them goes at the bottom. That way every function is defined before it's called.

Call a function with its name and brackets, as often as you like, but only after its def.

your turnOrder the lines

Put the lines in order to print Welcome! then Bye

  1. print("Bye")
  2. def welcome():
  3. print("Welcome!")
  4. welcome()
These lines are mixed up. Put them back in order, then press Check.
your turnPredict the output

What will this print?

def beep(): print("Beep") for i in range(3): beep()
Your turn! What will this code show on the screen?

Why Use Functions?

Functions make your code reusable (write it once, use it many times) and readable (a good name tells you what a group of lines does).

Think of it like a TV remote: there's one "volume up" button, and you press it whenever you need it. Nobody builds a new remote each time they want it louder.

Four reasons to use a function

  • No copy and paste. Lines you need in many places live in one place.
  • Fix once. Change the function, and every call uses the new version.
  • A name explains. print_receipt() tells you what happens, without reading the lines.
  • Small steps. A big problem becomes a few small, named jobs, like the steps of an algorithm in chapter 3.

Functions can call functions

The body of a function can call another function:

PYTHONedit me
def draw_line():
    print("=" * 20)

def show_title():
    draw_line()
    print("  LivePython Quiz")
    draw_line()

show_title()
print("Question 1: What is 2 + 3?")
OUTPUT
====================
  LivePython Quiz
====================
Question 1: What is 2 + 3?

show_title() uses draw_line() twice. Want dashes instead of =? Change one line in draw_line(), and the whole title changes.

Avoid: the same lines again and again

print("=" * 20)
print("  LivePython Quiz")
print("=" * 20)
print("Question 1: What is 2 + 3?")
print("=" * 20)
print("  LivePython Quiz")
print("=" * 20)

This works, but every change has to be made in many places, and it's easy to miss one. When you see the same lines twice, it's time for a function.

Common beginner doubt: "When should I make a function?" Two good signs: you're about to copy some lines, or a group of lines does one clear job that you can give a name to.

Use a function when you'd copy lines, or when a job deserves a name.

your turnPick the right idea

You print the same 4-line header in 5 places. What's the best fix?

Think about it, then pick one.
your turnType the output

Remember counting with a for loop?

total = 0 for n in range(1, 4): total += n print(total)
Read the code line by line, then type the output exactly.

Practice: Functions

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 130.Python Program to Print a Welcome Banner Using a FunctionEasySolve
  2. 131.Python Program to Draw a Box Using FunctionsMediumSolve