Lesson 3 of 38 · Written learning
Python data and control flow
Use variables, collections, conditions, and loops to express a small program.
A variable gives a name to a value. Common values include integers, decimal numbers, strings, and Booleans. Lists keep an ordered sequence; dictionaries associate keys with values. A document-processing program might keep tokens in a list and count them in a dictionary.
Make the program follow the data
Conditions choose between paths, and loops repeat work. For example, a loop can visit each word, normalize it, then increment its count. Functions give a name to a reusable operation. Keep functions small enough that their input, output, and side effects are easy to describe.
tokens = ["model", "learns", "patterns", "model"]
counts = {}
for token in tokens:
counts[token] = counts.get(token, 0) + 1
print(counts)- Use a list when order matters and duplicates are meaningful.
- Use a dictionary when you need to look up a value by a key.
- Use explicit names such as `token_count` rather than unexplained abbreviations.
- Test a function with an empty input and an ordinary input; edge cases reveal assumptions.
Return to the Python and software foundations stage · Suggested timing is flexible; move at your own pace.