Skip to main content

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​

Quiz

Loops

1 / 2

What 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