Lesson 11 - Logical Operators

The following topics are discussed in this notebook:

  • Logical Operators

And Operator

In [1]:
b1 = True and True
b2 = True and False
b3 = False and False
b4 = False and False

print(b1)
print(b2)
print(b3)
print(b4)
True
False
False
False

Or Operator

In [2]:
b5 = True or True
b6 = True or False
b7 = False or False
b8 = False or False

print(b5)
print(b6)
print(b7)
print(b8)
True
True
False
False

Not Operator

In [3]:
print(not True)
print(not False)
False
True

Example

In [4]:
import random
In [5]:
random.seed(1)
rlist = random.sample(range(1,21), 10)
print(rlist)
[5, 19, 3, 9, 4, 8, 13, 15, 14, 11]
In [6]:
for i in range(0, len(rlist)):
    if ( (rlist[i] > 5) and (rlist[i] < 15) ):
        print(rlist[i], "is between.")

print()
        
for i in range(0, len(rlist)):
    if ( (rlist[i] <= 5) or (rlist[i] >= 15) ):
        print(rlist[i], "is not between.")

print()

for i in range(0, len(rlist)):
    if ( not((rlist[i] > 5) and (rlist[i] < 15)) ):
        print(rlist[i], "is not between.")
9 is between.
8 is between.
13 is between.
14 is between.
11 is between.

5 is not between.
19 is not between.
3 is not between.
4 is not between.
15 is not between.

5 is not between.
19 is not between.
3 is not between.
4 is not between.
15 is not between.

The & and | Symbols

In [7]:
print(True & True)
print(True & False)
print(False & True)
print(False & False)
True
False
False
False
In [8]:
print(True | True)
print(True | False)
print(False | True)
print(False | False)
True
True
True
False
In [9]:
n = 5
bool1 = (n > 9 or n < 7)
bool2 = (n > 9 | n < 7)

print(bool1)
print(bool2)
True
False
In [10]:
print(9 | 5)
13

Example: The Titanic Dataset

In this example, we will explore a dataset containing information about the 887 passengers on the first (and last) voyage of the RMS Titanic.

The following two code cells loads two packages needed for this example.

In [11]:
import pandas as pd
import matplotlib.pyplot as plt

The next cell reads the data from the titanic.csv file into our Python session and creates five lists, each with 887 elements:

  • name - Contains the names of the titanic passengers.
  • sex - Contains the sex of each of the passengers. Each element is either the string 'male' or the string 'female'.
  • age - Contains the age of each of the passengers, as an integer.
  • pclass - Contains the ticket class of each of the passengers. Each element is an integer 1, 2, or 3. Lower numbers indicate a higher class.
  • surv - Explains whether each of the passengers lived or died in the disaster. Each element is either a 1, indicating that the passenger survived, or a 0, indicating that the passenger died.

Note that any particular index position refers to the same passenger in all three list. In other words, the passenger whose name is in name[37] has their sex recorded in sex[37], has their age recorded in age[37], and so on.

In [12]:
df = pd.read_csv('titanic.csv')
name = list(df['Name']) 
sex = list(df['Sex'])
age = list(df['Age'])
pclass = list(df['Pclass'])
surv = list(df['Survived'])

The following cell will print the record for a randomly selected passenger each time it is ran.

In [13]:
n = random.choice(range(0, len(name)))

print("Name:", name[n])
print("Sex:", sex[n])
print("Age:", age[n])
print("Class:", pclass[n])
print("Survived:", surv[n])
Name: Mr. William Ernest Carter
Sex: male
Age: 36.0
Class: 1
Survived: 1

Survival Rates by Sex

In [14]:
female_survived = 0
female_died = 0
male_survived = 0
male_died = 0


for i in range(0, len(sex)):

    if((sex[i] == "female") and (surv[i] == 1)):
        female_survived += 1
        
    if((sex[i] == "female") and (surv[i] == 0)):
        female_died += 1
        
    if((sex[i] == "male") and (surv[i] == 1)):
        male_survived += 1
        
    if((sex[i] == "male") and (surv[i] == 0)):
        male_died += 1
        
female_total = female_survived + female_died
male_total = male_survived + male_died

print("Total Female Passengers:", female_total)
print("Female Passengers who Survived:", female_survived)
print("Female Passengers who Died:", female_died)
print()
print("Total Male Passengers:", male_total)
print("Male Passengers who Survived:", male_survived)
print("Male Passengers who Died:", male_died)
Total Female Passengers: 314
Female Passengers who Survived: 233
Female Passengers who Died: 81

Total Male Passengers: 573
Male Passengers who Survived: 109
Male Passengers who Died: 464
In [15]:
female_survival_rate = round(female_survived / female_total, 4)
male_survival_rate = round(male_survived / male_total, 4)

print("The proportion of females who survived the Titanic voyage is equal to " + str(female_survival_rate) + ".")
print("The proportion of males who survived the Titanic voyage is equal to " + str(male_survival_rate) + ".")
The proportion of females who survived the Titanic voyage is equal to 0.742.
The proportion of males who survived the Titanic voyage is equal to 0.1902.
In [16]:
survival_rates = [female_survival_rate, male_survival_rate]
death_rates = [1-female_survival_rate,1- male_survival_rate]

plt.bar(range(2),survival_rates, label='Survived', color='cornflowerblue')
plt.bar(range(2),death_rates, label='Died', bottom=survival_rates, color='Salmon')
plt.legend(loc="center left", bbox_to_anchor=(1.03,0.5))
plt.xticks(range(2), ['Female', 'Male'])
plt.ylabel('Proportion')
plt.title('Survival Rate by Sex')
plt.show()

Survival Rates by Passenger Class

In [17]:
c1_survived = 0
c2_survived = 0
c3_survived = 0
c1_total = 0
c2_total = 0
c3_total = 0

for i in range(0, len(pclass)):
    
    if(pclass[i] == 1):
        c1_total += 1
        if(surv[i] == 1):
            c1_survived += 1
            
    elif(pclass[i] == 2):
        c2_total += 1
        if(surv[i] == 1):
            c2_survived += 1
            
    else:
        c3_total += 1
        if(surv[i] == 1):
            c3_survived +=1
            
c1_survival_rate = round(c1_survived / c1_total, 4)
c2_survival_rate = round(c2_survived / c2_total, 4)
c3_survival_rate = round(c3_survived / c3_total, 4)

print("The proportion of 1st class passengers who survived the Titanic voyage is equal to " + str(c1_survival_rate) + ".")
print("The proportion of 2nd class passengers who survived the Titanic voyage is equal to " + str(c2_survival_rate) + ".")
print("The proportion of 3rd class passengers who survived the Titanic voyage is equal to " + str(c3_survival_rate) + ".")
The proportion of 1st class passengers who survived the Titanic voyage is equal to 0.6296.
The proportion of 2nd class passengers who survived the Titanic voyage is equal to 0.4728.
The proportion of 3rd class passengers who survived the Titanic voyage is equal to 0.2444.
In [18]:
survival_rates_by_class = [c1_survival_rate, c2_survival_rate, c3_survival_rate]
death_rates_by_class = [1-c1_survival_rate, 1-c2_survival_rate, 1-c3_survival_rate]

plt.bar(range(3),survival_rates_by_class, label='Survived', color='cornflowerblue')
plt.bar(range(3),death_rates_by_class, label='Died', bottom=survival_rates_by_class, color='Salmon')
plt.legend(loc="center left", bbox_to_anchor=(1.03,0.5))
plt.xticks(range(3), ['Class 1', 'Class 2', 'Class 3'])
plt.ylabel('Proportion')
plt.title('Survival Rate by Class')
plt.show()