Collections, decisions and loops
1 / 9Collections, decisions and loops
Real programs handle many values, choose what to do, and repeat work.
Collections hold the values. if makes the choice. for and while do the repeating.
In this topic
Lists
A shopping list: items in order, and you can add, change and cross things off.
fruits = ["apple", "pear", "plum"]
Square brackets, items separated by commas.
fruits[0] is "apple". fruits[-1] is the last item, "plum".
fruits.append("fig")adds to the endfruits[1] = "kiwi"replaces an itemfruits.remove("apple")takes one out
fruits[0:2] gives the first two items. The end position is not included.
len(fruits) tells how many items there are. It works on every collection, and on strings too.
Dictionaries
A phone book: you look things up by name, not by position.
ages = {"Ada": 36, "Alan": 41}
Curly braces, with key: value pairs.
ages["Ada"] gives 36. A key that is missing raises a KeyError.
ages["Grace"] = 45 adds a new pair, or replaces the value if the key is already there.
"Ada" in ages answers True or False. The same in works on lists.
Tuples and sets
Two specialists: a sealed packet that cannot change, and a bag where every item is unique.
point = (3, 4)
Like a list, but fixed once made. Good for values that belong together.
x, y = point gives each part its own name in one line.
colours = {"red", "blue", "red"} keeps only "red" and "blue". No duplicates, no order.
- order matters and it changes: list
- look up by name: dictionary
- fixed group: tuple
- only unique items: set
Decisions
A fork in the road: the program asks a yes-or-no question and takes one of the paths.
if age >= 18:
print("adult")
The indented lines run only when the answer is True.
if age >= 18:
print("adult")
elif age >= 13:
print("teenager")
else:
print("child")
Only the first branch that fits is taken.
== equal, != not equal, <, >, <=, >=.
One = gives a name. Two == ask a question.
Join questions in plain words.
if age >= 18 and has_ticket:
An empty list, an empty string, 0 and None all count as False. So if fruits: asks "is there anything in the list?"
for loops
A conveyor belt: every item of a collection passes by once, and you do the same thing to each.
for fruit in fruits:
print(fruit)
for i in range(5): repeats five times, with i going from 0 to 4.
for name, age in ages.items():
print(name, age)
A loop that builds a new list in one line.
doubled = [n * 2 for n in numbers]
while loops
A roundabout: keep going round until a condition tells you to take the exit.
while lives > 0:
play_round()
The condition is checked before every round.
for when you know what to go through. while when you only know when to stop.
Leaves the loop at once.
Skips the rest of this round and starts the next one.
If the condition never becomes False, the loop never ends. Press Ctrl+C to stop the program.
Try it
Reading is not doing. Three small tasks: type them yourself instead of copying, and run each one.
Make a list of five things. Print the first one, the last one and how many there are. Add a sixth, then print them all with a for loop.
Put three names and numbers into a dictionary. Ask the user for a name. Print the number, or not found if the name is missing. Use in and if/else.
Store a secret number. In a while loop, ask for a guess and answer too high or too low. Leave the loop with break when the guess is right.