A. What is a Loop (For Loop)?
๐ฏ Learning Goals
By the end of this lesson, you'll be able to:
- โ
forUnderstand what a loop is - โ Understand why we use loops
- โ Understand the basic structure of a loop
Core Concepts
What is a loop?
Loopsis a way to run the same code multiple times.
๐ Analogy: a carousel
Just like a carouselLike this, it spins a set number of times, repeating the same thing!
Why do we use loops?
# โ Without a loop (inefficient)
print("Hi!")
print("Hi!")
print("Hi!")
# โ
Using a loop (efficient)
for i in range(3):
print("Hi!")
Advantage: - Code is short and clean - Easy to edit - Prevents mistakes
for syntax
| Element | Role |
|---|---|
for |
loop-start keyword |
i |
the variable that holds the current number |
in |
the connecting word meaning "from" |
range(count) |
creates a bundle of numbers |
: |
the signal that the loop body begins |
๐ Visualization: the feel of a for loop โrepeating automaticallyโ
If loops are hard to grasp just in your head, it helps to check out the demo below first.
- The hard way (No Loop): To deliver to 5 houses, you'd have to write the
go_to_house(10),go_to_house(11)โฆ command 5 times, like this. - The smart way (For Loop):
for i in houses:If you write it like this, Variableiautomatically changes to the house number while repeating the same command. (In the demo,ichanges like a sticky note!)
Example Code
from ursina import *
app = Ursina()
# Repeat 3 times to make cubes
for i in range(3):
Entity(model='cube', position=(i*2, 0, 0))
app.run()
What Happens
Three cubes appear in a row!
Quiz
for loop syntax practice:
- Loop start:
i in range(3): - Create a bundle of numbers:
for i in(5): - Loop-start signal:
for i in range(3)
๐ง Debug Clinic
Problem: I'm getting a SyntaxError!
โ Wrong Code
Error message:SyntaxError: expected ':'
Cause: for At the end of the statement, a colon (:) is missing
โ Correct Code
Fix:for At the end of the statement, a colon (:)!
Try Coding It Yourself
Take what you learned with the blocks and write it yourself in Python code!
Using a for loop
for i in range(3):Try repeating 3 times with this.
Try changing the number of repetitions
Change the number inside range() to repeat a different number of times!
๐ฏ Fill-in-the-Blank Mission
Fill in the blanks to complete the code!
๐งฉ Key Takeaways
What you learned in this lesson:
| Concept | Description |
|---|---|
| for | the keyword that starts a loop |
| i | the variable that holds the current loop number |
| range(n) | creates a bundle of numbers to repeat n times |
| Colon (:) | the signal that the loop body begins |
Review Checklist
- [ ]
forCan you explain what a loop is? - [ ] Do you know what advantages using a loop gives you?
- [ ]
for i in range(3):Do you know why a colon is needed after it?