Night 7: Count the stars
Tonight: count the stars
- It is your pet's first week! Tonight it counts the stars.
- You will learn one thing: the
forloop.
Words for tonight
| Word | Meaning |
|---|---|
| loop | do the same thing again and again |
| repeat | do again |
| range | a row of numbers, like 1, 2, 3, 4, 5 |
Repeat without typing again
- Five
printlines is a lot of typing. A loop does it for you. - The indented lines run again for each number.
for n in range(1, 6):
print("Star number", n)
How range counts
| You write | You get |
|---|---|
range(5) |
0 1 2 3 4 |
range(1, 6) |
1 2 3 4 5 |
range(2, 11, 2) |
2 4 6 8 10 |
rangestops before the last number.
Loop through a list
- A
forloop can also walk through a list, one item at a time.
snacks = ["apple", "rice", "fish"]
for snack in snacks:
print("Yum,", snack)
Inside or after the loop?
- Indented lines are inside the loop. They repeat.
- Lines with no indent come after the loop. They run once.
for i in range(3):
print("Zzz")
print("Good night!")
Week 1 is done!
- You know
print, variables,input(), numbers,if, lists and loops. - That is the base of almost every program.
- Finish the tasks below and your pet grows up a stage.
ความยาก 2/5 · 140 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Your pet counts stars. Use a for loop with range to print the numbers 1 ไป 5, one per line.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 2/5 · 140 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Use a for loop to print I like and each snack in the list. The first line is I like apple.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 2/5 · 140 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Read a number with int(input()). Print Zzz that many times, one per line. Then print Good night! once, at the end.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Your pet saw stars on 4 nights: stars = [3, 5, 2, 6]. Use a loop to add them all up in a variable total. Then print total. The output is 16.
คลิก Run เพื่อดูผลลัพธ์ที่นี่