While loops:
The loop will execute all the code until it becomes false, or in other words, exceeds the limit so that the code doesn’t do infinite loops. You have to tell the program to stop somehow.
Counter = 0
While counter < 11:
print(counter)
Counter += 1
The above code will print 0 down to 10
For loops:
The loop allows to repeat a code several times depending on how much we apply
for intNumber in range(1,10):
If intNumber == 6:
break
print(intNumber)
Breaking out of a loop:
The loop breaks before continuing and forgets the rest of the incoming code if something is true.
for intNumber in range(1,10):
If intNumber == 6:
break
print(intNumber)
The continue statement:
The current loop is being processed, which will be continued to an extent to what the applied code limits. The code after the continue statement, which is also in the same loop phase, will be ignored once something is true.
for i in range(10):
if i % 2 == 0:
continue # Skip even numbers
print(i)
# Only odd numbers will be printed
Can be used to skip a specific item in a loop. Can be used to prevent errors.
Optimizing loops:
Stopping a loop before it continues. Like trying to find a specific value within a list of numbers that stops automatically when it finds it without having the program continue the rest of the records.
target_value = 42
numbers = [1, 5, 8, 12, 42, 67, 89, 102]
for num in numbers:
if num == target_value:
print (f”Found {target_value}!”)
break #Exit the loop early
else:
continue