For loop (for)
Both for loops and while loops can achieve the same results. However, a while loop is more flexible because its condition can be fully customised, whereas a for loop is more structured and is typically used for iterating over a sequence.
So, theorically for loop is not suitable for infite looping as the data sets will never be infinty
Usage
for n in x
... handle task (can based on n)...forandinis the keywords.- x is Sequence Type (List, Tuple, Str)
Example
for-loop.py
py
text = str("HelloWorld")
for i in text:
print(i)Results:
H
e
l
l
o
W
o
r
l
dFind number of "o" in the text of "HelloWorld" using for loop.
py
# text = "HelloWorld"
number_of_o = int(0)
for i in text:
if i == "o":
number_of_o += 1
print(f"Text - {text} has {number_of_o} o.")Results:
Text - HelloWorld has 2 o.