Conditional Statements and While Loops¶
Relational Operators¶
In both math and language, we compare numbers, items, people, or other things to each other. For example, in math, we might compare 7 and 5 and say that "7 is greater than 5". In language, we might compare an apple and an orange and say that "an apple is not an orange". In coding, you can compare data and variables in the same way, using relational operators.
Here are some common relational operators in Python:
==: equal to<: less than>: greater than<=: less than or equal to>=: greater than or equal to!=: not equal to
These relational operators can be used to compare to different objects, such as an int or a string, to each other. The code will check if the comparison is true or false, then will return that value as output.
# "Equal to" comparison with integers
5 == 5
True
# "Equal to" comparison with strings
"apple" == "orange"
False
# "Less than" comparison
5 < 4
False
# "Greater than" comparison
6 > 3
True
# "Less than or equal to" comparison
3 <= 3
True
# "Greater than or equal to" comparison
8 >= 4
True
# "Not equal to" comparison with integers
4 != 9
True
# "Not equal to" comparison with strings
"apple" != "orange"
True
In addition to directly comparing numbers, strings, or other data, you can also compare variables.
# Comparing different variables
int_var1 = 5
int_var2 = 8
string_var1 = "apple"
string_var2 = "orange"
print(int_var1 < int_var2)
print(string_var1 == string_var2)
print(int_var1 != string_var1)
True False True
Membership operators¶
In math and language, we can check if an object is a member within some sort of group. For example, if we have a set of numbers called numbers that include 4, 7, 10, and 15, then we can say that "4 is in numbers". Likewise, if we have the word "mercury", then we can say that "The letter "e" is in "mercury"". In coding, you can check the membership of an object using membership operators.
Here are two common membership operators in Python:
in: checks if an object is in a set of objectsnot in: checks if an object is not in a set of objects
Code with a membership operator will check if an object is in or not in a group objects, then return true or false.
# "In" comparison in strings
'o' in 'origami'
True
# "Not in" comparison in strings
'g' not in 'origami'
False
# "In" comparison in lists
5 in [1, 3, 7, 10]
False
# Membership comparisons using variables
num = 1
list = [2, 6, 8, 14]
print(num in list)
print(num not in list)
False True
Conditional Statements¶
Relational operators and memberships operators can be used within conditional statements to selectively run code.
There are three main types of conditional statements:
- if statements
- if/else statements
- if/elif/else statements
If statements¶
An if statement is the simplest conditional statement. Below is the basic format for an if statement.
if X:
do something
The basic english explanation for an if statement is "If X condition is met, then do something."
Here are some examples:
# An if statement with integers and a relational operator
if 5 == 5:
print("These numbers are equal.")
These numbers are equal.
# An if statement with strings and a relational operator
if "peach" != "persimmon":
print("These strings are different.")
These strings are different.
# An if statement where the condition is false
if 5 < 3:
print("The first number is less than the second number.")
# An if statement with strings and a membership operator
if 'a' in 'data':
print("Data!")
Data!
# An if statement with variables
fruit_letter = 'p'
fruit_string = 'plum'
if fruit_letter in fruit_string:
print("Plum")
Plum
Non-zero integers evaluate to True in conditional statements.
if 1:
print("This is true.")
This is true.
If/else Statements¶
An if/else statement is a two-part conditional statement. Below is the basic format for an if/else statement.
if X:
do something
else:
do something else
The basic english explanation for an if/else statement is "If X condition is met, then do something. Otherwise, if that condition is not met, do something else."
Here are some examples:
# An if/else statement with relational operators, where the condition is met
if 4 < 8:
print("The first number is less than the second number.")
else:
print("The first number is not less than the second number.")
The first number is less than the second number.
# An if/else statement with relational operators, where the condition is not met
if 9 < 8:
print("The first number is less than the second number.")
else:
print("The first number is not less than the second number.")
The first number is not less than the second number.
# An if/else statement with membership operators
if 3 in [1, 4, 7, 10]:
print("This number is in the list.")
else:
print("This number is not in the list.")
This number is not in the list.
# An if/else statement with variables
coffee_shop_string = "Interzone"
coffee_shop_list = ["Coffee Culture", "Kel's Coffee", "Interzone", "Greenhouse Coffee"]
if coffee_shop_string in coffee_shop_list:
print("This coffee shop is in the coffee shop list.")
else:
print("This coffee shop is not in the coffee shop list.")
This coffee shop is in the coffee shop list.
If/elif/else Statements¶
An if/elif/else statement is a multi-part conditional statement. Below is the basic format for an if/elif/else statement.
if X:
do something
elif Y:
do something else
else:
do something else
The basic english explanation for an if/elif/else statement is "If X condition is met, then do something. Otherwise, if X condition is not met, but Y condition is met, do something else. Otherwise, if X and Y conditions are not met, do something else."
Here are some examples:
# An if/elif/else statement where the first condition is met
if 3 < 4:
print("The first number is less than the second number.")
elif 3 > 4:
print("The first number is greater than the second number.")
else:
print("The first number is equal to the second number.")
The first number is less than the second number.
# An if/elif/else statement where the second condition is met
if 5 < 4:
print("The first number is less than the second number.")
elif 5 > 4:
print("The first number is greater than the second number.")
else:
print("The first number is equal to the second number.")
The first number is greater than the second number.
# An if/elif/else statement where the else statement is run
if 4 < 4:
print("The first number is less than the second number.")
elif 4 > 4:
print("The first number is greater than the second number.")
else:
print("The first number is equal to the second number.")
The first number is equal to the second number.
# An if/elif/else statement can have more than one elif statement
squid_word = "Magnapinna"
if squid_word == "Giant squid":
print("Giant squid!")
elif squid_word == "Humboldt squid":
print("Humboldt squid!")
elif squid_word == "Magnapinna":
print("Magnapinna!")
elif squid_word == "Diamond Squid":
print("Diamond Squid!")
else:
print("A different squid.")
Magnapinna!
You can make more complex code with conditional statements, a few of which are shown below.
# Identifying the squid in a collection of squids
squid_list = ["Magnapinna", "Reef squid", "Giant squid", "Colossal squid"]
for squid_word in squid_list:
if squid_word == "Giant squid":
print("Giant squid!")
elif squid_word == "Humboldt squid":
print("Humboldt squid!")
elif squid_word == "Magnapinna":
print("Magnapinna!")
elif squid_word == "Diamond Squid":
print("Diamond Squid!")
else:
print("A different squid.")
Magnapinna! A different squid. Giant squid! A different squid.
# Determining the letter composition of a word.
lengthy_word = "hemidemisemiquaver"
a_count, e_count, i_count, o_count, u_count, con_count = 0, 0, 0, 0, 0, 0
for letter in lengthy_word:
if letter == 'a':
a_count += 1
elif letter == 'e':
e_count += 1
elif letter == 'i':
i_count += 1
elif letter == 'o':
o_count += 1
elif letter == 'u':
u_count += 1
else:
con_count += 1
print(f"The word \"{lengthy_word}\" has {a_count} a's, {e_count} e's, {i_count} i's, {o_count} o's, {u_count} u's, and {con_count} consonants.")
The word "hemidemisemiquaver" has 1 a's, 4 e's, 3 i's, 0 o's, 1 u's, and 9 consonants.
Logical Operators¶
When comparing two objects, you might want to check if multiple conditions are true for the same object. For example, if you have two apples, apple1 and apple2, you might want to check if both apple1 and apple2 are honeycrisp apples. Or, you may want to check if at least one of the apples is a honeycrisp, so if apple1 or apple2 are honeycrisp. These combined comparisons are linked by logical operators.
There are three common logical operators in Python:
and: is one condition and the other condition trueor: is one condition or the other condition truenot: is the condition not true.
Here are some examples of logical operators:
# An if/else statement where both conditions are met
if (5 == 5) and ('five' == 'five'):
print("Both conditions are met.")
else:
print("At least one of the conditions isn't met.")
Both conditions are met.
# An if/else statement where at least one of the conditions isn't met
if (5 == 5) and ('five' == 'six'):
print("Both conditions are met.")
else:
print("At least one of the conditions isn't met.")
At least one of the conditions isn't met.
# An if/else statement where at least one of the conditions isn't met
if (5 == 5) or ('five' == 'six'):
print("At least one of the conditions is met.")
else:
print("None of the conditions are met.")
At least one of the conditions is met.
# An if/else statement with not
hat = True
if not hat:
print("A normal platypus.")
else:
print("Perry the Platypus!")
Perry the Platypus!
While Loops¶
While loops are a type of loop that run until a certain condition isn't met anymore. Below is the basic structure of a while loop.
while (condition is True):
do something
The basic english explanation of a while loop is "While this condition is true, do something, but once it is false, stop doing it."
Here are some examples:
# This while loop executes until counter reaches 5.
counter = 0
while counter < 5:
counter += 1
print(f"Iteration {counter}")
Iteration 1 Iteration 2 Iteration 3 Iteration 4 Iteration 5
# This while loop prints the Fibonacci sequence until the number equals 144
fib_one_prev, fib_two_prev, fib_curr, counter = 1, 0, 0, 3
print(f"Number 1: 0")
print(f"Number 2: 1")
while fib_curr != 144:
fib_curr = fib_one_prev + fib_two_prev
print(f"Number {counter}: {fib_curr}")
counter += 1
fib_two_prev = fib_one_prev
fib_one_prev = fib_curr
print("Fibonacci loop done!")
Number 1: 0 Number 2: 1 Number 3: 1 Number 4: 2 Number 5: 3 Number 6: 5 Number 7: 8 Number 8: 13 Number 9: 21 Number 10: 34 Number 11: 55 Number 12: 89 Number 13: 144 Fibonacci loop done!
# Prints out if the numbers from 1 to 10 are odd or even
# % gets the remainder when the first number is divided by the second number
number = 1
while number <= 10:
if number % 2 == 1:
print(f"The number {number} is odd!")
else:
print(f"The number {number} is even!")
number += 1
The number 1 is odd! The number 2 is even! The number 3 is odd! The number 4 is even! The number 5 is odd! The number 6 is even! The number 7 is odd! The number 8 is even! The number 9 is odd! The number 10 is even!
A for loop can be converted to a while loop and vice versa.
for num in range(5):
print(num)
0 1 2 3 4
num = 0
while num < 5:
print(num)
num += 1
0 1 2 3 4