#!/usr/bin/env python # coding: utf-8 # # 6. Booleans and Comparison Operators # # In this section, we'll explore the concept of booleans and how they are used in Python to represent true or false values. We'll also delve into comparison operators, which are used to evaluate conditions and make decisions within your programs. # # We'll learn about the following topics: # # - [6.1. Booleans](#Booleans) # - [6.2. Comparison Operators](#Comparison_Operators) # - [6.3. Chained Comparison Operators](#Chained_Comparison_Operators) #
#
#
Name | #Type in Python | #Description | #
---|---|---|
Booleans | #bool | #Logical value indicating True or False | #
Operator | Description | Example | #
---|---|---|
== | #If the values of two operands are equal, then the condition becomes true. | #(a == b) is not true. | #
!= | #If values of two operands are not equal, then condition becomes true. | #(a != b) is true | #
> | #If the value of left operand is greater than the value of right operand, then condition becomes true. | #(a > b) is not true. | #
< | #If the value of left operand is less than the value of right operand, then condition becomes true. | #(a < b) is true. | #
>= | #If the value of left operand is greater than or equal to the value of right operand, then condition becomes true. | #(a >= b) is not true. | #
<= | #If the value of left operand is less than or equal to the value of right operand, then condition becomes true. | #(a <= b) is true. | #
==
is a comparison operator, while =
is an assignment operator.
# - **Not Equal**
# In[4]:
5 != 6
# In[5]:
5 != 5
# These two operations (`==` `!=`) can be done on lists, tuples, dictionaries, and sets.
# In[6]:
{'key1':1, 'key2':2} != {'key2':2, 'key1':1}
# In[7]:
[1, 2] == [2, 1]
# - **Greater Than**
# In[8]:
6>4
# In[9]:
2>3
# - **Less Than**
# In[10]:
2 < 6
# In[11]:
5 < 2
# - **Greater Than or Equal to**
# In[12]:
3 >= 3
# In[13]:
1 >= 7
# - **Less than or Equal to**
# In[14]:
4 <= 4
# In[15]:
8 <= 4
#
#
# ## 6.3. Chained Comparison Operators:
# An interesting feature of Python is the ability to chain multiple comparisons to perform a more complex test.
# In[16]:
1 < 2 < 3
# The above statement checks if 1 was less than 2 and if 2 was less than 3. We could have written this using an and statement in Python:
# In[17]:
1<2 and 2<3
# In[18]:
1 < 3 > 2
# The above checks if 3 is larger than both of the other numbers, so you could use and to rewrite it as:
# In[19]:
1<3 and 3>2
# It's important to note that Python is checking both instances of the comparisons. We can also use **or** to write comparisons in Python. For example:
# In[20]:
1==2 or 2<3
# In[21]:
1==1 or 100==1