Comparisons & Logical operators
Comparisons
Now, that we have covered all basic Python
types, we can start comparing them.
As the name suggests, comparisons are used to compare two values. The result
of a comparison is a boolean value.
Equality
We can compare any type with each other. In the above case, the comparison
checks if both strings are equal, using the ==
operator. The result is
False
, because the case of the strings do not match.
Let's check if two integers are equal:
Inequality
We can also check if two values are not equal with the !=
operator:
Numerical comparisons
... are done with:
Operator | Description |
---|---|
< |
less than |
> |
greater than |
<= |
less than or equal |
>= |
greater than or equal |
Logical Operators
You may want to check multiple conditions at the same time. For example,
sometimes you might need two conditions to evaluate to True
in
order to perform an action. Hence, logical operators are introduced.
There are three logical operators:
Operator | Meaning | Example | Result |
---|---|---|---|
and |
Returns True if both statements are True |
True and True |
True |
or |
Returns True if one of the statements is True |
True or False |
True |
not |
Reverses a result | not True |
False |
and
or
not
Evaluate password security requirements: Part 1
You are given two variables that describe properties of a password:
password_length
- represents how many characters are in the password (int
)has_special_characters
- represents whether the password contains special characters (True
/False
)
Variables to use:
Task:
Write code that checks if this password is secure based on these requirements:
- The password must be longer than 10 characters
- The password must contain special characters
Use comparisons and logical operators to create a single expression that evaluates whether BOTH requirements are met.
Evaluate password security requirements: Part 2
To increase security, a third variable is introduced alongside the previous password properties:
already_used
- represents whether this password has been used before
(True
/False
)
Variables to use:
Task:
Write code that checks if this password is secure based on these three requirements:
- The password must be longer than 10 characters
- The password must contain special characters
- The password must not have been used before
Build on your previous solution and evaluate whether all THREE requirements are met.
Recap
We have covered the basic comparison and logical operators in Python
.
-
Comparisons
==
for equality!=
for inequality<
,>
,<=
,>=
for numerical comparisons
-
Logical operators
and
or
not