Loops are very used in programing when is necesary repeat a instruction x times. Some examples : search a number in a list or wait for a specific input.
In python the most important loop is "while", while a condition is met then the block of code inside of itself continue executing.
Syntax
example_number = 0
while example_number < 3 :
print(example_number)
example_number = example_number + 1
output :
0
1
2
Useful when we dont know the exact number of iterations. If we have the number of iterations defined then "for" is better than while loop.
Example : count odd numbers in a list
for i in range (5):
if i % 2 != 0:
print(i)
output :
1
3
Also exist "for each" with this loop is possible iterate in a list and the iterator will be each element.
Example: print each element of a list
example_list = ['house', 'apple', 1]
for element in example_list:
print(element)
output :
house
apple
1
Top comments (0)