Introduction to Simple Loops
Loops in programming allow us to execute a block of code multiple times. They are an essential component of any programming language, and Python is no exception. In Python, there are two types of loops: for loops and while loops.
For Loops
A for loop is used when you want to execute a block of code a set number of times. It iterates over a sequence such as a list, tuple, string, or a range object.
for i in range(5):
print(i)
The above code will print numbers from 0 to 4. The range() function generates a sequence of numbers starting from 0 by default, and stops before a specified number.
While Loops
A while loop allows you to execute a block of code as long as a certain condition remains true.
count = 0
while (count < 5):
print(count)
count += 1
Here, the loop will keep running and printing the value of count until it becomes equal to or greater than 5.
Control Statements in Loops
Control statements change the execution from its normal sequence. In Python, such statements are break, continue, and pass.
for i in range(5):
if i == 3:
break
print(i)
The break statement ends the loop prematurely when it encounters a condition. In the above example, the loop stops running when the value of i is equal to 3.
Conclusion
In Python, we use loops to repeatedly execute a block of code. For loops iterate over a sequence for a specific amount of times while while loops continue executing as long as a certain condition is satisfied. Control statements like break, continue, and pass help alter the flow of loops. Understanding these fundamental concepts is key to mastering Python.