Course contentsShow
← Python
Lesson 37 of 1,0601. Foundations and EnvironmentFree lesson

Comparing Values with Relational Operators

Use comparison operators to evaluate relationships between variables, enabling the program to make decisions based on quantitative data differences.

Comparing Values with Relational Operators

In this lesson, you will learn how to use relational operators to ask Python questions about the relationship between two values, allowing your code to make logic-based decisions.

Understanding Relational Operators

When you want your program to make a decision—like checking if a player has enough points to win or if a bank balance is too low—you need a way to compare quantities. Relational operators allow you to compare two values and return a Boolean result: either True or False.

Python provides six standard operators for this purpose:

  • == (Equal to)
  • != (Not equal to)
  • > (Greater than)
  • < (Less than)
  • >= (Greater than or equal to)
  • <= (Less than or equal to)

Seeing it in Action

Imagine you are building a system to verify if a user is old enough to access specific content. You can store the user's age in a variable and compare it against a requirement:

required_age = 18
user_age = 16

# This expression evaluates to False
is_adult = user_age >= required_age

if is_adult:
    print("Access granted.")
else:
    print("Access denied: You are too young.")

In the example above, the expression user_age >= required_age compares the integer 16 to 18. Because 16 is not greater than or equal to 18, Python evaluates the entire expression as False. This result is then used by your if statement to control the flow of the program.

Why This Matters

Relational operators are the foundation of decision-making in programming. Without them, your program would execute the same steps every single time. By comparing values, you enable your code to adapt its behavior based on the specific data it receives, whether that data comes from user input, calculations, or files.

Key Takeaway: Relational operators compare two values and yield a Boolean result (True or False), serving as the essential "logic gates" that allow your programs to make decisions.