Literals, variables, and constants in Python

Dr. Huidae Cho
Institute for Environmental and Spatial Analysis...University of North Georgia

1   Literals

A literal is a value that the user types directly into code. It is often said to be hard-coded to put literals in the code because they cannot be changed while the programming is running. They can only be changed by the programmer, not by the user nor by the program itself. Hard coding means that you cannot change these values without directly modifying the program code.

A literal is a value that the user types directly into code.

Putting literals in the code is often referred to as hard coding.

Hard coding means that you cannot change these values without directly modifying the program code.

'string' # string
"string" # string
123      # integer
3.14     # floating-point number
1+2j     # complex number
True     # boolean
False    # boolean

2   Variables

A variable is a container in the memory that holds a literal.

a = 1     # assign an integer literal to a variable
b = 2     # assign an integer literal to a variable
c = a + b # c holds the result of a + b, not the expression itself
c         # c is 3
a = 2     # now, a is 2
c         # c is still 3 because it holds the result of a + b
          # at the time of assignment

3   Constants

A constant is defined once and never changes.

Python 3 does not have a syntax for constants, but they can be imitated using a function or class.

The naming convention for constants in Python 3 is all caps.

CONST = 1 # supposed to be a constant
CONST = 2 # but you can still change it

However, just don’t change it because it’s meant to be a constant!

4   Summary

Literals are actual values that we want to use while variables are containers of literals. Variables can vary (hence, the name variable) while literals cannot (123 is 123, 123 cannot mean something else). Constants are non-varying containers of literals and Python does not support them, but Python programmers use a naming convention such as all-capital to name constants (but they are still variables).

Different programming languages use different capitalization conventions. Python uses snake_case for variables, ALL_CAPS for constants, UpperCamelCase for classes. These casing styles are not enforced, but it’s always a good idea to follow common naming conventions. Please refer to this section about naming convention in programming.

5   Exercise: Literals and variables

In this following Python code, how many literals and variables can you find? What is the value of c?

a = 1
b = 2
c = a + b
print(c)