A Boolean value is either True
or False
and is used frequently in computer programs.
Google Maps uses a boolean to decide whether to avoid highways in driving directions:
avoid_highways = True
Twitter uses a boolean to remember where the user allows personalized ads:
personalized_ads = False
An expression can evaluate to a Boolean. Most Boolean expressions use either comparison or logical operators.
An expression with a comparison operator:
passed_class = grade > 65
An expression with a logical operator:
wear_jacket = is_raining or is_windy
Operator | Meaning | True expressions |
== | Equality | 32 == 32
|
!= | Inequality | 30 != 32
|
> | Greater than | 60 >= 32
|
>= | Greater than or equal | 60 >= 32 , 32 >= 32
|
< | Less than | 20 < 32
|
<= | Less than or equal | 20 < 32 , 32 <= 32
|
⚠️ Common mistake: Do not confuse =
(the assignment operator) with ==
(the equality operator).
⚠️ Common mistake: Do not confuse =
(the assignment operator) with ==
(the equality operator).
x = y
is very different from
x == y
Operator | True expressions | Meaning |
---|---|---|
and | 4 > 0 and -2 < 0 | Evaluates to True if both cconditions are true; otherwise evaluates to False .
|
or | 4 > 0 or -2 > 0 | Evaluates to True if either condition is true; evaluates to False only if both are false.
|
not | not (5 == 0) | Evaluates to True if condition is false; evaluates to False if condition is true.
|
W3Schools has a handy Python operators reference
A conditional statement gives you a way to execute a different set of code statements based on whether certain conditions are true or false.
if <condition>:
<statement>
<statement>
...
A simple conditional:
clothing = "shirt"
if temperature < 32:
clothing = "jacket"
def get_number_sign(num):
if num < 0:
sign = "negative"
elif num > 0:
sign = "positive"
else:
sign = "neutral"
return sign
Syntax tips:
if
clause.
elif
clauses.
else
clause, always at the end.
The while loop syntax:
while <condition>:
<statement>
<statement>
As long as the condition is true, the statements below it are executed.
multiplier = 1
while multiplier <= 5:
print(9 * multiplier)
multiplier += 1
We need to tell a While loop when to stop, otherwise it might keep running forever!
It's common to use a counter variable whose job is keeping track of the number of times the loop has run.
total = 0
counter = 0
while counter < 5:
total += pow(2, 1)
counter += 1
What's this +=
thing?
counter += 1
does the same thing as counter = counter + 1
Can also subtract -=
, multiply *=
, divide /=
and assign the result
See the full list of special assignment operators on W3Schools
A loop in a function will commonly use a parameter to determine some aspect of its repetition.
def sum_up_squares(start, end):
counter = start
total = 0
while counter <= end:
total += pow(counter, 2)
counter += 1
return total
sum_up_squares(1, 5)
Let's review the homework from last week together!
Note: We did the first problem from each exercise together in class
A data structure is a particular way of organizing data in a computer so that it can be used effectively.
Data structures in programming are a bit like lists and tables in text docs/presentations - we use them to organize information and make it more meaningful/useful.
A list is a container that holds a sequence of related pieces of information.
The shortest list is an empty list, just 2 square brackets:
members = []
Lists can hold any Python values, separated by commas:
# all strings
members = ["Liz", "Tinu", "Brenda", "Kaya"]
# all integers
ages_of_kids = [1, 2, 7]
# all floats
prices = [79.99, 49.99, 89.99]
# mixed types
mixed_types = ["Liz", 7, 79.99]
Lists are ordered. Each list item has an index, starting from 0.
temps = [48.0, 30.5, 20.2, 99.0, 52.0]
# Index: 0 1 2 3 4
Access each item by putting the index in brackets:
temps[0] # 48.0
temps[1] # 30.5
temps[2] # 20.2
temps[3] # 99.0
temps[4] # 52.0
temps[5] # 🚫 Error!
Use the global len()
function
to find the length of a list.
attendees = ["Tammy", "Shonda", "Tina"]
print(len(attendees)) # 3
num_of_attendees = len(attendees)
print(num_of_attendees)
🤔 What could go wrong with storing the length?
Python lists are mutable, which means you can change the values stored in them.
Use bracket notation to modify single items in the list:
temps = [48.0, 30.5, 20.2, 99.0, 52.0]
temps[2] = 22.22
temps[-1] = 55.55
What if we change the value of an item beyond the list length?
temps[5] = 111.11 # 🚫 Error!
Method | Description |
---|---|
append(item)
| Adds item to the end of the list. This increases list length by one.
|
insert(index, item)
| Inserts item at the specified index . This increases the list length by one and
shifts all items after the specified index forward by one index.
|
remove(item)
| Remove the first item from the list whose value is equal to item .
It raises a ValueError if there is no such item.
|
index(item)
| Returns the index of the first occurrence of an item whose value is equal to item .
It raises a ValueError if there is no such item.
|
pop([index])
| If no index is specified, it removes the last item from the list and returns it.
Otherwise, it removes the item at the specified index and returns it.
|
See more in Python.org documentation
groceries = ["apples", "bananas"]
groceries.append("peanut butter")
groceries.insert(0, "applesauce")
groceries.insert(3, "cheerios")
groceries.remove("bananas")
bought_food = groceries.pop()
bought_food2 = groceries.pop(1)
i = groceries.index("cheerios")
bought_food3 = groceries.pop(i)
We'll work on the first question together, and then you'll work on the rest individually.
The other type of loop supported in Python is a for
loop
The for loop syntax:
for <value> in <sequence>:
<statement>
<statement>
For loops provide a clean way of repeating code for each item in a data structure (like a list).
for
loops are for cases where the loop will run for a known number of times, ex for each item in a list
while
loops are for cases where the loop may run for an unknown number of times, ex until a condition is no longer true
😍 For loops love lists!
scores = [80, 95, 78, 92]
total = 0
for score in scores:
total += score
This does the same thing as a while
loop with a counter, but with less code.
scores = [80, 95, 78, 92]
total = 0
i = 0
while i < len(scores):
score = scores[i]
total += score
i += 1
We'll work on the first question together, and then you'll work on the rest individually.
Since Python lists can contain any values, an item can itself be a list.
gymnasts = [
["Brittany", 9.15, 9.4, 9.3, 9.2], # gymnasts[0]
["Lea", 9, 8.8, 9.1, 9.5], # gymnasts[1]
["Maya", 9.2, 8.7, 9.2, 8.8] # gymnasts[2]
]
You can think of nested lists like rows in a table:
gymnasts = [
["Brittany", 9.15, 9.4, 9.3, 9.2], # gymnasts[0]
["Lea", 9, 8.8, 9.1, 9.5], # gymnasts[1]
["Maya", 9.2, 8.7, 9.2, 8.8] # gymnasts[2]
]
gymnasts
? 3
gymnasts[0]
? 5
gymnasts = [
["Brittany", 9.15, 9.4, 9.3, 9.2],
["Lea", 9, 8.8, 9.1, 9.5],
["Maya", 9.2, 8.7, 9.2, 8.8]
]
Access using bracket notation, with more brackets as needed:
gymnasts[0] # ["Brittany", 9.15, 9.4, 9.3, 9.2]
gymnasts[0][0] # "Brittany"
gymnasts[1][0] # "Lea"
gymnasts[1][4] # 9.5
gymnasts[1][5] # 🚫 IndexError!
gymnasts[3][0] # 🚫 IndexError!
gymnasts = [
["Brittany", 9.15, 9.4, 9.3, 9.2],
["Lea", 9, 8.8, 9.1, 9.5],
["Maya", 9.2, 8.7, 9.2, 8.8]
]
Modify using bracket notation as well, just like before:
gymnasts[0] = ["Olivia", 8.75, 9.1, 9.6, 9.8]
gymnasts[1][0] = "Leah"
gymnasts[2][4] = 9.8
If we start with...
gymnasts = [
["Brittany", 9.15, 9.4, 9.3, 9.2],
["Lea", 9, 8.8, 9.1, 9.5]
]
We can append another list a few ways:
gymnasts.append(["Maya", 9.2, 8.7, 9.2, 8.8])
gymnasts += ["Maya", 9.2, 8.7, 9.2, 8.8]
gymnast = []
gymnast.append("Maya")
gymnast.append(9.2)
gymnast.append(8.7)
gymnast.append(9.2)
gymnast.append(8.8)
gymnasts.append(gymnast)
gymnasts = [
["Brittany", 9.15, 9.4, 9.3, 9.2],
["Lea", 9, 8.8, 9.1, 9.5],
["Maya", 9.2, 8.7, 9.2, 8.8]
]
Use a nested for-in
loop:
for gymnast in gymnasts:
for data in gymnast:
print(data, end="|")
Remember what type of data is being stored in the loop variable!
Finish the rest of the questions in each exercise - we'll review in the next class
Please fill out the feedback form to let me know how I can improve the class!