Lesson 35: Robot commands
Text into actions
- A route can be written as text: short commands like
F400orR90. - The program cuts each command into a letter (what to do) and a number (how far).
- This is string handling: taking text apart and turning it into numbers.
Words for this lesson
| Word | Meaning |
|---|---|
| string | text: a list of characters |
| slice | part of a string, e.g. from position 1 to the end |
| split | cut a string into a list at a separator |
| casting | changing a type, e.g. text "400" to the number 400 |
Cut up one command
| Code | Result |
|---|---|
c = "F400" |
the command |
c[0] |
"F" |
c[1:] |
"400" (text) |
int(c[1:]) |
400 (a number) |
- Python counts from 0: the first character is
c[0].
In the exam
- 0478/23/M/J/24 Q7(a): store a string, use SUBSTRING to take out two words and store them, and output the string in upper case. Mark scheme: assign the string; use SUBSTRING correctly and store the result; use UCASE; output both strings.
- In the exam pseudocode the first character is at position 1; in Python it is at 0. Check which one a question uses.
難易度 4/5 · 280 コイン + 今日初回達成時の小ボーナス
The route is a list of commands. Each command is a letter and a number: F400 means forward 400 mm, B200 back 200 mm, R90 turn right 90°, L90 turn left 90°. The program takes the letter with c[0] and the number with int(c[1:]). Finish it so it obeys all four letters and reaches the green square through the checkpoints.
実行ボタンをクリックして出力を確認してください。
難易度 4/5 · 280 コイン + 今日初回達成時の小ボーナス
Now the route comes as one string: "F400 R90 F300 L90 F500 R90 B200". Split it into a list with text.split(" "), run it as before, and also add up the millimetres driven (F and B) and count the turns (R and L). At the end print Driven: 1400 mm, turns: 3, worked out by the program.
実行ボタンをクリックして出力を確認してください。