Python for loop statement

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

Syntax:

The syntax of the

for loop is as follows:

for iterating_var in sequence:
statements(s)

Flowchart:

python_for_loop

Instance:

Instance

#!/usr/bin/python # -*- coding: UTF-8 -*- for letter in 'Python': # First instance print 'Current letter :', letter print "Good bye!"

The output of the above example:

Current letter : P
Current letter : y
Current letter : t
Current letter : h
Current letter : o
Current letter : n
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!


Iterating through sequence index

Another way to traverse the execution loop is through an index, as in the following example:

Instance

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

The output of the above example:

Current Fruit : banana
Current Fruit : apple
Current Fruit :Good bye!

The above example uses the built-in functions len() and range(), and the function len() returns the length of the list, which is the number of elements. Range returns the number of a sequence.



Recycling the else statement

In python, for ... else means that the statement in for is no different from normal, and the statement in else will be executed if the loop is executed normally (that is, if for is not interrupted by a break) , while ... else is the same.

Instance

#!/usr/bin/python # -*- coding: UTF-8 -*- for num in range(10,20): # Iterate between numbers 10 and 20 for i in range(2,num): # Iteration based on factors if num%i == 0: # Determine the first factor j=num< Span class="hl-code">/i # Calculate the second factor print '%d equals %d * %d' % (num,i,j ) break # Jump out of the current loop else: # the else part of the loop< /span> print num, 'is a prime number'

The above example output:

10 equal 2 * 5
11 Is a prime number
12 equal 2 * 6
13 Is a prime number
14 equal 2 * 7
15 equal 3 * 5
16 equal 2 * 8
17 Is a prime number
18 equal 2 * 9
19 Is a prime number





welookups is optimized for learning.© welookups .
All Right Reserved and you agree to have read and accepted our term and condition