When we want to check if a user is registered on a website, we ask for their username and password. If the username exists in the database and the entered password matches the one in the database, we authorize the user. Otherwise, we continue to ask the user for their username and password. In the examples below, we will compare values of the same type with each other using the Python programming language.
Here’s how to compare two strings in Python:
print(10 == 5) # False
print('abc' == 'abc') # True
Example with password verification:
correct_password = 'qwerty'
asked_password = input('Enter password: ')
if (correct_password == asked_password):
print('You are authorized')
else:
print('Incorrect password')
Enter password: 123
Incorrect password
Enter password: qwerty
You are authorized
Logical comparisons or their results are used in if-else
constructions and while
loops.
A logical expression, in the simplest sense, is a mathematical comparison. In Python, the question "What is greater: 3 or 5?" would be written as 3 > 5
and would sound like: “Three is greater than five. True? - No.”
print(3 > 5) # False
Or another option: 4 != 0
(4 is not equal to 0. True?)
print(4 != 0) # True
Here’s how comparison operators are expressed in Python:
a == b
- A equals B
a > b
- A is greater than B
a >= b
- A is greater than or equal to B
a < b
- A is less than B
a <= b
- A is less than or equal to B
a != b
- A is not equal to B
a = 5
b = 10
print(a == b) # False
print(a > b) # False
print(a >= b) # False
print(a < b) # True
print(a <= b) # True
print(a != b) # True
The result of such comparisons can be stored in a variable, just like any other value:
a = 5
b = 10
expr = a > b
print(expr) # False
You can compare multiple values in sequence:
a = 4
expr = 0 < a < 10
print(expr) # True
a = 15
expr = 0 < a < 10
print(expr) # False
In the first case, we obtained True, while in the second case, Python returned False.
In addition to numbers, Python allows to compare strings, lists, and other data types. For example, here’s how to compare two strings in Python:
s1 = 'python'
s2 = 'python'
s3 = 'Python' # Changing one letter to uppercase
print(s1 == s2) # True
print(s1 == s3) # False
In the second case, the result is false because the comparison is case-sensitive.
Strings can also be compared in terms of greater than or less than:
print('abc' > 'abc') # False
print('abc' > 'aaa') # True
print('abc' > 'x') # False
In the first case, the strings are equal. In the second case, a character-by-character comparison occurs. The first two characters are equal, so the next characters are compared. 'b' > 'a' is true because 'b' comes after 'a' in the alphabet. Thus, the entire expression is true. To make it easier to understand, you can think of the letters as their positions in the alphabet: 123 > 111.
The character-by-character comparison does not depend on the length of the strings, so in the third case, the expression is false: 'a' > 'x'.
print('a' > 'x') # False
This type of comparison is called lexicographic comparison.
Comparing lists is similar to comparing strings. For example, when using the not equal condition in Python, each element of the list is compared in sequence with the other:
print([1, 2, 3] > [1, 2, 3]) # False
print([1, 2, 3] > [1, 1, 1]) # True
print([1, 2, 3] > [25]) # False
Values of different types can also be compared with each other:
expr1 = '1' == 1
expr2 = '' == 0
print(expr1) # False
print(expr2) # False
The result is false because the data types are not the same (a string and an integer). Comparing greater than or less than between different types will raise an error:
print('a' > 1) # TypeError: '>' not supported between instances of 'str' and 'int'
print((1, 1, 1) < [1, 2, 3]) # TypeError: '<' not supported between instances of 'tuple' and 'list'
Values can be converted to False or True directly from the values themselves, without a comparison operation. For example, the string 'a' will evaluate to True, while 0 will evaluate to False. To do this, you can call the bool()
function and pass it the value you want to convert:
var1 = bool('a')
var2 = bool(0)
print(var1) # True
print(var2) # False
An empty string or list will evaluate to False:
var1 = bool('')
var2 = bool([])
print(var1) # False
print(var2) # False
The logic is simple: if the size of a list or string is zero, then the bool
variable will be False. Similarly, 0 is also considered False. All other values, other than 0 or with a length greater than 0, will be True.
Typically, boolean operations in Python are used when checking for the presence of information in a variable, for example, to determine whether the user has filled in the required fields in a registration form or left them empty.
Here’s a simplified version of such a check:
user_name = input('Enter your name: ')
if user_name:
print(f'Welcome, {user_name}!')
else:
print('This field is required')
Enter your name:
This field is required
Enter your name: Mary
Welcome, Mary!
If we want to check multiple logical expressions or values for truth at the same time, we need to use logical operators in Python 3. For example, to check whether a user has entered their name and if their age is greater than 12:
name = 'Mary'
age = 10
expr = name and age > 12
print(expr) # False
In this case, we used the logical operator and
. It returns a true value only when both sides of it are true values.
There are also or
and not
operators:
or
- Returns a true value when at least one side has a true value.
not
- Changes the value to the opposite.
All of these operators work with the boolean equivalents of values, meaning they first convert them to the bool type before performing calculations.
print(True and False) # False
print(True or False) # True
print(not True) # False
print(not False) # True
Logical operations can be combined in a single expression:
expr = not True and False
print(expr) # False
Calculations happen in order. To change the order, parentheses can be used, just like in mathematics:
expr = not (True and False)
print(expr) # True
The value changed to true because the expression inside the parentheses is calculated first (resulting in False), and then it is inverted. When using the and and or operators in Python, they do not necessarily return only True or False; they return the actual value where the calculations stopped.
Let’s look at an example:
name1 = 'Mary'
age = 0
name2 = 'Anna'
print(name1 and age and name2) # 0
print(name1 or age or name2) # Mary
In the first case, the output is 0 because the calculations stopped at the variable age. Since all operators are and, if any value is false, the entire expression is false, meaning there's no point in calculating further.
In the second case, the situation is reversed. All operators are or, so the calculations stop at the first true value, which is the value of the variable name1.
Other logical operations are used less frequently and in specific situations. For example, there are bitwise logical operations that are applied in data encryption. One of these is XOR (exclusive OR), which is represented by the symbol ^
in Python.
Here’s an example of encrypting a number. Any binary data can replace the numbers.
phrase = 2022
key = 101
# Encrypting using the key
encrypt = phrase ^ key
print(encrypt)
# Decrypting the message using the key
decrypt = encrypt ^ key
print(decrypt)
Output:
1923
2022
Operation |
Description |
a & b |
Bitwise AND for a and b |
a | b |
Bitwise OR for a and b |
a ^ b |
Bitwise XOR for a and b |
~a |
Bitwise NOT for a |
a << b |
Bitwise left shift for a by b |
a >> b |
Bitwise right shift for a by b |
However, not all logical operations are present in Python. For example, there is no logical implication operation.
We have explored logical expressions and operators in Python 3. For more information on working with Python, check out the tutorials on Hostman.
Check out our app platform to find Python applications, such as Celery, Django, FastAPI and Flask.