Python programming for loop statement learning tutorial, pythonfor
A Python for loop can traverse any series of projects, 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:
Instance:
#! /Usr/bin/python #-*-coding: UTF-8-*-for letter in 'python': # First Instance print 'current letter :', letterfruits = ['bana', 'apple', 'mango'] for fruit in fruits: # print the second instance 'current letter: ', fruitprint "Good bye! "
Output result of the above instance:
Current letter: P current letter: y current letter: t current letter: h current letter: o current letter: n current letter: banana current letter: apple current letter: mangoGood bye!
Iterative by sequential Index
Another way to traverse the execution cycle is by indexing, as shown in the following example:
#! /Usr/bin/python #-*-coding: UTF-8-*-fruits = ['bana', 'apple ', 'mango'] for index in range (len (fruits): print 'current fruit: ', fruits [index] print "Good bye! "
Output result of the above instance:
Current fruit: banana current fruit: apple current fruit: mangoGood bye!
In the above example, we use the built-in functions len () and range (). The function len () returns the length of the list, that is, the number of elements. Range returns the number of sequences.
Loop using else statements
In python,... Else indicates this. The statements in for are no different from those in general. The statements in else are executed after the loop is executed normally (that is, the for statements are not interrupted by the break jump, while... The same is true for else.
Example:
#! /Usr/bin/python #-*-coding: UTF-8-*-for num in range (): # iterations of numbers between 10 and 20 for I in range (2, num): # iteration Based on the factor if num % I = 0: # determine the first factor j = num/I # Calculate the second factor print '% d equals % d * % d' % (num, I, j) break # Jump out of the current loop else: # print num of the loop else, 'is a prime number'
Output result of the above instance:
10 equals 2*511 is a prime number 12 equals 2*613 is a prime number 14 equals 2*715 equals 3*516 equals 2*817 is a prime number 18 equals 2*919 is a prime number