C. The Variable i Basket
๐ฏ Learning Goals
By the end of this lesson, you'll be able to:
- โ The variable
iUnderstand its role - โ
iUnderstand that it changes on every repetition - โ
iBe able to use it in code
Core Concepts
What is the variable i?
๐งบ Analogy: a number basket
Variable iholds the current number, like a basketIt is!
Every time the carousel spins, a new number goes into the basket.
How i's value changes
| Repeat | i's value |
|---|---|
| 1st | 0 |
| 2nd | 1 |
| 3rd | 2 |
Putting i to use
for i in range(3):
print(f"This is the {i}!")
# Output:
# This is number 0!
# This is number 1!
# This is number 2!
Using it in a game
Result: 5 cubes are placed along the x-axis!
Example Code
from ursina import *
app = Ursina()
# Calculate position using i
for i in range(5):
Entity(
model='cube',
color=color.red,
position=(i * 2, 0, 0) # Positions 0, 2, 4, 6, 8
)
EditorCamera()
app.run()
What Happens
5 cubes are placed at even intervals!
Quiz
Quiz: Number of repetitions
for i in range(8)how many times does it repeat?
Show Answer
Answer: 8
for i in range(8)repeats 8 times total, from 0 to 7.
range(n)always repeats n times!
Variable i practice:
- The variable that holds the current number:
forin range(5): - Calculate i times 2:
position = i * - i's last value when range(4):
๐ง Debug Clinic
Problem: every object is created at the same position
โ Wrong Code
Cause:iwasn't used in the position calculation
โ Correct Code
Fix:iUse it to calculate the position!
Try Coding It Yourself
Take what you learned with the blocks and write it yourself in Python code!
Printing i's value
Check how the variable i changes on each repetition.
Example Answer
Result: i is printed as it changes from 0 to 4!
Using i in calculations
Use the variable i to calculate positions!
๐ฏ Fill-in-the-Blank Mission
Fill in the blanks to complete the code!
๐งฉ Key Takeaways
What you learned in this lesson:
| Concept | Description |
|---|---|
| Variable i | a basket that holds the current loop number |
| How the value changes | A new number goes in on each repetition |
| How to use it | Used to calculate position, size, etc. |
Review Checklist
- [ ] The variable
ican you explain what it holds? - [ ]
iCan you use it to give objects different positions? - [ ]
for i in range(5)iniDo you know what values it takes?