Expressions and Variables
Learn about arithmetic operators, order of operations (PEMDAS), variable assignment & reassignment, inter-variable calculations, and clean naming conventions.
3.1 Expressions & Operators
An expression in Python is a combination of numbers and mathematical symbols (operators) that Python evaluates to produce a single final value.
Division deserves a special note: in Python 3, / always returns a float, even when the numbers divide evenly (e.g. 10 / 5 gives 5.0, not 5). Use // when you want a whole-number result rounded down.
Enter numbers for Operand A and Operand B, choose an operator, and watch Python compute the result in real time.
25 + 63.2 Order of Operations
Python follows standard mathematical operator precedence conventions (PEMDAS): multiplication and division happen before addition and subtraction, and anything inside parentheses is evaluated first.
3.3 Variables
A variable stores a value so you can use it again later. Use the assignment operator (=) to give a variable a value, and just type its name to use that value elsewhere in your code.
my_variable = 1
print(my_variable)
You can assign a new value to an existing variable at any time. The old value simply isn't important anymore — Python only remembers what the variable holds right now.
3.4 Building Expressions with Variables
Variables can store the result of an expression, and you can use one variable to compute another. You can even reassign a variable using its own current value.
x = 2 + 3 + 3 # x is 8
y = x / 3 # y is 2.666...
x = x / 3 # x is now 2.666... too
You can also check a variable's type just like any other value, with type(x).
3.5 Naming Variables Well
It's good practice to use meaningful variable names, so you don't have to keep track of what a variable is doing from memory. It's common to use an underscore to join words (total_min) or camelCase (totalMin).
Say you have a music dataset with a song's length in minutes, and you want the length in hours instead:
total_min = 876
total_hr = total_min / 60
print(total_hr)
Change total_min input below and observe total_hr recalculate instantly.
total_hr = total_min / 60Key Takeaways
- An expression combines operands with an operator (
+ - * / //). /always returns a float in Python 3;//floors down to a whole number.- Python evaluates parentheses first, then multiplication/division, then addition/subtraction.
- A variable stores a value with
=; reassigning it overwrites the old value completely. - Variables can depend on each other — change one and rerun, and anything calculated from it updates automatically.