Loops#

Open In Colab

Course Announcements

Due this week:

  • VQ8 due Wed

  • CL4 due Fri

  • A3 due Sun

  • Take your exam!

Control Flow - Loops#

  • while

  • for

  • range, continue, break

SideNote: counters#

# Initialize a counter variable
counter = 0 
print(counter)
counter = counter + 1
print(counter)
counter = counter + 1
print(counter)

The idea here…is that as the code executes, the value of the counter increases. We’ll use these a lot in loops!

SideNote: append#

append is a list methods (we’ll talk about others soon) that adds an item to the end of an existing list in place

my_list = ['a', 'b', 'c']
my_list.append('d') ### NOTE THAT IT IS NOT ASSIGNED BACK TO my_list
my_list
['a', 'b', 'c', 'd']

Loops#

A loop is a procedure to repeat a piece of code.

while Loops#

A while loop is a procedure to repeat a piece of code while some condition is still met.

while Loop: live demo#

while is_sitting(studentA):
    # studentB moves one sheet of paper from chair to table

for Loops#

A for loop is a procedure a to repeat code for every element in a sequence.

for Loop: live demo#


students_in_line = ['', '', '', '', '']
brown_hair = []
other_hair = []

for student in students_in_line:
    if has_brown_hair(student):
        brown_hair.append(student)
    else:
        other_hair.append(student)         

Activity I: Comprehension Check#

Complete all questions in this Google Form (https://forms.gle/N8ao851V5G3rdnSo7) and then click submit.

You are encouraged to:

  1. Talk with your neighbor

  2. Try things out to check your understanding

If you have questions, I’m happy to come over as we work on this!

Loops: Code#

while Loop: code#

shopping_budget = 20
bill = 0
index = 0
prices = [3, 4, 10, 3, 2, 15, 7]

while bill < shopping_budget:
  
    # add cost of item (prices) to bill
    bill = bill + prices[index]
    
    # increment index each time through the loop
    index = index + 1
    
    #print bill so we can see what's going on
    print(bill)

for loop: code#

# Define a list of items
shopping_list = ['bananas', 'cookies', 'ice cream']
in_stock = ['apples', 'bananas', 'cookies', 'chicken', 'cucumbers']
in_cart = []

# Loop across each element
for item in shopping_list:
    if item in in_stock:
        in_cart.append(item)
    else: 
        print(item + ' not in stock')

in_cart
ice cream not in stock
['bananas', 'cookies']
# Loop across items in a string
vowels = ['A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u']
my_string = 'python'

for char in my_string:
    if char not in vowels:
        print(char)

Activity II: loops#

Complete the coding question in this Google Form (https://forms.gle/MRrSUvFDAehJmpxX7) and then click submit.

Write a function sum_odd() contatining a loop that will add up all the odd numbers in an input list.

For example: sum_odd(['a', 3, 5, 6]) would return 8, b/c 3 + 5 is 8

# WRITE CODE
# TEST FUNCTION

Dictionaries: Indexing & Looping#

Dictionaries are indexed by their key.

scores = {
    'Alondra': 85,
    'Holly': 58,
    'Brooke': 92,
    'Pauline': 47,
    'Minqi': 76
}

scores['Holly']
58
passing_score = 60
passed_students = []

for student in scores:
    if scores[student] >= passing_score:
        passed_students.append(student)

print("Students who passed:", passed_students)
Students who passed: ['Alondra', 'Brooke', 'Minqi']

Activity III: Dictionaries#

Complete the coding question in this Google Form (https://forms.gle/Cgw35fmyhfqRMx178) and then click submit.

Define a function name_dictionary that will generate a dictionary that stores each unique letter in the input name as a different key, and the number of times each letter shows up in your name as the letter’s value.

For example, name_dictionary('Shannon')would return: {'S':1, 'h':1, 'a': 1, 'n': 3, 'o': 1}

An aside…there’s a shortcut! The += operator

out = out + 4

# OR 

out += 4

# THE CODE
# TEST IT OUT

range, continue and break#

range#

range is an operator to create a range of numbers, that is often used with loops.
# for temp in [114, 115, 116, 117, 118]:
for temp in range(114, 119): 
    print(temp)
    
    if(temp > 115):
        print('The tea is too hot!')

continue#

continue is a special operator to jump ahead to the next iteration of a loop.
for number in range(1, 11):
    if number % 2 == 0:
        continue  # Skip even numbers

    print(number)
1
3
5
7
9

break#

break is a special operator to break out of a loop.

break examples#

numbers = [4, 7, 10, 3, 8, 5]

for num in numbers:
    if num == 8:
        print("Found 8!")
        break  # Stop the loop as soon as we find 8
Found 8!

Activity: range, break, continue#

Coming soon

Code Style: Loops#

  • for/while statement with a colon at the end on first line

  • all code within the loop inside a code block (indented)

Good Code Style

number = 5
while number < 0:
    print(number)
    number = number + 1

Code Style to Avoid

number=-5
while number<0:print(number);number=number+1 # avoid all on a single line

Activity: Additional Loops Practice#

Coming Soon