2-3.1 Intro Python

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()

 

Concepts

Iterate through Lists using

for in

view video

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

for city in cities:
    print(city)

 

Examples

In [1]:
# [ ] review and run example
cities = ["New York", "Shanghai", "Munich", "Tokyo", "Dubai", "Mexico City", "São Paulo", "Hyderabad"]

for city in cities:
    print(city)
New York
Shanghai
Munich
Tokyo
Dubai
Mexico City
São Paulo
Hyderabad
In [2]:
# [ ] 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

In [3]:
# [ ] 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

In [4]:
# [ ] create a list of 4 to 6 strings: birds
# print each bird in the list

birds=['Eagle','pigeon','Pelican','Parrot','Crow','Falcon']
for bird in birds:
    print(bird)
Eagle
pigeon
Pelican
Parrot
Crow
Falcon
In [7]:
# [ ]  create a list of 7 integers: player_points
# [ ] print double the points for each point value
player_points = [4,5,7,8,9,4,5,7,8,9,1,0]
for point in player_points:
    print('Double point = ',point," * 2 =", 2*point)
Double point =  4  * 2 = 8
Double point =  5  * 2 = 10
Double point =  7  * 2 = 14
Double point =  8  * 2 = 16
Double point =  9  * 2 = 18
Double point =  4  * 2 = 8
Double point =  5  * 2 = 10
Double point =  7  * 2 = 14
Double point =  8  * 2 = 16
Double point =  9  * 2 = 18
Double point =  1  * 2 = 2
Double point =  0  * 2 = 0
In [9]:
# [ ] create long_string by concatenating the items in the "birds" list previously created
# print long_string - make sure to put a space betweeen the bird names
long_string = ""
for bird in birds:
    long_string += (bird+" ")
print(long_string)
Eagle pigeon Pelican Parrot Crow Falcon 

 

Concepts

Sort and Filter

view video

use comparison operators while iterating lists

 

Examples

In [10]:
# [ ] 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(shorter_names)
print(longer_names)
calcaneus
talus
cuboid
navicular

lateral cuneiform
intermediate cuneiform
medial cuneiform
In [11]:
# [ ] review and run example of sorting into lists
foot_bones = ["calcaneus", "talus", "cuboid", "navicular", "lateral cuneiform", 
            "intermediate cuneiform", "medial cuneiform"]
longer_names_list = []
shorter_names_list = []

for bone_name in foot_bones:
    if len(bone_name) < 10:
        shorter_names_list.append(bone_name)
    else:
        longer_names_list.append(bone_name)

print(shorter_names_list)
print(longer_names_list)
['calcaneus', 'talus', 'cuboid', 'navicular']
['lateral cuneiform', 'intermediate cuneiform', 'medial cuneiform']

 

Task 2

sort and filter

In [14]:
# [ ] Using cities from the example above iterate throught the list using "for"/"in"
# [ ] Print only cities starting with "m"

#Answer:
cities = ["New York", "Shanghai", "Munich", "Tokyo", "Dubai", "Mexico City", "São Paulo", "Hyderabad"]
string_to_compare = "m"
for city in cities:
    if (city[0].lower() == string_to_compare):
        print(city)
Munich
Mexico City
In [15]:
# [ ] Using cities from the example above iterate throught the list using "for"/"in"
# cities = ["New York", "Shanghai", "Munich", "Tokyo", "Dubai", "Mexico City", "São Paulo", "Hyderabad"]
# [ ] sort into lists with "A" in the city name and without "A" in the name: a_city & no_a_city

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

#Answer:
string_to_find='a'
a_city=[]
no_a_city=[]
for city in cities:
    if (city.find(string_to_find)<0):
        no_a_city.append(city)
    else:
        a_city.append(city)
print('a_city: ',a_city)
print('no_a_city: ',no_a_city)
a_city:  ['Shanghai', 'Dubai', 'São Paulo', 'Hyderabad']
no_a_city:  ['New York', 'Munich', 'Tokyo', 'Mexico City']

 

Concepts

More iteration of lists

- Counting

- Searching

view video

use string methods while iterating lists

 

Examples

In [17]:
# [ ] 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 Paulo", "Hyderabad"]
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 "i" found in the list is 5

search function view video

In [20]:
# [ ] 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", "São Paulo", "Hyderabad"]

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: Singapore
Singapore in default cities is False
Singapore in visitied_cites list is False

 

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
In [24]:
# [ ] complete paint stock

#Answer:
paint_colors = ['Red','Green','Blue','Pink','Yellow','Black','White']
color_request = input('Type your requested color: ')
for color in paint_colors:
    if (color.lower() == color_request.lower()):
        print('color is found')
        break
if (color.lower() != color_request.lower()):
    print('color is not found')
Type your requested color: yellow
color is found

 

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 identified

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

In [28]:
# [ ] Complete Foot Bones Quiz
#Answer:
foot_bones = ["calcaneus", "talus", "cuboid", "navicular", "lateral cuneiform",
             "intermediate cuneiform", "medial cuneiform"]

def bone_search(search_bone, foot_bones):
    for bone in foot_bones:
        if bone.lower() == search_bone.lower():
            return True
        else:
            # go to the next item
            pass
    # no more items in list
    return False

correct = 0

while True:
    bone_name = input('Type bone name you want to search')
    if (bone_name.lower() == 'q'):
        break
    if (bone_search(bone_name,foot_bones)):
        print('correct')
        correct += 1
    else:
        print('incorrect')
    
    print('Correct: ', correct)
        
Type bone name you want to searchtalus
correct
Correct:  1
Type bone name you want to searchcuboid
correct
Correct:  2
Type bone name you want to searchtalus
correct
Correct:  3
Type bone name you want to searchtulas
incorrect
Correct:  3
Type bone name you want to searchq
In [29]:
# [ ] bonus version
#Answer:
foot_bones = ["calcaneus", "talus", "cuboid", "navicular", "lateral cuneiform",
             "intermediate cuneiform", "medial cuneiform"]

def bone_search(search_bone, foot_bones):
    for bone in foot_bones:
        if bone.lower() == search_bone.lower():
            return True
        else:
            # go to the next item
            pass
    # no more items in list
    return False

correct = 0

while True:
    bone_name = input('Type bone name you want to search')
    if (bone_name.lower() == 'q'):
        break
    if (bone_search(bone_name,foot_bones)):
        print('correct')
        correct += 1
        foot_bones.remove(bone_name)
    else:
        print('incorrect')
    
    print('Correct: ', correct)
Type bone name you want to searchtalus
correct
Correct:  1
Type bone name you want to searchtalus
incorrect
Correct:  1
Type bone name you want to searchq

Terms of use   Privacy & cookies   © 2017 Microsoft