Python for loop and pythonfor Loop
Similar to other languages, Python for can also be used to traverse objects cyclically. This article introduces how to use and use Python for loops. for more information, see.
A loop is a structure that causes the first program to repeat for a certain number of times. The repeat and loop condition remains the same. When the condition changes to false, the loop ends and the program control is passed to the subsequent statement loop.
For Loop:
Any item in the Python for loop traversal sequence, such as a list or a string, has the ability.
The for loop syntax is:
for iterating_var in sequence: statements(s)
If a sequence contains a list of expressions, it is the first evaluation. Then, the first item in the sequence is assigned the iteration variable iterating_var. Next, execute the statement block. Each item in the list is allocated to iterating_var, and the report block is executed until the entire sequence is exhausted.
Note: In Python, all reports with the same number of programming structures after spaces with indentions are considered part of a single code block. Python uses indentation as its statement grouping method.
Example:
#!/usr/bin/pythonfor letter in 'Python': # First Example print 'Current Letter :', letterfruits = ['banana', 'apple', 'mango']for fruit in fruits: # Second Example print 'Current fruit :', fruitprint "Good bye!"
The output result is as follows:
Current Letter : PCurrent Letter : yCurrent Letter : tCurrent Letter : hCurrent Letter : oCurrent Letter : nCurrent fruit : bananaCurrent fruit : appleCurrent fruit : mangoGood bye!
Iteration Sequence index:
Another way to traverse each project is by the offset index of the sequence itself:
For example:
#!/usr/bin/pythonfruits = ['banana', 'apple', 'mango']for index in range(len(fruits)): print 'Current fruit :', fruits[index]print "Good bye!"
This produces the following results:
Current fruit : bananaCurrent fruit : appleCurrent fruit : mangoGood bye!
Here, with the assistance of len (), we adopt the built-in function, which provides the total number of elements in tuple and the actual sequential traversal given by the built-in function of range.
Address: http://www.manongjc.com/article/971.html
Related reading:
Explain the break continue Statement of Python Loop Control
Python absolute value function abs () instance
Two Methods for deleting files and directories in python
Python OS. system
Python global variables and local variables