English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The Python for loop can iterate over items in any sequence, such as a list or a string.
The for loop in Python is used to iterate over sequences (list,tuple,string) or other iterable objects. Iterating over a sequence is called traversal.
for val in sequence: Body of for
Here, val is the variable that gets the value of the item within the sequence in each iteration.
The loop continues until we reach the last item in the sequence. Use indentation to separate the body of the for loop from the rest of the code.
# The program finds the sum of all numbers stored in the list # List of numbers numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11] # Variable used to store the sum sum = 0 # Traverse the list for val in numbers: sum = sum+val print("The sum is", sum)
When you run the program, the output will be:
The sum is 48
We can use the range() function to generate a sequence of numbers. range(10) will produce numbers from9numbers between (10numbers).
We can also define the start, stop, and step as range(start, stop, step_size). If not provided, the step_size defaults to1.
The range object is in a sense 'lazy' because it does not generate all the numbers it 'contains' when we create it. However, it is not an iterator; it supports in, len, and getitem operations.
This function does not store all values in memory; this would be inefficient. Therefore, it remembers the start, stop, and step, and generates the next number on the fly.
To force this function to output all items, you can use the list() function.
The following example will demonstrate this point.
print(range(10)) print(list(range(10)) print(list(range(2, 8)) print(list(range(2, 20, 3))
Output Result
range(0, 10)}} [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [2, 3, 4, 5, 6, 7] [2, 5, 8, 11, 14, 17]
We can use the range() function in the for loop to iterate over a sequence of numbers. It can be combined with the len() function to index and traverse the sequence. Here is an example.
# Program to traverse the list using index genre = ['pop', 'rock', 'jazz'] # Traversing the list using index for i in range(len(genre)): print("I like", genre[i])
When the program is run, the output is:
I like pop I like rock I like jazz
The for loop can also have an optional else block.
If the items in the sequence used in the for loop are exhausted, the else part is executed.
The break keyword can be used to stop the for loop. In this case, the else part will be ignored.
Therefore, if no interruption occurs, the else part of the for loop is executed.
This is an example to illustrate this.
digits = [0, 1, 5] for i in digits: print(i) else: print("No remaining items.")
When the program is run, the output is:
0 1 5 "No remaining items."
Here, the for loop will print the items in the list until the loop is exhausted. When the for loop is exhausted, it executes the else code block and outputs ""No remaining items."
The for...else statement can be used with the break keyword to run the else block only if the break keyword is not executed. Let's take an example:
# Display the program of student's grades in the record student_name = 'Soyuj' marks = {'James': 90, 'Jules': 55, 'Arthur': 77} for student in marks: if student == student_name: print(marks[student]) break else: print('No entry found with this name.')
Output Result
No entry found with this name.