Lecture 06 - For Loops
18 September, 2024
&
and |
&
is the logical AND operator: both conditions must be true|
is the logical OR operator: at least one condition must be trueif
statements: conditional execution
if
statements allow you to execute a block of code only if a condition is trueelse
statements: alternative execution
else
statements allow you to execute a block of code if the condition is falseelif
statements: multiple conditions
elif
statements allow you to check multiple conditions&
or |
? 🤔age = 31
) is strictly less than 20, or greater than 30None
to create empty listslist.append()
method to add elements to a listfor
loops, a useful tool to iterate over listsfor
loops to create multiple graphsNone
objectNone
is a special object in Python that represents the absence of a valueNone
is often used to represent missing values or, in our case today, placeholdersNone
is not the same as 0
, False
, or an empty string ''
None
, as it is not a stringNone
:Note
You can read more about None
at https://realpython.com/null-in-python/.
list.append()
methodlist.append()
commandlist.extend()
method*
operatorlist = [value] * n
[7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7]
['Nashville', None, None, 'Nashville', None, None, 'Nashville', None, None, 'Nashville', None, None]
np.array
objects when doing operations+
operator[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
[1, 2, 3, 4, 5, 6]
# When you multipy an array times a number, you multiply each element
import numpy as np
vec_a = np.array(list_a)
print(vec_a * 4)
[ 4 8 12]
for
loop?for
loop is a way to iterate over a sequence of elementsif
statement, including the colon :
and the necessary indentation (4 spaces)for
loop?list_ids = ["KIA", "Ferrari", "Ford", "Tesla"]
print("Dear customer, we are writing about your " + list_ids[0] + " car.")
print("Dear customer, we are writing about your " + list_ids[1] + " car.")
print("Dear customer, we are writing about your " + list_ids[2] + " car.")
print("Dear customer, we are writing about your " + list_ids[3] + " car.")
Dear customer, we are writing about your KIA car.
Dear customer, we are writing about your Ferrari car.
Dear customer, we are writing about your Ford car.
Dear customer, we are writing about your Tesla car.
list_ids = ["KIA", "Ferrari", "Ford", "Tesla"]
for i in list_ids:
print("Dear customer, we are writing about your " + i + " car.")
Dear customer, we are writing about your KIA car.
Dear customer, we are writing about your Ferrari car.
Dear customer, we are writing about your Ford car.
Dear customer, we are writing about your Tesla car.
This code iterates over each element in list_ids
and three additional elements: ‘a’, ‘b’, and ‘c’.
The +
operator is used to concatenate list_ids
with another list ['a', 'b', 'c']
.
For each element in this combined list, the loop assigns the element to the variable id
and then prints it out using the print
function.
index = 1
before the loop (just to start at 1, since Python indexes start at 0)index = index + 1
at the end of the bodylist_ids = ["KIA", "Ferrari", "Ford", "Tesla"]
index = 1
print('We are out of the loop', index)
for id in list_ids:
print("Dear customer, your position is " + str(index) + " on the waitlist" +
" and your car brand is " + id )
index = index + 1
print('We are inside the loop', index)
We are out of the loop 1
Dear customer, your position is 1 on the waitlist and your car brand is KIA
We are inside the loop 2
Dear customer, your position is 2 on the waitlist and your car brand is Ferrari
We are inside the loop 3
Dear customer, your position is 3 on the waitlist and your car brand is Ford
We are inside the loop 4
Dear customer, your position is 4 on the waitlist and your car brand is Tesla
We are inside the loop 5
for i in range(len(list_ids)):
print("Dear customer, your position is " + str(i+1) + " on the waitlist" +
" and your car brand is " + list_ids[i])
Dear customer, your position is 1 on the waitlist and your car brand is KIA
Dear customer, your position is 2 on the waitlist and your car brand is Ferrari
Dear customer, your position is 3 on the waitlist and your car brand is Ford
Dear customer, your position is 4 on the waitlist and your car brand is Tesla
range(len(list_ids))
does?str(i+1)
do?for
loopsimport pandas as pd
import matplotlib.pyplot as plt
carfeatures = pd.read_csv("data/features.csv")
list_vars = ["acceleration","weight"]
variable_name = "acceleration"
plt.scatter(x = carfeatures[variable_name],
y = carfeatures["mpg"])
plt.ylabel("mpg")
plt.xlabel(variable_name)
plt.show()
variable_name = "weight"
plt.scatter(x = carfeatures[variable_name],
y = carfeatures["mpg"])
plt.ylabel("mpg")
plt.xlabel(variable_name)
plt.show()
carfeatures = pd.read_csv("data/features.csv")
list_vars = ["acceleration","weight"]
index = 1
for variable_name in list_vars:
plt.scatter(x= carfeatures[variable_name], y = carfeatures["mpg"])
plt.ylabel("mpg")
plt.xlabel(variable_name)
plt.title("Figure " + str(index))
plt.show()
index = index + 1
# Create a list of x-values list_x = [1,2,4,5, ..., 50]
# Create a list of y-values to fill in later.
list_x = [1,2,4,5,6,7,8,9,10]
list_y = [None] * len(list_x)
# Create an index
index = 0
for x in list_x:
list_y[index] = list_x[index]**2 + 2*list_x[index]
index = index + 1
# Display results visually
print(list_y)
plt.scatter(list_x, list_y)
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Scatter plot of Y = X^2 + 2X")
plt.show()
[3, 8, 24, 35, 48, 63, 80, 99, 120]
(age < 20) | (age > 30)
(age < 25) & (age > 27)
&
operator checks if both conditions are true simultaneously. So, someone should be less than 25 and greater than 27 at the same time, which is impossible.|
, which checks if at least one of the conditions is true (but not both!). For the age to be not in the range 25-27, it must be either less than 25 or greater than 27.list_personal = []
list_personal.append("First element")
list_personal.append("Second element")
print(len(list_personal))
2
# Here I used the index -1 to change the last element
# You could also use the index 1
list_personal[-1] = "Last element"
print(list_personal)
['First element', 'Last element']
range(len(list_ids))
:
len(list_ids)
gets the length (number of items) in the list_ids
list.range()
then creates a sequence of numbers from 0 up to (but not including) that length.str(i+1)
:
i
is the current loop index, starting at 0.i+1
adds 1 to that index so that the position number starts at 1. (Remember: Python indexes start at 0.)str()
converts the resulting number to a string[2].i
starts at 0, but we want to display position numbers starting at 1 for the customers.So, this code loops through each item in list_ids
, printing a message for each customer that includes: - Their position (index + 1) - The corresponding car brand from list_ids
The loop will run once for each item in list_ids
, with i
taking on values from 0 to len(list_ids) - 1
.