Python for Loop Statement

Python for loops can iterate over items of any sequence, such as a list or a string.

Syntax:

The syntax format of the for loop is as follows:

for iterating_var in sequence:
   statements(s)

Flowchart:

Example:

Examples

#!/usr/bin/python # -*- coding: UTF-8 -*- for letter in 'Python': # First example print("Current letter: %s" % letter) fruits = ['banana', 'apple', 'mango'] for fruit in fruits: # Second example print ('Current fruit: %s'% fruit) print ("Good bye!")

Try it yourself »

The output of the above example is:

当前字母: P
当前字母: y
当前字母: t
当前字母: h
当前字母: o
当前字母: n
当前水果: banana
当前水果: apple
当前水果: mango
Good bye!


Iterating by Sequence Index

Another way to perform loop traversal is by index, as in the following example:

Example

#!/usr/bin/python # -*- coding: UTF-8 -*- fruits = ['banana', 'apple', 'mango'] for index in range(len(fruits)): print ('Current fruit : %s' % fruits[index]) print ("Good bye!")

The output of the above example is:

当前水果 : banana
当前水果 : apple
当前水果 : mango
Good bye!

In the above example we used the built-in functions len() and range(). The len() function returns the length of the list, i.e., the number of elements. range() returns a sequence of numbers.



Using else Statement with Loop

In Python, for...else means the following: the statements in the for loop are no different from ordinary ones, and the statements in the else branch will be executed when the loop completes normally (i.e., the for loop is not interrupted by a break). The same applies to while...else.

Example

#!/usr/bin/python # -*- coding: UTF-8 -*- for num in range(10,20): # Iterate over numbers between 10 and 20 (exclusive) for i in range(2,num): # Iterate over factors if num%i == 0: # Determine the first factor j=num/i # Calculate the second factor print ('%d equals %d * %d' % (num,i,j)) break # Break out of the current loop else: # The else part of the loop print ('%d is a prime number' % num)

Try it yourself »

The output of the above example is:

10 等于 2 * 5
11 是一个质数
12 等于 2 * 6
13 是一个质数
14 等于 2 * 7
15 等于 3 * 5
16 等于 2 * 8
17 是一个质数
18 等于 2 * 9
19 是一个质数

More examples:Python printing diamond, triangle, rectangle

Other extensions