The format of a for
loop is
for VARIABLE in COLLECTION:
FOR_LOOP_BODY
COLLECTION
can be list, range, and other objects too
for x in [2,19,4]:
print(x)
# What will be printed?
result = 0
for x in [2,19,4]:
result = result + x
print(result)
for x in range(4):
print(x)
# What will be printed?
result = 0
for x in range(101):
result = result + x
print(result)
Suppoe that you invest hundred dollars in stock X. Every year the stock grows by 4%. How much will your stock be worth after 20 years.
value = 100
for year in range(20):
value = value * 1.04
print(value)
Write a function final_value
that takes as input initial_investment
, pct_growth_per_year
, and num_years
and returns the final value of the investment.
def final_value(initial_investment, pct_growth_per_year,num_years):
value = initial_investment
for year in range(num_years):
value *= 1+pct_growth_per_year / 100
return value
final_value(100,4,20)
# shortcut
100*(1.04)**20
# Lists can contain any type
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
# You can put control flow in a loop
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == 'apple':
print(x)
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x != 'apple':
print(x)
Write a function starts_with_b
that takes as input a list L
of strings and returns the first element in the list that starts with the letter b
. Otherwise it returns None
.
def starts_with_b(L):
"""Returns the first element in the list L that starts with the letter b"""
for elem in L:
if elem[0]=='b':
return elem
return None
starts_with_b(fruits)
starts_with_b(["apple", "cherry"])
When you write a function, it makes some assumptions on its input. If the assumptions are wrong then it may result in an error or Exception
starts_with_b([2,3,7])
def starts_with_b(L):
"""Returns the first element in the list L that starts with the letter b
Assumes: L is a list of strings
"""
for elem in L:
if elem[0]=='b':
return elem
return None
L = ["Apple","","banana"]
starts_with_b(L)
def starts_with_b(L):
"""Returns the first element in the list L that starts with the letter b
Assumes: L is a list of strings
"""
for elem in L:
if len(elem)>0 and (elem[0]=='b'):
return elem
return None
starts_with_b(L)
Sometimes because of errors, the function will not have an exception, but will return the wrong output - this is worse!
starts_with_b("banana")
Always make sure to call a function with inputs that match its assumptions!
# What will happen?
starts_with_b([])
def starts_with_b(L):
"""Returns the first element in the list L that starts with the letter b
Assumes: L is a list of strings
"""
for elem in L:
if len(elem)>0 and (elem[0]=='b'):
return elem
return None
# range with two arguments (call them n and m) is like looping over the list from n to m-1
for x in range(3, 6):
print(x)
# What will this do?
for x in range(3, 3):
print(x)
# Range with three arguments (call them n, m, and step)
# is like looping over the list from n to m-1, but incrementing by step
for x in range(3, 8, 3):
print(x)
# You can put loops inside loops
# ALWAYS make sure the variables for the loops are different
for i in range(3):
for j in range(3): # DO NOT USE i HERE
print(i, j)
n = 0
for i in range(4):
for j in range(4):
n = n+1
# What will be printed?
print("n=",n)
n = 0
for i in range(4):
for j in range(i):
n = n+1
# What will be printed
print("n=",n)
n = 0
for i in range(4):
for j in range(i):
print(f"(i={i},j={j})")
n = n+1
# What will be printed
print("n=",n)
# What will be printed?
for i in range(10):
line = ""
for j in range(i):
line += "*"
print(line)
!pip install termcolor #not needed for colab
# What will be printed?
from termcolor import colored # colored(text,color) prints text in color
for i in range(0,20):
line = ""
for j in range(0,100):
if (j<5*i and j< 99-5*i) or (j>5*i and j> 99-5*i):
color= None
else:
color = "green"
if (j//5 == i) or ((99-j)//5==i): color="yellow"
line += colored("█",color)
print(line)