appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Functions, lists and dictionaries

Lesson 3 of 411 minBeginner

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.

1. What does fruits[-1] return for a list?
2. Which keyword sends a value back from a function?
3. How do you read a missing key without an error?
HintA list method that adds at the end.

Key terms