for val in sequence: loop body
Python for in loop
Simple example code where for loop does not require an indexing variable to set beforehand. Let’s write the Program to find the sum of all numbers stored in a list.
# List of numbers numbers = [1, 2, 3, 8, 4, 2, 5, 4] sum = 0 # iterate over the list for val in numbers: sum = sum + val print("The sum is", sum)
fruits = ["apple", "banana", "cherry"] for x in fruits: print(x)
Looping Through a String
for x in "Hello": print(x)
With the break statement you can stop the loop before it has looped through all the items:
fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) if x == "banana": break
Do comment if you have any doubts or suggestions on this Python loop topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.