Overview containers: REVIEW THIS!
Name | Create empty | Operators | Important methods |
---|---|---|---|
List | [] or list() | [i], in, +, * | append, count, index, insert, pop, remove |
Tuple | () or tuple() | [i], in, +, * | count, index |
Set | set() only | in | add, pop, remove |
Dict | {} or dict() | [k], in | get, items, pop |
For loops and dictionary: REVIEW THIS!¶
def dict_example(some_dict):
for key, value in some_dict.items():
print(key, "->", value)
dict_example({"color": "blue", "fruit": "apple", "pet": "dog"})
dict_example({1234:"Sharon", 3450:"Ann", 6901:"Robert"})
¶
def dict_example(some_dict):
for key, value in some_dict.items():
print(key, "->", value)
dict_example({"color": "blue", "fruit": "apple", "pet": "dog"})
dict_example({1234:"Sharon", 3450:"Ann", 6901:"Robert"})
Number of iterations¶
# Iterating some determined amount of times using a loop variable
count = 1
while count < limit:
# Loop body statements go here
count += 1
for count in range(1, limit)
# Loop body
Review of for loops:¶
predict the behavior
# Problem 1
for row in range(10):
print(row, end="\t")
print("#" * row)
#Problem 2
cities = ["boise", "omaha", "tulsa", "utica"]
result = []
for city in cities:
result.append(city.upper())
print(result)
# Problem 3
word = "onomatopoeia"
locs = []
for i in range(len(word)):
if word[i] in ('a', 'e', 'i', 'o', 'u'):
locs.append(i)
print("Locations:", locs)
Another for loop¶
Notice split()
name = "James Madison University"
words = name.split()
acronym = ""
for word in words:
letter = word[0]
print(letter, "is for", word)
acronym += letter
print(acronym)
Go to exercises on the web page¶
def get_short(words):
short = []
for word in words:
if len(word) <= 5:
short.append(word)
return short
print(get_short(["hello", "goodbye", "hi", "another", "day"]))
¶
def get_short(words):
short = []
for word in words:
if len(word) <= 5:
short.append(word)
return short
print(get_short(["hello", "goodbye", "hi", "another", "day"]))
Thonny debugger¶
n = int(input("Enter a positive integer: "))
while n != 1:
print(n)
if n % 2 == 0:
n = n // 2
else:
n = 3*n + 1
print("n is now 1!")
¶
n = int(input("Enter a positive integer: "))
while n != 1:
print(n)
if n % 2 == 0:
n = n // 2
else:
n = 3*n + 1
print("n is now 1!")
While Loops¶
- how are while loops different from for loops?
- fixed number of times?
- infinite loop
- boolean expression never evaluates to false
- some execution must occur in the loop body to cause evalution to false
For loop¶
for
is a keyword- iterates
- iterables
- list, tuple, set, dictionary, string
- body of the
for
loop, executed for each iteration
VA_birds = ["mockingbird", "robin", "woodpecker", "cardinal"]
for birdtype in VA_birds:
print(f'{birdtype} can be found in Virginia')
¶
VA_birds = ["mockingbird", "robin", "woodpecker", "cardinal"]
for birdtype in VA_birds:
print(f'{birdtype} can be found in Virginia')
Body of the for loop¶
sum = 0
grades = [75, 81, 65, 83, 88]
for grade in grades:
sum += grade
average = sum/len(grades)
print(f'Your average is {average}')
¶
sum = 0
grades = [75, 81, 65, 83, 88]
for grade in grades:
sum += grade
average = sum/len(grades)
print(f'Your average is {average}')
range()¶
- generates a sequence of integers
- range object that is immutable
- three values
- starting integer, default 0
- ending integer, integers generated up to but not include ending
- integer step value, default 1
range(4)
range(10, 20)
range(100, 10000, 50)
range(10, 0)
for loop with range()¶
year_started = int(input("enter the year you started at JMU: "))
print("My four years at JMU")
for year in range(year_started, year_started + 4):
print(year)
¶
year_started = int(input("enter the year you started at JMU: "))
print("My four years at JMU")
for year in range(year_started, year_started + 4):
print(year)
checkpoint 1¶
- write a python for loop to print all the numbers from 1 to 105 that are evenly divisible by 3 and not even¶
for num in range (1, 106):
if num % 3 == 0 and num % 2:
print(num)
¶
for num in range (1, 106):
if num % 3 == 0 and num % 2:
print(num)
for
loops and dictionaries¶
calories = {'apple': 72,
'bagel': 290,
'chicken breast' : 150,
'ice cream' : 160
}
for food_item in calories:
print(f'{food_item} has {calories[food_item]} calories')
# same results
for food_item, number in calories.items():
print(f'{food_item} has {number} calories')
¶
calories = {'apple': 72,
'bagel': 290,
'chicken breast' : 150,
'ice cream' : 160
}
for food_item in calories:
print(f'{food_item} has {calories[food_item]} calories')
# same results
for food_item, number in calories.items():
print(f'{food_item} has {number} calories')
enumerate¶
- iterate through a sequence
- index and corresponding element
- combination
range()
andlen()
- then index into the sequence for value
enumerate()
function- pass an iterable (string, list, tuple, set, dictionary)
- returns an enumerate object
- adds a counter index to each corresponding element value
Checkpoint 2: try these¶
names = ['Bob', 'Sally', 'John', 'Nathan']
enumerate_info = enumerate(names)
print(names)
print(list(enumerate_info))
enumerate()
yields a new tuple each itertion of the loopnames = ['Bob', 'Sally', 'John', 'Nathan'] for who in enumerate(names): print(who)
enumrate()
- returns a tuple
- can be unpacked into two variables
names = ['Bob', 'Sally', 'John', 'Nathan'] for order, who in enumerate(names): print(order, who)
Recap of for
loops¶
Code | Meaning |
---|---|
for value in my_list: |
for each value in a list |
for index in range(len(my_list)): |
for each index in a list |
for index, value in enumerate(my_list): |
for each index and value |
for key in my_dict: |
for each key in a dict |
for key, value in my_dict.items(): |
For each key and value |
Other Concepts in this chapter¶
- incremental programming
- function stubs
pass
- keyword function arguments
- default parameter values
For Loops with sets¶
def all_pairs(sentence):
"""Return a set containing all neighboring pairs of letters.
Args:
sentence (string): Any string
Returns:
set: A set containing all unique pairs of neighboring letters.
"""
all_pairs = set()
for i in range(len(sentence) - 1): # Stop one index *before* the end.
letter = sentence[i]
next_letter = sentence[i + 1]
all_pairs.add(letter + next_letter)
return all_pairs
print(all_pairs("abbbbcbcbcab"))
{'bc', 'ca', 'cb', 'ab', 'bb'}