Python Tutorial menu

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

python
print(10 > 3)
print(10 == 3)
print("ali" == "Ali")
Output
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

python
print(bool(0))
print(bool(""))
print(bool([]))
print(bool(None))
print(bool(25))
print(bool("Hi"))
Output
False
False
False
False
True
True

Arithmetic Operators

OperatorNameExampleResult
+Addition7 + 29
-Subtraction7 - 25
*Multiplication7 * 214
/Division7 / 23.5
//Floor division7 // 23
%Remainder (modulus)7 % 21
**Power7 ** 249

Assignment Operators

These change a variable using its own value:

Example

python
points = 10
points += 5    # same as points = points + 5
print(points)
points -= 3
print(points)
points *= 2
print(points)
Output
15
12
24

Comparison Operators

OperatorMeaning
==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

python
age = 20
has_cnic = True
print(age >= 18 and has_cnic)
print(age < 18 or has_cnic)
print(not has_cnic)
Output
True
True
False
  • and is True only if both sides are True
  • or is True if at least one side is True
  • not flips 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

python
fruits = ["mango", "banana", "apple"]
print("mango" in fruits)
print("grapes" not in fruits)

x = None
print(x is None)
Output
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

python
print(2 + 3 * 4)
print((2 + 3) * 4)
Output
14
20

Exercise

Exercise

What is the result of 15 % 4?

Learn Python with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp