JamCoders

💾 Download

JamCoders Day 2 Lecture 2

Loops, Double loops, more on functions

Boaz Barak

For loops

The format of a for loop is

for VARIABLE in COLLECTION:
    FOR_LOOP_BODY

COLLECTION can be list, range, and other objects too

In [ ]:
for x in [2,19,4]:
    print(x)
2
19
4
In [ ]:
# What will be printed?
result = 0
for x in [2,19,4]:
    result = result + x
print(result)
In [ ]:
for x in range(4):
    print(x)
0
1
2
3
In [ ]:
# What will be printed?
result = 0
for x in range(101):
    result = result + x
print(result)
5050

Example

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.

In [ ]:
value = 100
for year in range(20):
    value = value * 1.04
print(value)
219.11231430334212

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.

In [ ]:
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
In [ ]:
final_value(100,4,20)
Out[ ]:
219.11231430334212
In [ ]:
# shortcut

100*(1.04)**20
Out[ ]:
219.1123143033421

Loops on lists

In [ ]:
# Lists can contain any type
fruits = ["apple", "banana", "cherry"]
for x in fruits:
    print(x)
apple
banana
cherry
In [ ]:
# You can put control flow in a loop
fruits = ["apple", "banana", "cherry"]
for x in fruits:
    if x == 'apple':
        print(x)
apple
In [ ]:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
    if x != 'apple':
        print(x)
banana
cherry

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.

In [ ]:
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
In [ ]:
starts_with_b(fruits)
Out[ ]:
'banana'
In [ ]:
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

In [ ]:
starts_with_b([2,3,7])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-16-f1d7431e5c03> in <module>()
----> 1 starts_with_b([2,3,7])

<ipython-input-13-148868dec26d> in starts_with_b(L)
      2   """Returns the first element in the list L that starts with the letter b"""
      3   for elem in L:
----> 4     if elem[0]=='b':
      5       return elem
      6   return None

TypeError: 'int' object is not subscriptable
In [ ]:
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
In [ ]:
L = ["Apple","","banana"]
starts_with_b(L)
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-20-1a2dfd4615fb> in <module>()
      1 L = ["Apple","","banana"]
----> 2 starts_with_b(L)

<ipython-input-19-dbc790dbbba9> in starts_with_b(L)
      4   """
      5   for elem in L:
----> 6     if len(L)>0 and (elem[0]=='b'):
      7       return elem
      8   return None

IndexError: string index out of range
In [ ]:
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
In [ ]:
starts_with_b(L)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Input In [5], in <cell line: 1>()
----> 1 starts_with_b(L)

NameError: name 'L' is not defined

Sometimes because of errors, the function will not have an exception, but will return the wrong output - this is worse!

In [ ]:
starts_with_b("banana")
Out[ ]:
'b'

Always make sure to call a function with inputs that match its assumptions!

In [ ]:
# What will happen?
starts_with_b([])
In [ ]:
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

Options for range (skip)

In [ ]:
# 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)
3
4
5
In [ ]:
# What will this do?
for x in range(3, 3):
    print(x)
In [ ]:
# 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)
3
6

Loops inside loops

In [ ]:
# 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)
In [ ]:
n = 0
for i in range(4):
    for j in range(4):
        n = n+1
# What will be printed?
print("n=",n)
16
In [ ]:
n = 0
for i in range(4):
    for j in range(i):
        n = n+1
# What will be printed
print("n=",n)
n= 6
In [ ]:
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)
(i=1,j=0)
(i=2,j=0)
(i=2,j=1)
(i=3,j=0)
(i=3,j=1)
(i=3,j=2)
n= 6
In [ ]:
# What will be printed?
for i in range(10):
  line = ""
  for j in range(i):
    line += "*"
  print(line)
*
**
***
****
*****
******
*******
********
*********
In [ ]:
!pip install termcolor #not needed for colab
Collecting termcolor
  Downloading termcolor-1.1.0.tar.gz (3.9 kB)
Building wheels for collected packages: termcolor
  Building wheel for termcolor (setup.py) ... done
  Created wheel for termcolor: filename=termcolor-1.1.0-py3-none-any.whl size=4848 sha256=beac596ef673583affdb850ca5bdc8850dd623ebe16c73f68c3febb367cdb7d9
  Stored in directory: /Users/boazbarak/Library/Caches/pip/wheels/b6/0d/90/0d1bbd99855f99cb2f6c2e5ff96f8023fad8ec367695f7d72d
Successfully built termcolor
Installing collected packages: termcolor
Successfully installed termcolor-1.1.0
In [ ]:
# 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)

██████████
████████████████████
██████████████████████████████
████████████████████████████████████████
██████████████████████████████████████████████████
████████████████████████████████████████████████████████████
██████████████████████████████████████████████████████████████████████
████████████████████████████████████████████████████████████████████████████████
██████████████████████████████████████████████████████████████████████████████████████████
██████████████████████████████████████████████████████████████████████████████████████████
████████████████████████████████████████████████████████████████████████████████
██████████████████████████████████████████████████████████████████████
████████████████████████████████████████████████████████████
██████████████████████████████████████████████████
████████████████████████████████████████
██████████████████████████████
████████████████████
██████████