Loops#

Last week’s highlights#

  • Lists

  • Ranges

Agenda#

Loops

  • types of loops: while, for
  • Other loop statements: break, continue
  • The phonebook of Rick

For loops#

Syntax#

for element in iterable:
    statement1
    statement2
    
rest of code

Iteration can also be done on a string#

name = "Rick"
for letter in name:
    print("Give me", letter)
print("What did we get?", name)
Give me R
Give me i
Give me c
Give me k
What did we get? Rick

Put zeros instead each even element#

# Modify the list
lst = [1,2,3,4,7]
for i in range(len(lst)):
    if lst[i] % 2 == 0:
        lst[i] = 0
print(lst)
[1, 0, 3, 0, 7]
# The This is NOT equivalent! Does not modify the list...
lst = [1,2,3,4,7]
for elem in lst:
    if elem % 2 == 0:
        elem = 0
print(lst)
[1, 2, 3, 4, 7]

Slide 55

Infinite for loop#

# Do not run this code
x=[1]
for a in x:
    x.append(1)
    print(x)

Avoid changing the list on which you iterate! (may cause all kind of problem, including infinite loops)#

Example #3: concatenate all characters in a matrix into a single string#

mat = [["m", "a", "t", "R"], ["i", "c", "k", "s"]]
# Write your code here
mat = [["m", "a", "t", "R"], ["i", "c", "k", "s"]]
my_string=""
num_rows = len(mat)
num_columns = len(mat[0])
for i in range(num_rows):
    for j in range(num_columns):
        my_string+=mat[i][j]
print(my_string)
matRicks

Try this with Python Tutor

Slide 56

while loops#

Syntax#

while expression: ## expression is either True or False
    statement1
    statement2
    
rest of code

Infinite loop#

# Do not run this code
i = 1
while i < 137:
    print(i)

break and continue statements#

  • Interrupts the nearest enclosing loop

  • Jointly used with an if statement

break statement – breaking loops#

lst = [4, 2, -6, 3,-9]
for elem in lst:
    if elem < 0: 
        print("First negative number is", elem)
        break
print("done!")
First negative number is -6
done!
x=0
while x<30: 
    x+=1
    if not x % 10:
        break
    print(x, end='\t')
1	2	3	4	5	6	7	8	9	

continue statement – Skipping loops#

x=0
while x<30: 
    x+=1
    if not x % 10:
        continue
    print(x, end='\t')
1	2	3	4	5	6	7	8	9	11	12	13	14	15	16	17	18	19	21	22	23	24	25	26	27	28	29	

Loops - for or while?#

In most cases it is more natural to use for
In some cases it is better to use while

  • for:

    • Predefined number of iterations

    • No need to initialize or advance the loop variable

  • while:

    • Unknown number of iterations

    • Can specify a stop condition

Self learning#

Exercise 1: List methods#

What will be printed?#

students=['Rick', 'Tiny Rick!', 'Beth', 'Jerry', 'Summer', 'Jessica', 'Rick', 'Rick']
x = students.pop(-1)
if x in students[:len(students)//2] and x in students[len(students)//2:]:
    students.remove(x)
    students.remove(x)
    
if x in students[:len(students)//2] or x in students[len(students)//2:]:
    students.remove(x)

print("Rick" in students)
False

Exercise 2: Multiplication chart#

Solution#

for i in range(1,11):
    for j in range(1,11):
        print(i*j, end ="\t")
    print()
1	2	3	4	5	6	7	8	9	10	
2	4	6	8	10	12	14	16	18	20	
3	6	9	12	15	18	21	24	27	30	
4	8	12	16	20	24	28	32	36	40	
5	10	15	20	25	30	35	40	45	50	
6	12	18	24	30	36	42	48	54	60	
7	14	21	28	35	42	49	56	63	70	
8	16	24	32	40	48	56	64	72	80	
9	18	27	36	45	54	63	72	81	90	
10	20	30	40	50	60	70	80	90	100	

Exercise 3: Unique list of numbers#

Write a function that receives a list of number, and returns a list where each number from the original list appears exactly once.#

[1,3,3,1,7,7,7,1,3] \(\rightarrow\) [1,3,7]

lst = [1,3,3,1,7,7,7,1,3]
## You code here

Solution#

lst = [1,3,3,1,7,7,7,1,3]
uniques = []
for x in lst: 
    if x in uniques: 
        continue 
    uniques.append(x)
print(uniques)
[1, 3, 7]

Exercise 4: The phone book of Rick#

  • We want to develop an application for managing the Contacts of Ricks

  • It will contain a database

  • A list of contacts

  • Each contact is a list in the format [name, phone]

  • Functionality

  • Find contact(s) by full name or prefix

  • Add contact

  • Remove contact

phone_book = [['Morty','1111'], ['Beth', '2222'], ['rick c-138', '8888'], ['rick c-139', '9999']]

Retrieve the number for a given person#

name = 'rick' ## Change the value here
### Write your code here

if found:
    print("Name:", name , "Phone:", phone)
else:
    print("Cannot find", name , "in contact list.")

Solution#

name = 'rick' ## Change the value here
found = False
phone = ""
for contact in phone_book:
    if contact[0] == name:
        found = True
        phone = contact[1]
        break
if found:
    print("Name:", name , "Phone:", phone)
else:
    print("Cannot find", name , "in contact list.")
Cannot find rick in contact list.

Add a contact#

name = 'rick'# Change the value here
num = 1234
phone_book.append([name, num])
print(phone_book)
[['Morty', '1111'], ['Beth', '2222'], ['rick c-138', '8888'], ['rick c-139', '9999'], ['rick', 1234]]

Remove a contact#

name = 'rick'# Change the value here
found = False
for contact in phone_book:
    if contact[0] == name:
        ###  Write your code here

if not found:
    print("Cannot find the contact", "name")

Solution#

name = 'rick'# Change the value here
found = False
for contact in phone_book:
    if contact[0] == name:
        phone_book.remove(contact)
        print(f'The contact {name} was deleted')
        found = True
        break

if not found:
    print("Cannot find the contact", name)
The contact rick was deleted

Search for all contacts with given prefix.#

Ignore character case (aka, case insensitive).#

prefix = "Rick"
### Write your code here
prefix = "Rick"
prefix = prefix.lower()
for contact in phone_book:    
    if contact[0].lower().startswith(prefix):        
        print("Name:", contact[0], "Phone:", contact[1])
Name: rick c-138 Phone: 8888
Name: rick c-139 Phone: 9999