9.11.3. Variables and names

9.11.3.1. Using variables

Now you can output things with print() and you can do math. The next step is to learn about variables. In programming, a variable is nothing more than a name for something and helps making the code easier to read. In Python the equal sign (=) is used to assign a value to a variable.

 1width = 10
 2depth = 5
 3height = 20
 4
 5area_size = width * depth
 6volume = area_size * height
 7
 8# Variables can be output with print()
 9print(area_size)
10
11# The output of strings and variables can be combined
12print("Volume:", volume)
50
Volume: 1000

A value can be assigned to several variables simultaneously as seen below. Additionally, you will learn how to make strings that have variables embedded in them. You embed variables inside a string by using specialized format sequences (in this case %d) and then putting the variables at the end with a special syntax.

1width = depth = height = 10
2
3print("The edge lengths of the cube are %d, %d and %d, respectively." % (width, depth, height))
4print("Still the same volume: %d" % (width * depth * height))
The edge lengths of the cube are 10, 10 and 10, respectively.
Still the same volume: 1000

Note

Remember to put # -- coding: utf-8 -- at the top of your script file if you use non-ASCII characters and get an encoding error.