Chapter 4a - Loops and arrays
Arraysβ
Arrays hold ordered values. Index from 0.
var items = ["sword", "shield", "potion"]
print(items[0])
print(items.size())
items.append("key")
π§ͺ Try it
for loopsβ
for x in collection walks each element. range(n) counts 0 .. n-1.
for i in range(3):
print(i)
for name in ["Ada", "Lin"]:
print(name)
π§ͺ Try it
Mini quiz β loopsβ
Loops
1 / 2What does range(3) produce?
Pick an answer to see if you are right.
while loopsβ
var n = 3
while n > 0:
print(n)
n -= 1
π§ͺ Try it
Challenge: sum an arrayβ
Write sum_of(nums) so it returns the total of every number in the array. Use a loop (do not hard-code a single answer).
Indentation
Indent with 4 spaces. Click Reset if an old draft looks flat.
Exercisesβ
Warm up with a countdown, print an inventory list, then find a max in an array.
Activity: Countdown
Print 3, then 2, then 1 (each on its own line) using a loop.
3
2
1