Conditional Tests

Before dealing with if statements, we need to understand conditional tests.

Conditional tests are expressions that can be evaluated as True or False. Both True and False are special values that belong to the bool type.

Comparing Strings

We can test whether two strings are equal by using the equality operator ==. Note that the equality operator is different from the assignment operator =.

Let's start with a simple example:

File: strings.py:

car = 'Bmw'
print(car == 'Bmw')

which produces:

True

Here our conditional test evaluates to True because the two strings are equal. If we change the value on the right-side of the equality operator to something else, the test will evaluate to False:

print(car == 'Audi')
# False

Equality operator is case-sensitive. For example, the following test also evaluates to False:

print(car == 'bmw')
# False

This is because variable car contains the string Bmw with a capital B, while the string literal on the right-side of the equality operator contains the string bmw with a lowercase b.

If our intention was to compare the two strings without considering the case, we can use the lower() method to convert variable car to lowercase before comparison:

print(car.lower() == 'bmw')
# True

Checking for Inequality

We can check whether two strings are not equal by using the inequality operator !=:

print(car != 'Bmw')
print(car != 'Audi')
# False
# True

Numerical Comparisons

As with strings, we can compare numbers using the equality and inequality operators:

age = 33
print(age == 33)
print(age != 18)

which prints:

True
True

Additionally, we can use less or greater than operators to check whether a number is less than or greater than another number:

print(age < 40) # less than
# True

print(age > 40) # greater than
# False

Two more operators to compare numbers are <= and >= which check whether a number is less than or equal to, or greater than or equal to another number:

print(age <= 33) # less than or equal to
# True

print(age >= 33) # greater than or equal to
# True

Boolean Variable

One special case of conditional tests is a boolean variable. A boolean variable has type bool and can be either True or False. For example:

breakfast_ready: bool = True
game_over: bool = False