[go: up one dir, main page]

0% found this document useful (0 votes)
22 views11 pages

For in For Loop - Colaboratory

The document provides an overview of using 'for in' loops and 'for range' in Python for iterating through lists and performing operations. It includes examples of iterating through lists of cities and sales, as well as tasks for students to practice list iteration and filtering. Additionally, it covers more advanced concepts such as counting, searching, and string manipulation within lists.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views11 pages

For in For Loop - Colaboratory

The document provides an overview of using 'for in' loops and 'for range' in Python for iterating through lists and performing operations. It includes examples of iterating through lists of cities and sales, as well as tasks for students to practice list iteration and filtering. Additionally, it covers more advanced concepts such as counting, searching, and string manipulation within lists.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

For in for Loop - Colaboratory 11/12/20, 11'05 PM

Section 3.1
The Power of List Iteration
for in: for loop using in
for range: for range(start,stop,step)
More list methods: .extend() , +, .reverse(), .sort()
Strings to lists, .split() , and list to strings, .join()

Student will be able to


Iterate through lists using for with in
Use for range() in looping operations
Use list methods .extend() , +, .reverse(), .sort()
Convert between lists and strings using .split() and .join()

Concept: Iterate through Lists using for in

cities = ["New York", "Shanghai", "Munich", "Tokyo", "Dubai", "Mexico City", "São Pau
lo", "Hyderabad"]

for city in cities:


print(city)

https://colab.research.google.com/drive/1sP6NK4fSNkLMBI5VCD0TK_-fnDXzJPY0 Page 1 of 11
For in for Loop - Colaboratory 11/12/20, 11'05 PM

Examples

# [ ] review and run example


cities = ["New York", "Shanghai", "Munich", "Tokyo", "Dubai", "Mexico City", "São Paul

for city in cities:


print(city)

New York
Shanghai
Munich
Tokyo
Dubai
Mexico City
São Paulo
Hyderabad

# [ ] review and run example


sales = [6, 8, 9, 11, 12, 17, 19, 20, 22]
total = 0

for sale in sales:


total += sale

print("total sales:", total)

total sales: 124

change the iterator variable name from "sale" to "dollars" or to any valid name

https://colab.research.google.com/drive/1sP6NK4fSNkLMBI5VCD0TK_-fnDXzJPY0 Page 2 of 11
For in for Loop - Colaboratory 11/12/20, 11'05 PM

# [ ] review and run example


sales = [6, 8, 9, 11, 12, 17, 19, 20, 22]
total = 0

for dollars in sales:


total += dollars

print("total sales:", total)

total sales: 124

Task 1: Iterate through Lists using in

# [ ] create a list of 4 to 6 strings: birds


# print each bird in the list
birds = ["bluejay","robin","cardnial","cuckoo","toucan","woodpecker"]
for bird in birds:
print(bird)

bluejay
robin
cardnial
cuckoo
toucan
woodpecker

# [ ] create a list of 7 integers: player_points


# [ ] print double the points for each point value
player_points = [12, 15, 13, 14, 10, 5, 22]
for point in player_points:
double = point*2
print(double)

24
30
26
28
20
10
44

https://colab.research.google.com/drive/1sP6NK4fSNkLMBI5VCD0TK_-fnDXzJPY0 Page 3 of 11
For in for Loop - Colaboratory 11/12/20, 11'05 PM

# [ ] create long_string by concatenating the items in the "birds" list previously cre
# print long_string - make sure to put a space betweeen the bird names
long_string = []
for bird in birds:
long_string.append(bird)
print(long_string)

['bluejay', 'robin', 'cardnial', 'cuckoo', 'toucan', 'woodpecker']

Concept: Sort and Filter

use comparison operators while iterating lists

Examples

https://colab.research.google.com/drive/1sP6NK4fSNkLMBI5VCD0TK_-fnDXzJPY0 Page 4 of 11
For in for Loop - Colaboratory 11/12/20, 11'05 PM

# [ ] review and run example of sorting into strings to display


foot_bones = ["calcaneus", "talus", "cuboid", "navicular", "lateral cuneiform",
"intermediate cuneiform", "medial cuneiform"]
longer_names = ""
shorter_names = ""

for bone_name in foot_bones:


if len(bone_name) < 10:
shorter_names += "\n" + bone_name
else:
longer_names += "\n" + bone_name

print("SHORT NAMES: ",shorter_names)


print("\nLONG NAMES: ",longer_names)

SHORT NAMES:
calcaneus
talus
cuboid
navicular

LONG NAMES:
lateral cuneiform
intermediate cuneiform
medial cuneiform

# [ ] review and run example of sorting into lists


foot_bones = ["calcaneus", "talus", "cuboid", "navicular", "lateral cuneiform",
"intermediate cuneiform", "medial cuneiform"]
longer_names = []
shorter_names = []

for bone_name in foot_bones:


if len(bone_name) < 10:
shorter_names.append(bone_name)
else:
longer_names.append(bone_name)

print(shorter_names)
print(longer_names)

['calcaneus', 'talus', 'cuboid', 'navicular']


['lateral cuneiform', 'intermediate cuneiform', 'medial cuneiform']

https://colab.research.google.com/drive/1sP6NK4fSNkLMBI5VCD0TK_-fnDXzJPY0 Page 5 of 11
For in for Loop - Colaboratory 11/12/20, 11'05 PM

Task 2: Sort and Jlter

# [ ] Using cities from the example above iterate throught the list using "for"/"in"
# [ ] Print only cities starting with "m"
cities = ["New York", "Shanghai", "Munich", "Tokyo", "Dubai", "Mexico City", "São Paul
for city in cities:
if city.lower().startswith("m"):
print(city)
else:
pass

Munich
Mexico City

# [ ] Using cities from the example above iterate throught the list using "for"/"in"
# cities = ["New York", "Shanghai", "Munich", "Tokyo", "Dubai", "Mexico City", "São Pa
# [ ] sort into lists with "A" in the city name and without "A" in the name: a_city &
cities = ["New York", "Shanghai", "Munich", "Tokyo", "Dubai", "Mexico City", "São Paul
with_A = []
without_A = []
for city in cities:
if city.startswith("A"):
with_A.append(city)
else:
without_A.append(city)
print("Cities starting with A",with_A)
print("\nCities starting without A",without_A)

Cities starting with A []

Cities starting without A ['New York', 'Shanghai', 'Munich', 'Tokyo', 'Dubai', 'M

https://colab.research.google.com/drive/1sP6NK4fSNkLMBI5VCD0TK_-fnDXzJPY0 Page 6 of 11
For in for Loop - Colaboratory 11/12/20, 11'05 PM

Concept: More List Iteration


- Counting

- Searching

use string methods while iterating lists

Examples

# [ ] review and run example


# iterates the "cities" list, count & sum letter "a" in each city name

cities = ["New York", "Shanghai", "Munich", "Tokyo", "Dubai", "Mexico City", "São Paul
search_letter = "a"
total = 0

for city_name in cities:


total += city_name.lower().count(search_letter)

print("The total # of \"" + search_letter + "\" found in the list is", total)

The total # of "a" found in the list is 6

https://colab.research.google.com/drive/1sP6NK4fSNkLMBI5VCD0TK_-fnDXzJPY0 Page 7 of 11
For in for Loop - Colaboratory 11/12/20, 11'05 PM

Search function

# [ ] review and run example


# city_search function has a default list of cities to search
def city_search(search_item, cities = ["New York", "Shanghai", "Munich", "Tokyo"] ):
for city in cities:
if city.lower() == search_item.lower():
return True
else:
# go to the next item
pass
# no more items in list
return False

# a list of cities
visited_cities = ["New York", "Shanghai", "Munich", "Tokyo", "Dubai", "Mexico City"

search = input("enter a city visited: ")

# Search the default city list


print(search, "in default cities is", city_search(search))

# search the list visited_cities using 2nd argument


print(search, "in visitied_cites list is", city_search(search,visited_cities))

enter a city visited: tokyo


tokyo in default cities is True
tokyo in visitied_cites list is True

https://colab.research.google.com/drive/1sP6NK4fSNkLMBI5VCD0TK_-fnDXzJPY0 Page 8 of 11
For in for Loop - Colaboratory 11/12/20, 11'05 PM

Task 3 (program): Paint Stock


Check a list for a paint color request and print status of color "found"/"not found".

Create list, paint_colors, with 5+ colors


Get user input of string:color_request
Iterate through each color in paint_colors to check for a match with color_request

# [ ] complete paint stock


paint_colors = ["Blue","Red","Green","Yellow","Purple","Orange"]
color_request = input("Which paint color would you like: ")
for color in paint_colors:
if color.capitalize() == color_request:
print("Color found! here is your",color,"paint")
break
else:
print("Not found, out of stock!")

Which paint color would you like: Purple


Not found, out of stock!
Not found, out of stock!
Not found, out of stock!
Not found, out of stock!
Color found! here is your Purple paint

Task 4 (program): Foot Bones Quiz


Create a function that will iterate through foot_bones looking for a match of a string argument

Call the function 2 times with the name of a footbone


print immediate feedback for each answer (correct - incorrect)
print the total # of foot_bones identiJed

The program will use the foot_bones list:

foot_bones = ["calcaneus", "talus", "cuboid", "navicular", "lateral cuneiform",


"intermediate cuneiform", "medial cuneiform"]

Bonus: remove correct response item from list if correct so user cannot answer same item twice

https://colab.research.google.com/drive/1sP6NK4fSNkLMBI5VCD0TK_-fnDXzJPY0 Page 9 of 11
For in for Loop - Colaboratory 11/12/20, 11'05 PM

# [ ] Complete Foot Bones Quiz


# foot_bones = ["calcaneus", "talus", "cuboid", "navicular", "lateral cuneiform",
# "intermediate cuneiform", "medial cuneiform"]

def bones_quiz(bone, foot_bones = ["calcaneus", "talus", "cuboid", "navicular", "later

for bones in foot_bones:


if bone.lower() == bones.lower():
foot_bones.remove(bones.lower())
return "Correct"
return "incorrect"

loop_count = 0
match = 0
while loop_count < 2:
bone_answer = input("Please enter a foot bone that you remember: ")
answer = bones_quiz(bone_answer)
print("Answer: ",answer)
if answer == "Correct":
match += 1
loop_count += 1
print ("Foot bones matched =", match)

Please enter a foot bone that you remember: navicular


Answer: Correct
Please enter a foot bone that you remember: talus
Answer: Correct
Foot bones matched = 2

Terms of use Privacy & cookies © 2017 Microsoft

https://colab.research.google.com/drive/1sP6NK4fSNkLMBI5VCD0TK_-fnDXzJPY0 Page 10 of 11
For in for Loop - Colaboratory 11/12/20, 11'05 PM

https://colab.research.google.com/drive/1sP6NK4fSNkLMBI5VCD0TK_-fnDXzJPY0 Page 11 of 11

You might also like