The Use of Python for Loop Statements

  • 2021-11-13 08:27:11
  • OfStack

The catalog Python for loop statement iterates through the sequence index iteration to loop through the else statement

Python for Loop Statement

The Python for loop can iterate through any sequence of items, 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)

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
for letter in 'Python':     #  No. 1 1 Instances 
   print ' Current letter  :', letter
 
fruits = ['banana', 'apple',  'mango']
for fruit in fruits:        #  No. 1 2 Instances 
   print ' Current fruit  :', fruit
 
print "Good bye!"

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!

Iterate through sequence index

Another way to perform a loop traversal is through an index, as shown in the following example:

Instances


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

Current Fruit: banana

Current Fruit: apple

Current Fruit: mango

Good bye!

In the above example, we used the built-in functions len () and range (), and the function len () returns the length of the list, that is, the number of elements. range returns the number of 1 sequence.

Recycle the else statement

In python, for … else means this. There is no difference between the statements in for and ordinary ones. The statements in else will be executed under the condition that the loop is normally executed (that is, for is not interrupted by jumping out of break), and while … else is also one.

Instances


#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
for num in range(10,20):  #  Iteration  10  To  20  The number between 
   for i in range(2,num): #  Iterate according to factors 
      if num%i == 0:      #  Determine the number 1 A factor 
         j=num/i          #  Calculate the number 2 A factor 
         print '%d  Equal to  %d * %d' % (num,i,j)
         break            #  Jump out of the current loop 
   else:                  #  Cyclic  else  Part 
      print num, ' Yes 1 Prime number '

Output of the above example:

10 equals 2 * 5

11 is a prime number

12 equals 2 * 6

13 is a prime number

14 equals 2 * 7

15 equals 3 * 5

16 equals 2 * 8

17 is a prime number

18 equals 2 * 9

19 is a prime number


Related articles: