Doing things again and again
Learn how for loops let you repeat code without copy-pasting. Tell Python how many times to repeat and it just does it!
A for loop tells Python to repeat a block of code a certain number of times. Instead of writing print("Hello") ten times, you write a loop that says "do this 10 times." It is cleaner, faster, and way less typing!
π‘ Think of it like this:
Imagine you have to hand out candy to 10 friends. Instead of saying "give candy" 10 times, you say "for each friend, give them candy." The loop handles the repetition for you!
Loops are one of the most powerful tools in programming. They let you process lists, repeat actions, draw patterns, and much more β all with just a few lines of code.
Where you see this in real life:
The word "loop" comes from the idea of a circle β you go around and around until you are done!
A forloop tells Python to repeat a block of code. Instead of writing the same line 10 times, you write it once and tell Python to repeat it!
The simplest for loop uses range()to count. Each time through the loop, the variable changes to the next number.
range(5) counts from 0 to 4 β that is 5 times!π‘ The variable i changes each time: 0, 1, 2, 3, 4
You can also loop through items in a list. The loop variable becomes each item in turn!
Click βΆ Run to see the output!Loops are great for counting! You can add up numbers, count down, or do math with the loop variable.
Click βΆ Run to see the output!Loops can create patterns! Try this triangle maker:
Click βΆ Run to see the output!π‘ Each time through the loop, i gets bigger, so more stars are printed!
What does range(5) produce in a for loop?