Functions, lists and dictionaries
Reuse code and store groups of values.
Functions
def greet(name, punctuation="!"):
return f"Hello, {name}{punctuation}"
print(greet("Ana")) # Hello, Ana!
print(greet("Bob", ".")) # Hello, Bob.A function groups code under a name. It takes parameters and can send a result back with return. A parameter with = has a default value.
Lists
fruits = ["apple", "pear"]
fruits.append("plum") # add to the end
print(fruits[0]) # apple (counting starts at 0)
print(fruits[-1]) # plum (last item)
print(len(fruits)) # 3
for f in fruits:
print(f)Dictionaries
user = {"name": "Ana", "age": 31}
print(user["name"]) # Ana
user["country"] = "ES" # add a key
print(user.get("phone", "n/a")) # n/a (safe lookup with default)
for key, value in user.items():
print(key, value)List comprehensions
squares = [n * n for n in range(5)] # [0, 1, 4, 9, 16]
evens = [n for n in range(10) if n % 2 == 0]NoteReading a missing key with user["phone"] raises a KeyError. Use .get() when the key may not exist.
Test yourself
Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.