Using Comparison Operators in Conditional Statements
One of the most important operators when writing conditional statements is the comparison operator.
Using comparison operators within conditional statements makes it easy to determine whether a condition is true or false.
Reviewing Comparison Operators
First, let's review some common comparison operators used in Python:
-
==
: Checks if two values are equal.a == b
is true ifa
andb
are equal. -
!=
: Checks if two values are not equal.a != b
is true ifa
andb
are not equal. -
>
: Checks if the left value is greater than the right value.a > b
is true ifa
is greater thanb
. -
<
: Checks if the left value is less than the right value.a < b
is true ifa
is less thanb
. -
>=
: Checks if the left value is greater than or equal to the right value.a >= b
is true ifa
is greater than or equal tob
. -
<=
: Checks if the left value is less than or equal to the right value.a <= b
is true ifa
is less than or equal tob
.
Using Comparison Operators in Conditional Statements
Let's examine how we can use comparison operators with conditional statements.
Comparing Numerical Values
Let's write a program to check if a person is an adult by determining if they are 18 or older.
age = 20
if age >= 18:
print("You are an adult")
else:
print("You are not an adult")
Here, the condition age >= 18
is true if age
is greater than or equal to 18.
Since the value of age
is 20, which is greater than 18, the message "You are an adult" will be printed.
Checking if Two Numbers are Equal
You can use the ==
comparison operator to check if two numbers are equal.
The following is an example of comparing whether two numbers are equal.
a = 10
b = 10
if a == b:
print("The two numbers are equal")
else:
print("The two numbers are not equal")
In the code above, since the values of a
and b
are both 10, the message "The two numbers are equal" will be printed.
Comparing Strings
The ==
comparison operator can be used not only with numbers but also with strings.
To compare whether strings are equal, you can write the following:
password = input("Enter your password: ")
if password == "python123":
print("Password matches")
else:
print("Password does not match")
In this code, if the value of the user-input password
matches "python123", the message "Password matches" will be printed.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.