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.
In Python, the 'for' loop iterates over a sequence (like a list or a string) or other iterable objects.
for i in range(5): print(i)
0 1 2 3 4
The 'while' loop executes as long as a specified condition is true.
count = 2 while count < 5: print(count) count += 1
2 3 4
'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.
for i in range(5): if i == 3: break print(i)
0 1 2
Copyright © 2023 - slash-root.com