Wednesday 9/27¶
Introduction to for
Loops¶
Basics¶
For loops perform the same operation for each element in a collection:
colors = ["red", "blue", "green"]
for c in colors:
print("Color is: ", c)
This will print:
Color is: red
Color is: blue
Color is: green
Finding the Maximum Item¶
One common task is looping through a list to find the maximum item (or the minimimum). This is one way to do it:
def get_max(numbers):
biggest = -float('inf') # Top of the hill
for num in numbers:
if num > biggest:
biggest = num # New king of the hill!
return biggest
Looping by Index¶
Usually our for loops just need to process each element in a list, we don't care about the index of the elements.
Sometimes, we do need to know the index. For example, we might want a
function that returns the position of the maximum element in a list.
In this cases we can use the range
function to generate all of the
necessary index values.
def get_max_index(numbers):
biggest = -float('inf') # Top of the hill
biggest_index = -1 # Invalid placeholder
for i in range(len(numbers)):
if numbers[i] > biggest:
biggest = numbers[i] # New king of the hill!
biggest_index = i
return biggest_index
Quiz Instructions¶
- Log into the desktop as
student
with no password. - Log into Canvas.
- Wait until the instuctor says to start before accessing Part 1.
- The quiz can be found in the "Modules" section of Canvas.
- The entire quiz has a 25 minute time limit.
- Part 1 (Conceptual):
- You may not use Thonny (or any other resources) for Part 1.
- There is a 15 minute time limit for Part 1 (I suggest you don't use that much time!)
- Raise your hand when you complete Part 1, and we will provide the Part 2 instructions.
- Part 2 (Coding):
- You have unlimited submissions.
- You do NOT need to provide docstrings.
- The autograder will NOT check for PEP8 violations (though you should still use good style.)
- You must use Thonny as your editor.
- You may not access any external web pages or other resources.