Python: If Statements, Equality Operators and Logical Operators

Aldrin Caalim
Probably Programming
10 min readDec 21, 2020
Image by Arek Socha from Pixabay

This is a summary of Chapter 5 of “Python Crash Course: A Hands-On, Project Based Introduction to Programming” by Eric Matthes

What is an If Statement?

If statements allow decision making in code. They check the stated variable and give a designated response. Here is a basic example:

name = "jill"if name == "jill":
print("Hey Jill")
elif name == "john":
print("Hello John")
else:
print("Wait a minute, who are you?")
>>> Hey Jill

Here is another example:

for number in range(1, 101):
if number == 7:
print(str(number) + " is my favorite number!")
elif number == 50:
print(str(number) + " is half of 100!")
else:
pass
>>> 7 is my favorite number!>>> 50 is half of 100!

As you can see with the above code, we created an empty list to store items. Items were then created from the for loop, in this case, the items are numbers. Then we append each individual item into the list. And then we get to the if statement that says that if any of the individual items is equal to seven, then we will print out “7 is my favorite number!”. Else if any individual item is equal to 50 print out “50 is half of 100!”. Else pass through the code.

So the if statement needs the “if” to initialize it, but you don’t need the “elif”, which is short for “else if”, or the else sections of the if statement. It’s best to use the “else” section as a default response. For example:

names = ['bob', 'bobby', 'bobber', 'gobber']
for name in names:
if name == 'bob':
print(name.title(), "is the shortest name")
elif name == 'bobby':
print(name.title(), "is the second shortest name")
else:
print(name.title(), "is a really long name!")
>>> Bob is the shortest name>>> Bobby is the second shortest name>>> Bobber is a really long name!>>> Gobber is a really long name!

Conditional Tests

If statements are just conditional statements that evaluate to either True or False. If a conditional statement is evaluated to be True, then the code block nested within that condition will be executed. If a conditional statement is evaluated to be False, then the code block nested within the condition will be ignored.

“=” operator versus “==” operator

“=” and “==” are different. “=” is the assignment operator. “==” is one of many equality operators which means “equal to”. For example:

x = 10
print(x)
>>> 10if x == 10:
print("x is equal to 10")
else:
pass
>>> x is equal to 10

If you use the equality operator on a variable that wasn’t assigned a value you will get an error:

value == 10Traceback (most recent call last):
File "main.py", line 1, in <module>
value == 10
NameError: name 'value' is not defined

“!=” operator

“!=” is another equality operator. In this case it means “not equal to”. For example:

x = 5
print(x)
>>> 5if x != 10:
print("x is not equal to 10")
else:
pass
>>> x is not equal to 10

“>” operator

“>” is another equality operator. It means that if the value of the left operand is greater than the value of the right operand, then the condition will be True. Otherwise, the condition will be False. For example:

x = 5
print(x)
>>> 5if x > 10:
print("x is greater than 10")
else:
print("x is not greater than 10")
>>> x is not greater than 10

“<” operator

“<” is an equality operator. It means that if the value of the right operand is greater than the value of the left operand, then the condition will be True. Otherwise, the condition will be False. For example:

x = 5
print(x)
>>> 5if x < 10:
print("x is less than 10")
else:
print("x is not less than 10")
>>> x is less than 10

“>=” operator

“>=” is an equality operator that means that if the value of the left operand is greater than or equal to the value of the right operand, then the condition will be True. Otherwise, the condition will be False. For example:

x = 5
print(x)
>>> 5if x >= 10:
print("x is greater than or equal to 10")
else:
print("x is not greater than or equal to 10")
>>> x is not greater than or equal to 10

“<=” operator

“<=” is an equality operator that means that if the value of the right operand is greater than or equal to the value of the left operand, then the condition will be True. Otherwise, the condition will be False. For example:

x = 5
print(x)
>>> 5if x <= 10:
print("x is less than or equal to 10")
else:
print("x is not less than or equal to 10")
>>> x is less than or equal to 10

Python is Case Sensitive

name = 'bob'
if name == 'Bob'
print("This Bob is uppercase")
elif name == 'bob'
print("This bob is lowercase")
else:
print("This won't print")
>>> This bob is lowercase

As you can see with the above code, I purposely placed “Bob” above “bob” as Python reads if statements starting from the top to the end of the if statement looking for the first True condition. That would be an important thing to note in some cases such as the “Fizz Buzz” problem. Here is my answer to the problem:

print("Here is the Fizz Buzz answer:")for number in range(1, 101):
if number % 3 == 0 and number % 5 == 0:
print("Fizz Buzz")
elif number % 3 == 0:
print("Fizz")
elif number % 5 == 0:
print("Buzz")
else:
print(number)

The reason why I designated the if part of the if statement to hold the “Fizz Buzz” response is because, as I said earlier, Python starts from the top and keeps going until it finds the first True condition. If you placed the “Fizz Buzz” response at the end of the if statement, then you will never see “Fizz Buzz” since Python stops at the first True statement.

Checking Multiple Conditions

As you saw earlier in the “Fizz Buzz” problem, I used an “and” to bridge two different conditions. Logical operators are used to combine multiple conditional statements. The three logical operators are “and”, “or”, and “not”.

Using “and” to check multiple conditions

Logical operator “and” will return True as long as all the conditions is True. For example:

first = "jill"
last = "smith"
if first == "jill" and last == "smith":
print("Hello jill smith")
else:
print("Who are you?")
>>> Hello jill smith

You can also use the logical “and” operator multiple times in the same conditional statement. For example:

first = "jill"middle = "ann"last = "smith"if first == "jill" and middle == "ann" and last == "smith":
print("Hello jill ann smith")
else:
print("Who are you?")
>>> Hello jill ann smith

Using “or” to check multiple conditions

Logical “or” operator will return True as long as one of the conditions are True. For example:

x = 25
y = 50
z = 100
if x > y or x > z:
print("This will not print")
elif x < y or x < z or x > y:
print("This will print")
>>> This will print

Using “not”

Logical “not” operator will change a boolean statement. It’s easier to explain with an example:

print(True == True) #True equal to True>>> Trueprint(not True == True) #not True(changes to False) equal to True>>> Falseprint(False == False) #False equal to False>>> Trueprint(not False == False) #not False(changes to True) equal to False>>> False

Checking Whether an Item is in a List

To check if a particular item is in a list, use the keyword “in”. For example:

groceries = ["eggs", "milk", "bread", "cheese"]if "eggs" in groceries:
print("We need eggs!")
elif "milk" in groceries:
print("We still need milk!")
elif "bread" in groceries:
print("We need bread!")
elif "cheese" in groceries:
print("We need the cheese!")
else:
print("We got everything")
>>> We need eggs!

The “in” keyword will check the list to see if particular items are found in the list. So if we just popped an item out of the list, we would get this result:

groceries = ["eggs", "milk", "bread", "cheese"]groceries.pop(0)if "eggs" in groceries:
print("We need eggs!")
elif "milk" in groceries:
print("We still need milk!")
elif "bread" in groceries:
print("We need bread!")
elif "cheese" in groceries:
print("We need the cheese!")
else:
print("We got everything")
>>> We still need milk!

Checking to see if an Item is not in a List

Use the keyword “not” to check if a value does not appear in a list. For example:

banned = ['john', 'bob', 'amber']
user = 'maria'
if user not in banned:
print(user.title() + ", enjoy your time here")
else:
print(user.title() + ", you're currently banned"
>>> Maria, enjoy your time here

Boolean Expressions

Boolean expressions are a synonym for conditional tests. A boolean value is either True or False. Boolean values are often used to keep track of a certain condition. For example:

is_game_over = False
is_full_health = True

Simple If Statement

A simple if statement has one condition and one action:

if condition:
do something

You can place any condition in the condition line. You can also place any action in the indented block. For example:

name = 'jenna'if name == 'jenna':
print(name.title() + ", hope you are well!")
>>> Jenna, hope you are well!

Remember, any indented lines will only run if the condition is the first True statement. In a simple if statement, if the condition is evaluated to be all False, then no code will run.

The If-Else Statement

Similar to the simple if statement, except for the fact that the else section will run if all the other earlier statements were evaluated to be False. For example:

name = 'jenna'if name != 'jenna':
print("Wait a minute, you're not Jenna!")
else:
print("I found you Jenna!")
>>> I found you Jenna!

The If-Elif-Else Chain

Similar to the if-else statement, except that the elif section allows us more flexibility in our decision making. You can have multiple elif statements to cover for more possibilities. For example:

name = 'jenna'if name == 'john':
print("Wait a minute, you're not Jenna!")
elif name == 'ryan':
print("I see that you're a perfectionist.")
elif name == 'creed':
print("You want a pie for your birthday?")
elif name == 'andy':
print("No Andy, the fire is not shooting at us.")
else:
print("I found you Jenna!")
>>> I found you Jenna!

Omitting the Elif-Else Block

As you saw before in the simple if statement, all you need is the if statement to perform decisions in code. You can omit both the elif and else blocks if you needed to. Remember, elif helps add more decision making in your code. While else is the catchall statement that prevents no code from running even if the other conditions were evaluated to be False. Therefore, else is always True.

Testing Multiple Conditions

The one flaw with the if-elif-else block would be its behavior. Remember that the first True condition will stop the entire if-elif-else block and only run the code found nested within the True condition. If you wanted to check all the conditions of interest, then you would use a series of simple if statements. For example:

sandwich_items = ['lettuce', 'chicken', 'beef', 'ham', 'cheese']if 'lettuce' in sandwich_items:
print('Added lettuce')
if 'cheese' in sandwich_items:
print('Added cheese')
if 'ketchup' in sandwich_items:
print('Added ketchup')
print("\nHere is your sandwich")>>> Added lettuce>>> Added cheese>>> Here is your sandwich

Here’s what an if-elif-else variation would look like:

sandwich_items = ['lettuce', 'chicken', 'beef', 'ham', 'cheese']if 'lettuce' in sandwich_items:
print('Added lettuce')
elif 'cheese' in sandwich_items:
print('Added cheese')
elif 'ketchup' in sandwich_items:
print('Added ketchup')
else:
pass
print("\nHere is your sandwich")>>> Added lettuce>>> Here is your sandwich

If you want only one block of code to run, use the if-elif-else block. If you want more than one block of code to run, use a series of independent if statements.

Using If Statements with Lists

ingredients = ['sausage', 'eggs', 'cheese', 'hashbrowns']for ingredient in ingredients:
if ingredient == 'cheese':
print("Sorry we are out of Cheese at the moment")
else:
print("Adding " + ingredient.title() + " to your meal")
print("\nHere is your meal")>>> Adding Sausage to your meal>>> Adding Eggs to your meal>>> Sorry we are out of Cheese at the moment>>> Adding Hashbrowns to your meal>>> Here is your meal

As you can see, we are checking each requested item before we add it to the meal. The for loop runs through each item of the list, meanwhile the if statement checks each ingredient to decide what to do with the item. In this case, when the loop through the list and get to the item ‘cheese’ we want to tell the customer that we are currently out of cheese. The else block will allow us to add all the other ingredients to the meal.

Checking that a List is not Empty

ingredients = []if ingredients:
for ingredient in ingredients:
print("Adding " + ingredient.title() + " to your meal.")
print("\nFinished making your meal.")else:
print("Are you sure you don't want to customize your meal?")
>>> Are you sure you don't want to customize your meal?

This time, we’re using the if-else statement to check if the ingredients list is empty or not. If there are no ingredients then the customer will receive a message asking if they don’t want to customize their meal. If the list is not empty, then it will behave as it did earlier by printing out each ingredient and telling the customer the meal is finished.

Using Multiple Lists

available_ingredients = ['sausage', 'eggs', 'cheese', 'hashbrowns']requested_ingredients = ['mushrooms', 'cheese', 'hashbrowns']for requested_ingredient in requested_ingredients:
if requested_ingredient in available_ingredients:
print("Adding " + requested_ingredient.title() + " to your meal.")
else:
print(requested_ingredient.title() + " is not available.")
print("\nFinished making your meal")>>> Mushrooms is not available.>>> Adding Cheese to your meal.>>> Adding Hashbrowns to your meal.>>> Finished making your meal

At the beginning of the code, we create two lists, one for all available ingredients and another for the customer’s requested ingredients. Then we create a for loop to loop through each item in the customer’s requested ingredient list. If the requested ingredients can be found in the available ingredients, then we will add them to the customer’s meal. Otherwise, we will inform the customer that the ingredient is not currently available.

--

--