For Loops
blue_foods = ['dasheen', 'yam', 'cassava', 'sweet potato']
# The 'in' keyword is used a again
# Read this as "for NEW_TEMPORARY_VARIABLE in LIST_OF_ITEMS"
for blue_food in blue_foods:
print(blue_food)
# On the console you'll see
# dasheen
# yam
# cassava
# sweet potato
# Function that prints a list of numbers after adding 2 to them
def add_two(numbers):
for n in numbers:
print(n + 2)
add_two([1,2,3,4,10]) # 3,4,5,6,12
# Let's do a function that prints out the values of a list of lists
# In this case, we'll nest the for loops to print them out
def print_double_list(double_list):
for dl in double_list:
for dl_item in dl:
print(dl_item)
print_double_list([[1,2],['bob',10,34.0],['c']])
# While Python already has a built in sum function, we can do one too!
def my_sum_1(items):
total = 0
for item in items:
total += item
return total
my_sum_1([1,2,4,5]) # 12Better coding with errors
Exercises
Last updated