Skip to content

Scope


Related course:

Scope

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)

Example:

#!/usr/bin/env python3

balance = 0

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

addAmount(5)
print(balance)

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.

Exercises

Try the exercises below:

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

After completing these continue with the next exercise.

Answers

Multiple return
Time and Date

Be First to Comment

    Leave a Reply