Skip to content

Exercise 16: Scope

Alternative course


Variables have a certain reach within a program. A global variable can be used anywhere in a program, but a local variable is known only in a certain area (function, loop)


#!/usr/bin/env python3

balance = 0

def addAmount(x):
    global balance
    balance = balance + x


In the program above, balance is a global variable. It can be used anywhere in the code. But the variable x can only be used inside addAmount.

What you see if successful

You should see the global variable has changed value.

Study drill

Try the exercises below:

1. Add a function reduce amount that changes the variable balance

After completing these continue with the next exercise.


Exercise 15: Multiple return
Exercise 17: Time and Date
Published inUncategorized

Be First to Comment

    Leave a Reply