Night 8: Keep playing
Bạn đã hoàn thành đêm này bằng Python hoặc mã giả. Kết quả được tính cho cả hai. Bạn có thể luyện tập lại nếu muốn.
Tonight: keep playing
- Welcome to week 2! This week your pet plays games.
- You will learn one thing: the
whileloop.
Words for tonight
| Word | Meaning |
|---|---|
| while | as long as something is true |
| condition | a question with the answer True or False |
| stop | end; do not go on |
A loop that checks first
- A
forloop knows how many times to run. - A
whileloop does not. It asks a question each time: is the condition still true? - True: run the indented lines again. False: stop.
energy = 3
while energy > 0:
print("Play! Energy:", energy)
energy = energy - 1
print("Time to rest")
Change something inside the loop
- Look at
energy = energy - 1above. It makes the energy smaller each time. - Without this line,
energy > 0is always true. The loop never stops. - A loop that never stops is called an infinite loop. If it happens, press Stop.
Stop when the user says so
- Sometimes you do not know how many times to repeat.
- Here the loop goes on until the user types
stop.
word = input()
while word != "stop":
print("You said", word)
word = input()
print("Bye!")
!=means is not. Read the next word inside the loop.
for or while?
| You know… | Use |
|---|---|
| how many times: 5 stars, each item in a list | for |
only when to stop: until stop, until energy is 0 |
while |
- Now do the tasks. Your pet is ready to play!
Độ khó 2/5 · 140 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Read a number with int(input()). Use a while loop to print the number, then one less, down to 1. Then print Go! once.
Nhấn Chạy để xem kết quả ở đây.
Độ khó 2/5 · 140 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Your pet wants to play. Read a word with input(). While the word is not stop, print the word with ! after it, and read the next word. At the end, print Bye!.
Nhấn Chạy để xem kết quả ở đây.
Độ khó 2/5 · 140 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Your pet has energy = 10. Each jump uses 3 energy. While energy is more than 0, print Jump! and the energy, then take away 3. At the end, print Tired. The first line is Jump! 10.
Nhấn Chạy để xem kết quả ở đây.
Độ khó 3/5 · 200 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Your pet has stars = 1. Every night the stars double. Use a while loop to count the nights until there are 100 stars or more. Print nights. The answer is 7.
Nhấn Chạy để xem kết quả ở đây.