Comparison Operators
You’ll learn the six comparison operators—they compare two values and give you True or False. You use them in conditions (like inside an if or a while loop) so your program can decide whether to run a block of code.
The six comparison operators
Each operator goes between two values. The result is always True or False (a boolean).
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | equal to | 5 == 5 | True |
!= | not equal to | 5 != 3 | True |
< | less than | 3 < 5 | True |
> | greater than | 5 > 3 | True |
<= | less than or equal to | 3 <= 3 | True |
>= | greater than or equal to | 5 >= 5 | True |
To check if two values are equal, use two equals signs: ==. A single = assigns a value to a variable; it doesn’t compare.
Using comparison operators in conditions
You’ll usually put a comparison inside an if (or while). The condition is either true or false, and Python runs the block only when it’s true.
age = 15
if age >= 13:
print("You can see this movie.")
else:
print("This movie is for older audiences.")Here, age >= 13 is the condition. Python evaluates it to True or False, then chooses which block to run. You can compare numbers, strings (e.g. name == "Alex"), and other types—just use values that make sense to compare.
Quick examples
score = 85
print(score >= 70) # True
print(score == 100) # False
grade_letter = "B"
print(grade_letter == "B") # True
print(grade_letter != "A") # TrueComparison operators always give you a boolean. Once you’re comfortable with these, you can combine conditions using logical operators (and, or, not) on the next page.