This guide is written for complete beginners who are encountering loops for the first time.
As a beginner introduced to loops for the first time, you'll find them confusing at first. What is a loop? How should I use it? And is it necessary?.... You'll end up with a lot of questions but not an ideal solution, and this is the last explanation you need to know about loops.
Loops are blocks of code that repeat automatically to execute the same expressions until a specified condition is met.
If you want to execute a code a million times, you should use a loop instead of writing the code a million times. They save time, reduce errors, and make code much cleaner.
You’ll find loops in almost every programming language you'll work with in the future ( such as JavaScript, TypeScript, Python, C#...). There are different types and different ways to implement a loop, but we can distinguish two major types:
For loop: A for loop runs a specific number of times. Here is how to write a For loop using Python:
for variable in iterable:
# Code to execute for each item
While loop: A while loop keeps running until a condition is no longer true. Here is how to write a While loop using Python:
count = 0
while count < 5:
print(f"Iteration: {count}")
count += 1 # Important: update the variable to eventually break the loop
The following examples show when you should use loops:
- When you try to find an item among a lot of items.
- When you try to compare different items.
- When you want to apply the same change to a lot of items.
Loops are one of the first tools that make you feel like a real programmer. Once you understand them, you'll see them everywhere — and wonder how you ever coded without them.
Top comments (0)