Loops are used in programming to repeat a specific block of code. A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages. With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
Syntax:
for val in sequence:
loop body
Loop continues until we reach the last item in the sequence. The body of for loop is separated from the rest of the code using indentation.
Example:
Program to find the sum of all numbers stored in a list
List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
variable to store the sum
sum = 0
iterate over the list
for val in numbers:
sum = sum+val
print("The sum is", sum)
Output:
The sum is 48