Python lesson 10

Combining Concepts

Put it all together. Variables, strings, loops, lists, and functions!

Everything Together

You have learned print, variables, strings, if/else, for loops, lists, and functions. Now combine them! A function can take a list, loop through it, and do something useful with each item.

def shout_all(items):
for item in items:
print(item.upper())

shout_all(["hello", "world"])

def shout_all(items):
    for item in items:
        print(item.upper())

shout_all(["hello", "world"])

Three Ideas At Once

def shout(word):
    return word.upper() + "!"

words = ["go", "win"]
for word in words:
    print(shout(word))

Function + Loop + List

Click Run to see a function that receives a list and loops through every item!

Hint: Click Run! The function takes a list and prints each item using a loop.

def print_all(items):
    for item in items:
        print(item)

fruits = ["apple", "banana", "mango"]
print_all(fruits)

Loop + If

Run this to print only names that start with "A". Then add more names to the list!

Hint: name[0] gets the first letter. Add more names and see which ones start with A!

names = ["Alice", "Bob", "Anna", "Charlie"]
for name in names:
    if name[0] == "A":
        print(name)

Mini Program

Run this mini program that uses functions, loops, and lists together!

Hint: Change the names and scores, then run again. Range(len(names)) gives one index per name!

def show_scores(names, scores):
    for i in range(len(names)):
        print(names[i], "scored", scores[i])

names = ["Alice", "Bob", "Charlie"]
scores = [90, 85, 92]
show_scores(names, scores)

What you can do on CodeIt

Run the example, change one part, and use the result to check your understanding before moving to the next lesson.