Night 6: Your pet's favourite snacks
이 페이지는 최신 브라우저(SharedArrayBuffer 지원)가 필요합니다. Chrome, Edge, Firefox 또는 Safari를 최신 버전으로 업데이트해 주세요.
English
Tonight: a list of snacks
- Your pet likes many snacks. One variable for each? Too many!
- You will learn one thing: lists.
Words for tonight
| Word | Meaning |
|---|---|
| list | many values in one variable, in order |
| item | one value in a list |
| position | where an item is; Python starts at 0 |
English
Make a list
- Use square brackets
[ ]. - Put a comma between the items.
snacks = ["apple", "rice", "fish"]
print(snacks)
English
Python counts from 0
| Position | 0 |
1 |
2 |
|---|---|---|---|
| Item | "apple" |
"rice" |
"fish" |
- Write the position in square brackets after the name.
snacks = ["apple", "rice", "fish"]
print(snacks[0])
print(snacks[1])
English
Add and count
.append( )adds a new item at the end.len( )tells you how many items there are.
snacks = ["apple", "rice"]
snacks.append("cake")
print(snacks)
print(len(snacks))
English
Change one item
- Put a new value at a position with
=.
snacks = ["apple", "rice", "fish"]
snacks[0] = "pear"
print(snacks)
- Careful:
snacks[3]gives an IndexError here. There is no position 3.
English
Now you try
- Do the tasks below. Press Run, then Check answer.
- Tomorrow your pet will use this list in a loop.
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
Make a list called snacks with three items: "apple", "rice" 및 "fish", in this order.
출력을 보려면 '실행'을 클릭하세요.
난이도 2/5 · 140코인 + 오늘 첫 완료 시 작은 보너스 추가
Print the 첫 번째 snack, then the 마지막 snack. The output is apple and then fish, on two lines.
출력을 보려면 '실행'을 클릭하세요.
난이도 2/5 · 140코인 + 오늘 첫 완료 시 작은 보너스 추가
Your pet found a new snack. Add "cake" to the end of the list with .append( ). Then print how many snacks there are with len( ). The output is 4.
출력을 보려면 '실행'을 클릭하세요.
난이도 2/5 · 140코인 + 오늘 첫 완료 시 작은 보너스 추가
Your pet does not like rice any more. Change the 초 item to "noodles". Then print the whole list.
출력을 보려면 '실행'을 클릭하세요.