Basic Operators
Use Python operators to calculate values and compare results.
Video coming to YouTube
Work through the full lesson and run its code while the video is being prepared for publication.
Understand the concept
Arithmetic operators combine numbers. The slash performs division, double slash gives floor division, percent gives the remainder, and double asterisks raise a value to a power.
Comparison operators such as ==, !=, >, and <= produce booleans. Parentheses make the intended order of evaluation clear when an expression has several operators.
- Arithmetic operators
- Comparison returns bool
- Parentheses control grouping
See it step by step
Read the code, predict the output, then compare it with the result.
01. Divide into full boxes
items = 18
box_size = 4
print(items // box_size)
print(items % box_size)4
2// counts full boxes and % gives the two items left over.
02. Group and compare
print((2 + 3) * 4)
print(7 > 5)20
TrueParentheses make addition happen first. The comparison produces a Boolean value.
Try it in Python
Edit the example and run it. Python starts in your browser the first time you click Run.
Python console
Ready to runNeed input()? Add one value per line
Your output appears here.
Need a hint?
Use 23 // 5 for the full boxes and 23 % 5 for leftovers. Print each result, with or without a descriptive label.
Complete the task and select Check task to verify your code.
Quick quiz
Three questions. You can change your answers and try again.
Typical mistakes
Everyone meets these errors. See what causes them and how to fix them.
Using ^ for powers
print(2 ^ 3)print(2 ** 3)What happens: It prints 1 because ^ is bitwise XOR.
Python's exponentiation operator is **.
Dividing by zero
print(10 / 0)print(10 / 2)What happens: ZeroDivisionError.
The divisor must be nonzero.