Functions and collections
Reuse logic with functions and model data with lists and dictionaries.
What you will be able to do
- Define functions with defaults
- Iterate over dictionaries
- Use list comprehensions
Functions name a piece of logic. Lists keep order, dictionaries map keys to values. Together they cover most everyday programming.
def average(values):
if not values:
return 0
return sum(values) / len(values)
scores = {"html": 88, "css": 92, "js": 79}
for skill, score in scores.items():
print(f"{skill.upper()}: {score}")
passed = [skill for skill, score in scores.items() if score >= 80]
print(f"Passed: {passed}")
print(f"Average: {average(list(scores.values())):.1f}")- Argument
- A value passed into a function.
- Default
- A parameter value used when the argument is omitted.
- Mutable
- A value that can be changed in place, like a list.
- Comprehension
- A concise expression that builds a collection.
Your turn
MediumFilter the passing scores
Build a list of skill names with a score of 80 or more using a comprehension.
PYTHON · starter
scores = {"html": 88, "css": 72, "js": 91}
# your code hereCheck your understanding before moving on.
Knowledge checkQuestion 1
Which method returns key-value pairs from a dictionary?
Select an answer to continue
Study tools
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.