Python is a great language for many tasks. It is commonly used for system administration tasks, as well as building websites, processing data, and text. It is also shaping up to be the language of choice for Machine Learning (ML), leveraging powerful modules for performing math and for visualizations.
As with the basis of most programming languages, you may use variables in Python to hold and manipulate values. This guide shows you the basics of creation and use of variables in Python.
To best benefit from this guide, you may want to follow along and run the code examples throughout this guide. The code examples are entered into Python's REPL interpreter. If your system does not already have a python interpreter, you can download one from here. Just pick the version matching your operating system and follow the installation instructions. This guide targets Python version 3.6 and the sample code was tested against that version.
Variables hold values. In Python, variables do not require forward declaration - all you need to do is provide a variable name and assign it some value.
The Python interpreter shows you a prompt that looks like this:
>>>. Each line you type into the interpreter is taken one at a time, parsed by the interpreter, and if the line is complete, executed as well.
If you enter
one = 1 in the Python interpreter and hit "Enter", the interpreter will just show you a new line prompt.
1>>> one = 1 2>>>
The new line prompt
>>> is empty. But Python actually did a few things:
1was assigned to the variable
This is not apparent from the blank line output. But the interpreter can show you the value of any variable if you just type the variable name and hit enter:
1>>> one 21 3>>>
The value 1 is shown because Python evaluates the line and reports the value returned. Previously, the line contained a statement. The variable
one was assigned a value. That operation evaluated a statement, so nothing was printed as a result. A more explicit way to print the value of a variable is to use the
1>>> print(one) 21 3>>>
Let's create another variable named
greeting and assign it the value
1>>> greeting = 'hi' 2>>> print(greeting) 3hi
Here we created a variable and assigned it a string value. Note the variable name
greeting. It was chosen to contain, well, a greeting of some sort. Python, of course, has no way to tell that the string value
'hi' is indeed a greeting. A variable is, well, variable! We can re-assign a variable later. The value stored in a variable is simply the last one assigned to it.
1>>> greeting = 'hi once' 2>>> greeting = 'hi again!' 3>>> print(greeting) 4hi again! 5>>>
The initial value
'hi once' is lost once the second assignment to the value
'hi again!' was evaluated. The current value of the variable remains
'hi again! for the duration of the session unless otherwise assigned a new value later.
Both variable names
greeting consist of characters only. Python allows you to name variables to your liking, as long as the names follow these rules:
_character. Either lowercase or uppercase letters are acceptable.
Following the rules above, all of these variable assignments are legal:
1>>> fish = 11 2>>> a = 12 3>>> _wow_ = 13 4>>> a1 = 14 5>>> something_longer_is_fine_2 = 15 6>>> RemoteAddress = '10.20.30.40'
All the above variable names are acceptable. But just because they are acceptable does not mean you should use them. The Python community has further developed naming conventions which should be followed. For example, even though a single-character identifier is perfectly legal, you are strongly discouraged from using the characters
l (lower case el) or
O (uppercase oh) or
I (uppercase eye). This is because in some fonts these are hard to distinguish from the digits 1 (one) and 0 (zero). For more on variable naming, see this reference.
The following variable names are not acceptable. If you attempt to use them, python will produce an error and no variable would be created.
An initial character which is not an underscore or a letter from A-Z or a-z will produce an error. The backtick (`) character for example:
1>>> `ticked = 1 2 File "<stdin>", line 1 3 `ticked = 1 4 ^ 5SyntaxError: invalid syntax 6>>>
An identifier starting with a digit is not legal.
1>>> 7days = 'week' 2 File "<stdin>", line 1 3 7days = 'week' 4 ^ 5SyntaxError: invalid syntax 6>>>
An identifier containing a space isn't legal:
1>>> day of week = 'Monday' 2 File "<stdin>", line 1 3 day of week = 'Monday' 4 ^ 5SyntaxError: invalid syntax 6>>>
Also, we can't use reserved words as variable names. In python, the word
and is a reserved word. The following assignment will therefore fail:
1>>> and = 'the winner is?' 2 File "<stdin>", line 1 3 and = 'the winner is?' 4 ^ 5SyntaxError: invalid syntax 6>>>
In all of the failed cases above, the Python interpreter raised an error and refused to carry out the assignment or creation of the variable. You may note that the caret
^ character points to different position in the erroneous identifier. This is due to the interpreter's attempt to match the identifier to an acceptable syntax. But either way, the outcome is the same: invalid variable names result in an error.
As a reference, Python's reserved words list includes:
Python does not require you to declare a variable. You do not need to tell Python ahead of time that you intend to reserve space for a variable. All you do is assign a variable a value. But this does not mean you can use a variable without having Python allocate it first. For example, the following line will fail in my session:
1>>> print(imaginary_thing) 2Traceback (most recent call last): 3 File "<stdin>", line 1, in <module> 4NameError: name 'imaginary_thing' is not defined 5>>>
This error appears because there is no identifier named
imaginary_thing as far as Python can tell. Python will joyfully accept a variable by that name, but it requires that any variable being used must already be assigned.
The act of assignment to a variable allocates the name and space for the variable to contain a value.
We saw that we can assign a variable a numeric value as well as a string (text) value. We also saw that we can re-assign a variable, providing it a new value which replaces any previous value it contained.
Python tracks the value of a variable by letting you access it via the variable name. Python also tracks the type of the value assigned to a variable. To tell what the value type is, you can use the built-in
type() function. In the following examples, we use the
type() function to display the value type:
1>>> x = 42 2>>> print(type(x)) 3<class 'int'> 4>>> x = 'hi' 5>>> print(type(x)) 6<class 'str'> 7>>> x = 3.14 8>>> print(type(x)) 9<class 'float'> 10>>> x = False 11>>> print(type(x)) 12<class 'bool'> 13>>>
In each of the examples above, Python infers the value type by parsing the right-hand part of the assignment and deciding the type accordingly. The existence of the decimal point in the value
3.14 clued Python to assign the type float whereas the bare number
42 produced an int.
Python also supports boolean data types. Booleans are assigned a value of
False (both of which are keywords by the way).
An integer data type is also created when you use hexadecimal or octal or binary literals. To type a value as octal, prefix the number with
0o. To type a value is hexadecimal, prefix it with
0x. For a binary literal, prefix with
1>>> x = 0xABBA 2>>> print(type(x)) 3<class 'int'> 4>>> x = 0o463 5>>> print(type(x)) 6<class 'int'> 7>>> x = 0b101010 8>>> print(type(x)) 9<class 'int'> 10>>>
If you want to ensure the value of a variable is of int type, you may use the built-in
int() class constructor:
1>>> x = int(3.14) 2>>> print(type(x)) 3<class 'int'> 4>>> x 53
The above statement assigned the variable type class int to
x. In order to store the number
3.14 to an integer value, the
int() function discarded the fraction part.
Similarly, you can use the
float() class constructor function to ensure that a bare number - expressed in decimal, hex, or octal forms - would yield a float data type:
1>>> x = float(43962) 2>>> print(type(x)) 3<class 'float'> 4>>> x = float(0xABBA) 5>>> print(type(x)) 6<class 'float'> 7>>> x = float(0o125672) 8>>> print(type(x)) 9<class 'str'> 10>>>
We saw that values do indeed have a type and that Python tracks variable value as well as type. Lastly though - what does this type mean? Python will allow you to perform operations that fit the type.
For example, you may wish to divide the value of a variable by 3:
1>>> x = 42 2>>> x/3 314.0
But the division operator does not work on a string. So you can't divide the string
'one two three' into 3:
1>>> x = 'one two three' 2>>> x/3 3Traceback (most recent call last): 4 File "<stdin>", line 1, in <module> 5TypeError: unsupported operand type(s) for /: 'str' and 'int' 6>>>
The error Python raises is descriptive of the fact that the operator
/ (used for numeric division) is not defined for the types string and integer. Python is aware of the type assigned to the variable
x which is how it made that determination. While you may be able to define your own operators on any types you wish, the point remains that Python does need the type system in order to map values, operators, and variables to the correct internal function. Python is a dynamically typed, but typed nonetheless.
Many programming languages support the notion of
null. Null is treated as a special value denoting "not-a-value", something which would let us denote an "empty" or undefined value. Python's version of that is the keyword
None, which is backed by the class
Note that assigning a variable to
None does not get rid of the variable. Space is still allocated for the variable - only the value is set to
None. If you want to remove the variable altogether you may use the
1>>> is_there = None 2>>> print(is_there) 3None 4>>> del is_there 5>>> print(is_there) 6Traceback (most recent call last): 7 File "<stdin>", line 1, in <module> 8NameError: name 'is_there' is not defined 9>>>
In the example above, after deleting the variable, any attempt to use that variable produces an error stating it is not (or no longer) defined.
type() function lets us glean which type a variable contains. When comparing numbers, we may need to check that they are identical - that both their value and type match. The
is operator provides for such identity checking. Numeric values may compare as equal to each other using the equality test
== yet not match on their type. Consider this example:
1>>> x = 1 2>>> y = 1.0 3>>> x == y 4True 5>>> x is y 6False 7>>>
In the above example,
x is assigned the integer value
y is assigned the float value
1.0. When tested using the equality match
==, the result is
True. Yet when tested using the object identity operator
is, the result is
False since float and int are different types.
Python does let you define your own operators on your objects, so you could add support for both the equality and the identity operators on your classes. The default behavior of most non-numeric classes though is that two instances of an object would not evaluate as equal or identical to each other.
Strings are a bit different. Strings in Python are immutable reference types. To complicate thing more, two strings containing the same exact sequence of characters and compared for object identity may produce either
False.This is due to internal implementation details and may vary across Python interpreters.
To summarize: Python lets you create variables simply by assigning a value to the variable, without the need to declare the variable upfront. The value assigned to a variable determines the variable type. Different types may support some operations which others don't. If you want to control the type of variable assigned, you may use the specific class constructor to assign the value, such as
float(). Bare numbers expressed without a decimal point - or as hex or octal literals - will produce an integer.
You can get the class type of a variable by using the
type() function, or test whether a type matches some specific type using the
Python variables provide a simple and dynamic way to create variables, yet maintains a powerful type system to ensure safe operations on your data.