Exercise 16: 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:

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.

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 17: Time and date

Python can get the system time using the module time. To use this module type: import time.

The first line returns all variables required (year,month,day,hour,minute). The function time.time() returns ticks, which are system ticks every computer holds. The function localtime() converts these ticks into the actual human readable values.

Type the program shown below and run it:

Study drill

Try the exercises below

1. Print the date in format year-month-day

After completing these continue with the next exercise.

Exercise 18: Class

Python can create objects. An object is a collection of methods and variables.
Objects are created from classes.

If an object is created, the method __init__ is called. The self keyword is required in methods and variables to tell Python they belong to the class.

Example:

Study drill

Try the exercises below

1. Using the code above, create another object

2. Add a method to the class: location()

After completing these continue with the next exercise.