Python Fundamentals: Basic Loops - 'for' and 'while'
Looping is a fundamental concept in programming, allowing you to execute a block of code multiple times. Python provides several loop mechanisms, the most common being the 'for' and 'while' loops.
a. The 'for' loop:
In Python, the 'for' loop iterates over a sequence (like a list or a string) or other iterable objects.
Code
for i in range(5): print(i)
Output
0 1 2 3 4
b. The 'while' loop:
The 'while' loop executes as long as a specified condition is true.
Code
count = 2 while count < 5: print(count) count += 1
Output
2 3 4
c. The 'break' and 'continue' statements:
'break' is used to exit a loop prematurely, while 'continue' skips the current iteration and moves to the next one. The range(5) function generates a sequence of numbers from 0 up to, but not including, 5, which our loop then iterates over.
Code
for i in range(5): if i == 3: break print(i)
Output
0 1 2