Skip to content

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

for i in range(3):
    print(i)
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

for i in range(5):
    Entity(
        model='cube',
        position=(i * 2, 0, 0)  # Calculate position with i!
    )

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: for in 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

for i in range(5):
    Entity(model='cube', position=(0, 0, 0))  # All at (0,0,0)!
Cause: iwasn't used in the position calculation

โœ… Correct Code

for i in range(5):
    Entity(model='cube', position=(i * 2, 0, 0))  # Positions 0, 2, 4, 6, 8
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
for i in range(5):
    print(f'Current i = {i}')

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!

Check answers
for i in range(4):
    print(f'Current number: {i}')
Check answers
for i in range(5):
    result = i * 3
    print(f'{i} x 3 = {result}')

๐Ÿงฉ 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)in iDo you know what values it takes?