Imagine you want to print the numbers from 1 to 100. Would you write print() one hundred times? Of course not. Python has a better way. It is called a loop. A loop repeats the same code again and again, so you write it only once. In this guide, you will learn the for loop and the while loop with simple examples. If you did not read the last lesson yet, start with Python Conditions: if, elif and else, because we will use if a little in this post.
- What a loop is and why we need it
- How to use
forwithrange() - How to use a
whileloop - How to stop a loop with
breakand skip a turn withcontinue - How to avoid an endless loop
What Is a Loop?
A loop runs the same lines of code many times. Each time the code runs once, we call it one turn (or one iteration). Python has two kinds of loops:
forloop: use it when you know how many times to repeat.whileloop: use it when you want to repeat until something changes.
Step 1: Your First for Loop
- Open VS Code and open your python-practice folder.
- Click the New File icon and name the file
loop.py. - Type the code below.
- Press
Ctrl + Sto save the file. - Click the triangle (Play) button at the top right to run it.
for number in range(1, 6):
print(number)
print("Loop finished")
You should see this output:
1
2
3
4
5
Loop finished
Let us read the first line slowly. for number in range(1, 6): means "take the numbers from 1 to 5, one by one, and call each one number". The line with 4 spaces runs once for every number. The last print has no spaces at the start, so it is outside the loop and runs only one time.
Just like if, the for line ends with a colon : and the lines inside the loop need 4 spaces.
Step 2: Understand range()
range() makes a list of numbers for the loop. You can give it one, two or three values:
for i in range(5):
print(i)
You should see this output:
0
1
2
3
4
With one value, Python starts from 0 and stops before that value. So range(5) gives five numbers, but the last one is 4, not 5.
range(5)gives 0, 1, 2, 3, 4range(1, 6)gives 1, 2, 3, 4, 5 (start, stop)range(2, 10, 2)gives 2, 4, 6, 8 (start, stop, step)range(5, 0, -1)gives 5, 4, 3, 2, 1 (counting down)
range(1, 11).Step 3: Loop Through Text and Add Numbers
A for loop can also go through the letters of a text, one letter at a time:
for letter in "Cat":
print(letter)
You should see this output:
C
a
t
Loops are also great for adding numbers. Here we keep a variable called total, and add one number to it in every turn:
total = 0
for number in range(1, 6):
total = total + number
print(total)
You should see this output:
15
The total starts at 0. Then it becomes 1, then 3, then 6, then 10, and at the end 15. Notice that print(total) is outside the loop, so it shows only the final answer.
Step 4: The while Loop
A while loop keeps running as long as its condition is True. It uses the same conditions you learned in the last lesson.
count = 1
while count <= 3:
print("Count is", count)
count = count + 1
print("Done")
You should see this output:
Count is 1
Count is 2
Count is 3
Done
Here is what happens. Python checks count <= 3. It is True, so it runs the lines inside. Then count becomes 2, and Python checks again. This goes on until count becomes 4. Now the condition is False, so the loop stops.
while loop. If you forget the line count = count + 1, the condition is always True and the loop never stops. This is called an endless loop. If it happens, click inside the terminal and press Ctrl + C to stop it.Step 5: break and continue
Sometimes you want to change how a loop runs. Python gives you two small tools:
breakstops the whole loop right now.continueskips the rest of this turn and goes to the next turn.
for number in range(1, 10):
if number == 5:
break
print(number)
You should see this output:
1
2
3
4
When number becomes 5, Python runs break and leaves the loop. Now look at continue:
for number in range(1, 6):
if number == 3:
continue
print(number)
You should see this output:
1
2
4
5
The number 3 is missing. Python skipped the print for that turn, but the loop did not stop.
Step 6: Practice Program
Let us make a multiplication table. Create a new file named table.py and type this:
number = int(input("Enter a number: "))
for i in range(1, 11):
print(f"{number} x {i} = {number * i}")
If you type 5, you will see this output (first lines):
Enter a number: 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
...
Here we used input(), int(), an f-string and a loop together. Run it again with other numbers like 7 and 12.
Common Errors and How to Fix Them
Error 1: IndentationError: expected an indented block
You forgot the spaces under the loop:
for i in range(3):
print(i)
Add 4 spaces before print:
for i in range(3):
print(i)
Error 2: SyntaxError: expected ':'
You forgot the colon at the end of the for or while line. Write for i in range(3):, not for i in range(3).
Error 3: TypeError: 'str' object cannot be interpreted as an integer
You gave text to range(). Remember that input() always gives text. Change it into a number first:
n = int(input("How many times? "))
for i in range(n):
print("Hello")
Error 4: The program never stops
This is an endless while loop. The condition never becomes False. Check that the variable in the condition changes inside the loop, and press Ctrl + C in the terminal to stop the program.
Common Mistakes Beginners Make
- Forgetting that range() stops early.
range(1, 5)gives 1, 2, 3, 4. It does not give 5. - Forgetting the colon. Both
forandwhilelines end with:. - Forgetting the indentation. The lines inside the loop need 4 spaces.
- Not changing the counter in a while loop. This makes an endless loop.
- Putting print inside the loop by mistake. If you want only the final answer, keep
printoutside the loop. - Using range() with input() text. Use
int()first.
Practice Time
Try these small tasks on your own. Click a question to open the code box, write your Python code and press Run. If your code is correct, you will see a green message. If there is an error, you will see the error, the line number and a tip to fix it.
- Print the numbers 1 to 5 with a
forloop. - Add the numbers from 1 to 10.
- Print a multiplication table.
- Count down with a
whileloop.
What to Learn Next
Now your programs can make decisions and repeat tasks. The next step is lists. A list lets you keep many values in one variable, like a list of names or marks, and loops work with lists very nicely. In the next post, we will learn lists with simple examples. If you missed the full learning plan, read my Python roadmap for beginners.
Frequently Asked Questions (FAQs)
What is the difference between a for loop and a while loop?
Use a for loop when you know how many times to repeat, like "print 10 times". Use a while loop when you repeat until a condition changes, like "keep asking until the password is correct".
Why does range(5) not include 5?
Because range() starts from 0 and stops before the number you give. So range(5) gives 0, 1, 2, 3, 4. That is still five numbers. If you want to reach 5, write range(1, 6).
How do I stop an endless loop?
Click inside the VS Code terminal and press Ctrl + C. After that, check your while loop and make sure the variable in the condition changes inside the loop.
Can I put a loop inside another loop?
Yes. This is called a nested loop. It is a bit harder, so first practice the simple loops from this post. We will see nested loops in a later lesson.
Final Thoughts
Loops save a lot of time. Remember the three big ideas: for is best when you know the number of turns, while runs until its condition is False, and break and continue give you more control. Practice a little every day, and try to change the numbers in the examples to see what happens.

.png)
.png)
Comments
Post a Comment