price = 16.80
total = price * 1.05
print(total)17.64
str, int, float and boolA variable is a temporary holding place for a value. Think of it as a box that can store a single item.
The value inside a variable can be of different type, for example:
a number, such as the user’s hourly pay, or the number of students in a course;
a word or sentence (aka. a “string”), such as the user’s name;
many other things that we’ll visit later…
variable_name = value
Here are a few examples:
Alternatively, you may also store the result of a Python expression:
variable_name = python_expression
=For instance, the following line will create a variable named my_sum and store the result 335 in memory:
Let’s break down the way variables are created and in Python, the following line is evaluated from right to left:

= sign is evaluated first.Given that assignments are evaluated from right to left in Python, the expression below is correct although it is mathematically not correct:
The value of x is increased by 1.
Variables are mutable. This means their values can be changed or updated over time.
For example, the following lines create a variable called temperature, initially setting its value to 23.0. The second line, is updating its value to 26.0. Thus erasing the previous value:
In python, the value of a variable can be changed to a different type, though this practice is highly discouraged.
For example, the following line assigns a literal of type string to a variable which initially was numeric:
Later, we will learn why those types are not the same.
To use a variable after it was created, simply re-type its name where you need it (e.g.: print(temperature), or (temperature +3)) and python will use its value in the expression.
x doesn’t existVariables can help make the code easier to read and follow, but also re-use logic.
Magic numbers are unexplained values used in the code which make the code hard to read and understand:
1.05 is not explained and is considered a magic number.Now consider this improved version using more variables:
It’s now a little bit clearer that this program is calculating the cost of something afterapplying a \(5%\) taxe rate.
The first program was hardcoding the tax rate in the magic number 1.05
Hardcoding means to embed a value litterally as it is in the code. Think of it as permanantly tattooing your best friend’s phone number, and regretting it when they change numbers.
Say, you’re creating a script implementing the Pythagorean theorem when \(a\) and \(b\) are known. \[ a^2 + b^2 = c^2 \]
Consider the two program below implementing the same equation. What’s the maing difference?
One possible answer is: it’s much easier to read, and update the second program because the values of \(a\) and \(b\) are well isolated in seperate variables.
🎯 Test Myself: Improve the program below by creating variables for each item price and the total:
The cost of item 1 is: $ 10
The cost of item 2 is: $ 22
The total cost is $ 32
You don’t have to create variables for every piece of data in the program. There’s a fine line between making a code re-usable or making too long with too many variables. For example, if you’re implementing the Pythagrean equation, the power 2 can be written because it’s not expected to change.
The variable name cannot start with a number, only with letters or _
It must contain only letters, numbers and underscores (A-z, 0-9, and _)
It cannot contain a space character, nor punctuation character, nor any special character (@, #, $, %, ?, etc..)
It must not be any of the Python keywords, as these are reserved by Python for predefined purposes.
Python is case sensitive! This means that uppercase APPLE and lowercase apple are not the same variable names, therefore will be considered by python as two different variables.
You may use alphabet from other languages too for example: sûr_la_mer, переменная, Adiós_Señora are valid variable names.
Now that you’ve seen that programming expressions don’t play by the math rules, let’s break away even more from your math habits.
While, you can use simple names just like x, y, it is preferable to give variables a name that is more descriptive of what they represent.
👉 Variable name should be meaningful!
Anyone reading your code should be able to guess what the variable represents and how it will be used just based on the variable name.
For example, using the variable t to represent a temperature reading could lead to confusion because t could also mean time, or any other quantity. It is therefore more meaningful to use temperature.
You may also use abbreviations, so long as they are commonly known (e.g: max for the maximum, min for the minimum, avg for average)
💣 Code submitted with poor variable names will have marks deducted.
Programmers came up with conventions to make code more easy to read and share. The PEP 8 – Style Guide for Python Code contains this list of conventions. Here are a few useful conventions we will reinforce in this course. You may select any of these conventions so long as you are consistent throughout your solutions.
| Convention | Formatting | Examples |
|---|---|---|
| Snake case | two_words | avg_temperature, estimation_pi, area_under_curve |
| Camel Case | twoWords | avgTemperature, estimationPi, areaUnderCurve |
{height=300}
Source: Convert Naming Convention, https://github.com/NewGuy012/convert-naming-convention
🎯 Test Myself: The following variable names contain mistakes. Identify and fix them, then ensure that the new name follow the camel case naming convention. Repeat the exercise, this time using the snake case convention. Use a Python Terminal to validate your answers.
Let’s have a look at this lengthy equation: ((16- (16+ 18+ 19)/3)**2 + (18- (16+ 18+ 19)/3)**2 + (19- (16+ 18+ 19)/3)**2)/3
This equation computes the variance of the grades of three students. The formula to calculate the variance of three numbers is as follows, where x_m represents the mean of the grades.

Let’s break it down in the following steps and implement them:
Python implementation of the variance
Firstly, we need to define three variables representing the student grades and set their values:
Using variables allows us to reuse the calculation with different numbers if required.
To calculate the mean we can add up the grades and divide by 3 and store the result in a new variable. This new variable can then be reused as many times as required.
To compute the squared difference of each grade, we can begin by calculating the difference from the mean and store these differences in new variables (diff = grade - mean). Then, using the power operator **, we can store the squared differences in another set of variables (e.g., square_diff = diff ** 2). While there are no limits in the amount of variable used, intermediate results like diff may not be necessary to retain. Hence, we can perform the difference and the power operations into a single calculation.
The last step is to calculate the variance by averaging the squared differences:
Finally, we simply need to print the variance.
🎯 Test Myself: Store your age in a variable as a number. Store one of your parent’s age in a variable as a number. Using those two variables, calculate the age difference and print it out in a message.
Constants like in math are suppose to be values that never change. In python, they are treated the same way as variables but their values cannot be modified in the program. We say that constants are immutable. These values are universally acknowledged to be true and they should not changeover time.
Typically, Python constants are declared and initialized on different modules or files and need to be imported within the source code. We will learn more about modules at a later moment.
Within a created constants.py file:
To use the constants into your main.py file:
The constants can still be modified since there is no built-in way to prevent this in Python. However, programmers follow the convention of using uppercase letters to name constants and treat them as immutable. There are also external modules available that can help “objects” that are constants and protected from modification.