Python Booleans and Operators
Booleans are the values True and False, and operators are the symbols that work on values.
Boolean Values
A boolean (bool) has only two possible values: True or False. You get one whenever you compare things.
Example
print(10 > 3)
print(10 == 3)
print("ali" == "Ali")True False False
The last one is False because capital and small letters are different.
Truthy and Falsy Values
The bool() function tells you if a value counts as true or false. Empty and zero values are False. Almost everything else is True.
Example
print(bool(0))
print(bool(""))
print(bool([]))
print(bool(None))
print(bool(25))
print(bool("Hi"))False False False False True True
Arithmetic Operators
| Operator | Name | Example | Result |
|---|---|---|---|
+ | Addition | 7 + 2 | 9 |
- | Subtraction | 7 - 2 | 5 |
* | Multiplication | 7 * 2 | 14 |
/ | Division | 7 / 2 | 3.5 |
// | Floor division | 7 // 2 | 3 |
% | Remainder (modulus) | 7 % 2 | 1 |
** | Power | 7 ** 2 | 49 |
Assignment Operators
These change a variable using its own value:
Example
points = 10
points += 5 # same as points = points + 5
print(points)
points -= 3
print(points)
points *= 2
print(points)15 12 24
Comparison Operators
| Operator | Meaning |
|---|---|
== | Equal to |
!= | Not equal to |
> | Greater than |
< | Less than |
>= | Greater than or equal to |
<= | Less than or equal to |
Do not mix up = and ==. One = gives a value to a variable. Two == compares two values.
Logical Operators
and, or and not combine conditions:
Example
age = 20
has_cnic = True
print(age >= 18 and has_cnic)
print(age < 18 or has_cnic)
print(not has_cnic)True True False
andis True only if both sides are Trueoris True if at least one side is Truenotflips True to False and False to True
Membership and Identity Operators
in and not in check if a value is inside a collection. is checks if two names point to the very same object.
Example
fruits = ["mango", "banana", "apple"]
print("mango" in fruits)
print("grapes" not in fruits)
x = None
print(x is None)True True True
Use is mainly to check for None. For normal comparisons, use ==.
Operator Precedence
Python does some operators before others, like in school maths. ** comes first, then * / // %, then + -, then comparisons, then not, and, or. Use brackets to make your meaning clear:
Example
print(2 + 3 * 4)
print((2 + 3) * 4)14 20
Exercise
Exercise
What is the result of 15 % 4?
