Loops#
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)
0
counter = counter + 1
print(counter)
1
counter = counter + 1
print(counter)
2
counter += 1
print(counter)
3
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#
while
Loops#
while
Loop: live demo#
while is_sitting(studentA):
# studentB moves one sheet of paper from podium to table
for
Loops#
for
Loop: live demo#
students_in_line = ['Lando', 'Annalise', 'Isaac', 'Parm']
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:
Talk with your neighbor
Try things out to check your understanding
If you have questions, I’m happy to come over as we work on this!
this_list = ['hi', 'bye', 'good', 'bad']
this_list.append('ok')
# this_list[4] = 'ok' # does not work
# this_list + ['ok']
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)
3
7
17
20
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')
print(in_cart)
print(item)
# check if item only exists in loop
ice cream not in stock
['bananas', 'cookies']
ice cream
# 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)
p
y
t
h
n
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
4.5 % 2
0.5
# WRITE CODE
def sum_odd(input_list):
# initializing a variable
output_sum = 0
# loop through each item/element in input_list
for item in input_list:
if type(item) == int:
if item % 2 != 0: #its odd
# output_sum = output_sum + item
output_sum += item
return output_sum
# TEST FUNCTION
sum_odd(['a', 3, 5, 6])
8
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']
range
, continue
and break
#
Q&A
Q: I am still confused on the different ways that append works with strings versus lists.
A: Ah - great point -append
only works with lists. It’s a list method! If you want to concatenate strings, we use+
Q: When we do loops do we always have to add a period between the codes?
A: I’m not sure which period you meant, but there will always be a colon (:
) at the end of thefor
orwhile
statement. Follow up if this wasn’t what you were asking!
Q: why do we have to include total = 0 at the beginning?
A: In loops we often define/initialize a variable before the loop so that we can update it in the loop. If we didn’t initialize it it wouldn’t exist when we went to update it.
Q: Can you start loops in the middle of a list?
A: You can, but you would specify that in thefor
line….for example:for val in my_list[5:]
would start looping at the fifth index.
Q: how does the term after “”for”” even work? shouldn’t that be a syntax error for it not being defined?
A: I know it feels like it should…but it doesn’t. Python knows that whatever comes after for will take the value of the first thing you’re looping over….and then the second thing…until you reach the end of the collection.
Q: For the shopping budget ‘while loop’ example, what would happen if the prices didn’t add up perfectly to the budget?
A: Love this question! Feel free to adjust the list so that’s the case and see…but once the condition were no longer true the loop would terminate. So….if bill added up to 22 and shopping budget was 20, you could with how the code was written, go “over” budget.
Q: so you just never use return in it?
A: You don’t use return in a loop….unless that loop is in a function
Course Announcements
Due this week:
CL4 due Fri
A3 due Sun
Take your exam!
Notes:
if you were scheduled to take your exam yesterday (Wed) at 4P or 5P, you should have received a message from PrairieTest to reschedule
If you were unable to schedule an oral exam, more times will be released/announced tomorrow for next week
There will be a mid-course survey released tomorrow - try and complete after your exam (if possible)
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 inputname
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
# input is a string ('Shannon')
# loop through each letter in name
# if key not in dictionary yet - make it a key and make value 1
# if it's an S - make S the key and make value 1
# it it's an h - make h the key and make the value 1
# if a - make a key; value 1
# if n - make n key; value 1
# if key already in dictionary, increase value by 1
# for 2nd n - increase value for n key by 1
# output is a dictionary {'S':1, 'h':1, 'a': 1, 'n': 3, 'o': 1}
def name_dictionary(name):
output_dictionary = {}
for ltr in name:
if ltr not in output_dictionary:
output_dictionary[ltr] = 1
elif ltr in output_dictionary:
output_dictionary[ltr] += 1
# output_dictionary[ltr] = output_dictionary[ltr] + 1
return output_dictionary
status1 = True
status2 = False
if status1 and status2:
print('both true')
elif status1 and not status2:
print('status1 true')
elif not status1 and status2:
print('status 2 true')
else:
print('both false')
status1 true
# TEST IT OUT
name_dictionary('Susan')
{'S': 1, 'u': 1, 's': 1, 'a': 1, 'n': 1}
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!')
114
115
116
The tea is too hot!
117
The tea is too hot!
118
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!
Altogether#
It is possible to use these all together…
find_first_even
finds the first even number in arange
if that number is odd,
continue
once you find the first even number
break
numbers = [1, 3, 7, 9, 6, 4, 11, 6, 8]
range(len(numbers))
range(0, 9)
def find_first_even(numbers):
for i in range(len(numbers)):
print(i)
if numbers[i] % 2 != 0:
continue
out = numbers[i]
break
return out
find_first_even(numbers = [1, 3, 7, 9, 6, 4, 11, 6, 8])
0
1
2
3
4
6
Activity: range
, break
, continue
#
Please complete the Google Form here: https://forms.gle/SsRvuJ7XT1zqy7hZA
Define a function
find_all_neg()
that will extract all negative values from a list, returning the list of negative numbers.
You can assume all elements in the input list are numeric.
## FUNCTION
# input a list [3, 4, -5, -19, -23, 6, -100]
# output a list [-5, -19, -23, -100]
def find_all_neg(input_list):
output_list = []
for num in input_list:
if num < 0:
output_list.append(num)
# return output_list
# output_list = output_list + [num]
# output_list += [num]
else:
continue
return output_list
## TEST IT OUT
find_all_neg([-3, 4, -5, -19, -23, 6, -100])
[-3, -5, -19, -23, -100]
Code Style: Loops#
for
/while
statement with a colon at the end on first lineall 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#
Please complete the Google Form here: https://forms.gle/3ZqsNwL8TUNpGbR86
Q1. Define a function
remove_special_characters()
that will remove any characters from a string if they are one of these characters:'!@#$%^&*();<>?/'
# FUNCTION
# input: 'hello!@'
# output: 'hello'
def remove_special_characters(input_string):
output_string = ''
special_char = '!@#$%^&*();<>?/'
for char in input_string:
if char in special_char:
continue
else:
output_string += char
# ouput_string = output_string + char
# else:
# continue
return output_string
# TEST IT OUT
remove_special_characters('hel%^&lo!@')
'hello'