Python online tutorial
Part 5: Variables
Variables are one of the core parts of almost all programming languages. If you’re not familiar with the term, here is a short explanation:
You can think of variables as boxes. You can do anything you want with a box – fill it with golf balls, put a plant pot in it, store shoes… More importantly, you can also slap a label on that box with a meaningful name to make sure you remember what’s in it. Variables are not that different. They are sections in the memory of your computer assigned to store whatever you please in them. When you create one, you must give it a name. A simple example:
x = 0
x
is the label you have given your variable – the variable’s name.
0
is the what’s in the box – the variable’s value.
The useful thing about variables is that, once they’re created, you can use them anywhere your program has access to them by using their name to reference them. The area of a program in which you can use a variable is called scope. If you try and use a variable outside its scope you will get an error looking like this:
NameError: name '' is not defined
Variable scope
A variable defined in the main body of a file (outside a function) is called a global variable. It is accessible from any part of your program. This functionality is very useful, as it lets you define constants such as a maximum number for something, for example. After defining it, you can use it with its name, so you don’t have to type its value every time.
A variable defined inside a function is called a local variable. It is only usable as long as the function is executing, and only within that function. You will learn how to create and call functions in a later section of this tutorial.
Creating a variable
Creating a variable in Python is easy. Take the value you want to use (say 5, but it doesn’t necessarily have to be numerical) and use the assignment operator (=
) to make a variable with it:
myVariable = 5
Yep, that’s it. myVariable
is now 5 until you or a function says otherwise. If you want to define many variables at once, you can use the following syntax:
a, b, c = 1, 2, 3
(a
, b
and c
are set to 1, 2 and 3 respectively).
a = b = c = 4
(a
, b
and c
are all set to 4).