Corsi registrati su
Corsi in diretta per la formazione di Front End Developer e Back End Developer
In this lesson we will introduce comparison operators and Boolean operators in Python. We must first of all know that comparison operators are widely used in programming languages and are very easy concepts to learn.
Comparison operators in Python
Comparison operators are used mostly in conditional statements (if else), which we will discuss later. We specify that the comparison operators can return only two values: True or False.
So let’s take an example, assuming that the variable a is equal to 5 and b is equal to 6.
== equal – Ex: a == b returns False
! = different – Ex: a! = b returns True
> greater – Ex: a> b returns False
< lesser – Ex: a <b returns True
Operator >= greater than or equal – Ex: a> = b returns False
<= less than or equal – Ex: a <= b returns True
Try running these examples in interactive mode.
Example of using comparison operators in Python
Now let’s do other examples of use. So let’s go back to interactive mode and type:
>>>name = ‘Alan’ # I assign the string Alan to name
>>>name == ‘Alan’ #I compare the variable name with the string Alan
>>>name == ‘Tom’ #I compare the variable name with the string Tom
As we can see, clearly having assigned the string to name Alan the following comparison gives the value True while the comparison with the string Tom gives me False.
Let’s see some examples of the use of comparison operators in Python:
name = 'Alan' name_2 = 'Tom' print(name == name_2) print(name != name_2) number = 5 number_2 = 10 print(number == number_2) print(number != number_2) print(number >= number_2) print(number <= number_2) print(number > number_2) print(number < number_2)
In this example we first took two strings as input, then we compared them to see if they are equal or not.
In the second part we took 2 numbers as input and compared them with the comparison operators, just studied.
In this lesson we have introduced comparison operators in Python, we will see later how to apply them together with conditional operators.
Some useful links
How to find the maximum of N numbers