Conditions

Control Flow

Conditions

In this tutorial, we'll write expressions that evaluate to True or False.

A condition is an expression that Python can treat as True or False.

Conditions are how programs make decisions.

age = 18
print(age >= 18)

Output:

True

Comparison Operators

Python has several comparison operators:

score = 75

print(score > 50)   # greater than
print(score >= 75)  # greater than or equal to
print(score < 100)  # less than
print(score == 75)  # equal to
print(score != 0)   # not equal to

Each comparison produces a boolean.

Comparing Strings

Strings can be compared too:

password = "python"

print(password == "python")
print(password != "secret")

String comparisons must match exactly. Capital letters matter:

print("Python" == "python")

Output:

False

Combining Conditions

Use and when both conditions must be true:

age = 20
has_ticket = True

print(age >= 18 and has_ticket)

Use or when at least one condition must be true:

is_member = False
has_coupon = True

print(is_member or has_coupon)

Use not to flip a condition:

is_banned = False
print(not is_banned)

Store Conditions in Variables

If a condition is important, you can store it with a clear name:

age = 20
has_ticket = True

can_enter = age >= 18 and has_ticket
print(can_enter)

This can make longer programs easier to read because the variable name explains the decision.

Practice

Create variables for temperature and is_raining. Print whether it is warm and dry enough to go outside.