Today introduces an important step in expanding the complexity of programs that you can write. So far you have only been able to store one value at a time in a variable, and this has limited what we can do. The one exception was our Image Manipulation lab where we read in an entire image of pixels into a single "object" variable. A helpful library did this for you, but you got a taste of what is possible.
A list is an object that stores a sequence of values, allowing you to easily store and alter lots of values at once. Today introduces the list object, its functions, and the special syntax that goes with it.
You should have read this before class.
We will discuss and learn about:
Input any number of words and print them out sorted alphabetically.
# Input words from the user
words = list()
word = input()
while word != "done":
words.append(word)
word = input()
# Sort and print
words.sort()
for word in words:
print(word, end=' ')
print()
This one is a bit longer, so jump right to a working version here to try it out.
# Command tool to add integers to a list.
# Also allows printing the list (dump), counting how
# many times a number appears in the list, and replacing
# all occurrences of an int with another int.
nums = list()
command = input(": ")
while command != "exit":
# add 4
if command.startswith("add"):
num = int(command[4:])
nums.append(num)
# "count 4"
elif command.startswith("count"):
num = int(command[6:])
count = 0
for x in nums:
if x == num:
count = count + 1
print(count)
# "dump"
elif command == "dump":
for num in nums:
print(num, end=' ')
print()
# "change 4 9"
elif command.startswith("change"):
parts = command.split()
old = int(parts[1])
new = int(parts[2])
print("Changing", old, "to", new)
for i in range(len(nums)):
if nums[i] == old:
nums[i] = new
else:
print("Unknown command!")
# Get the next command
command = input(": ")