Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Python Variables and Assignment

Sep 26, 2018 • 14 Minute Read

Introduction

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

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.

      >>> one = 1
>>>
    

The new line prompt >>> is empty. But Python actually did a few things:

  • A variable named one was created.
  • The value 1 was assigned to the variable one.

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:

      >>> one
1
>>>
    

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 print() function.

      >>> print(one)
1
>>>
    

Let's create another variable named greeting and assign it the value 'hi!':

      >>> greeting = 'hi'
>>> print(greeting)
hi
    

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.

      >>> greeting = 'hi once'
>>> greeting = 'hi again!'
>>> print(greeting)
hi again!
>>>
    

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 x and greeting consist of characters only. Python allows you to name variables to your liking, as long as the names follow these rules:

  • Variable names may contain letters, digits (0-9) or the underscore character _.
  • Variable names must begin with a letter from A-Z or the underscore _ character. Either lowercase or uppercase letters are acceptable.
  • Variable names may not be a reserved word in Python.

Following the rules above, all of these variable assignments are legal:

      >>> fish = 11
>>> a = 12
>>> _wow_ = 13
>>> a1 = 14
>>> something_longer_is_fine_2 = 15
>>> 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:

      >>> `ticked = 1
  File "<stdin>", line 1
    `ticked = 1
    ^
SyntaxError: invalid syntax
>>>
    

An identifier starting with a digit is not legal.

      >>> 7days = 'week'
  File "<stdin>", line 1
    7days = 'week'
        ^
SyntaxError: invalid syntax
>>>
    

An identifier containing a space isn't legal:

      >>> day of week = 'Monday'
  File "<stdin>", line 1
    day of week = 'Monday'
         ^
SyntaxError: invalid syntax
>>>
    

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:

      >>> and = 'the winner is?'
  File "<stdin>", line 1
    and = 'the winner is?'
      ^
SyntaxError: invalid syntax
>>>
    

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:

andasassertbreak
classcontinuedefdel
elifelseexceptFalse
finallyforfromglobal
ifimportinis
lambdaNonenonlocalnot
orpassraisereturn
Truetrywhilewith
yield

Variables and Type

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:

      >>> print(imaginary_thing)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'imaginary_thing' is not defined
>>>
    

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:

      >>> x = 42
>>> print(type(x))
<class 'int'>
>>> x = 'hi'
>>> print(type(x))
<class 'str'>
>>> x = 3.14
>>> print(type(x))
<class 'float'>
>>> x = False
>>> print(type(x))
<class 'bool'>
>>>
    

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 True or 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 0b.

      >>> x = 0xABBA
>>> print(type(x))
<class 'int'>
>>> x = 0o463
>>> print(type(x))
<class 'int'>
>>> x = 0b101010
>>> print(type(x))
<class 'int'>
>>>
    

If you want to ensure the value of a variable is of int type, you may use the built-in int() class constructor:

      >>> x = int(3.14)
>>> print(type(x))
<class 'int'>
>>> x
3
    

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:

      >>> x = float(43962)
>>> print(type(x))
<class 'float'>
>>> x = float(0xABBA)
>>> print(type(x))
<class 'float'>
>>> x = float(0o125672)
>>> print(type(x))
<class 'str'>
>>>
    

Mixing Types

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:

      >>> x = 42
>>> x/3
14.0
    

But the division operator does not work on a string. So you can't divide the string 'one two three' into 3:

      >>> x = 'one two three'
>>> x/3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'str' and 'int'
>>>
    

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.

The None Type

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 NoneType. 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 del statement:

      >>> is_there = None
>>> print(is_there)
None
>>> del is_there
>>> print(is_there)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'is_there' is not defined
>>>
    

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.

Checking for Type Equality

While the 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:

      >>> x = 1
>>> y = 1.0
>>> x == y
True
>>> x is y
False
>>>
    

In the above example, x is assigned the integer value 1 and 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 True or False.This is due to internal implementation details and may vary across Python interpreters.

Summary

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 int() or 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 is operator.

Python variables provide a simple and dynamic way to create variables, yet maintains a powerful type system to ensure safe operations on your data.

Learn More

Explore these Python courses from Pluralsight to continue learning: