Python for the same as other languages, can also be used to iterate through the object, this article introduces you to the Python for loop usage and examples, the need for friends and reference.
A loop is a structure that causes the first program to repeat a certain number of times. The same is true for repeated cyclic conditions. When the condition becomes false, the loop ends and the control of the program is passed to the following statement loop.
For loop:
Any item in a python for loop that iterates through a sequence, such as a list or a string, has the ability.
The For Loop syntax is:
for inch sequence: statements (s)
If a sequence contains a list of expressions, it is the first one to evaluate. Then, the first item in the sequence allocates the iteration variable Iterating_var. Next, execute the statement block. Each item in the list is assigned to Iterating_var, and the report block is executed until the entire sequence is exhausted.
Note: In Python, all indented characters spaces the same number of programming structures as the report, which is considered to be part of a single code block. Python uses indentation as a method of grouping its statements.
Example:
#!/usr/bin/python forLetterinch 'Python':#First Example Print 'Current Letter :', Letterfruits= ['Banana','Apple','Mango'] forFruitinchFruits#Second Example Print 'Current fruit:', FruitPrint "Good bye!"
The above will output the result:
Current letter:pcurrent letter:ycurrent letter:tcurrent letter:hcurrent letter:ocurrent letter:ncurrent Fruit : Bananacurrent fruit:applecurrent Fruit:mangogood bye!
Iteration sequence exponent:
Another way to iterate through each item is by the offset exponent of the sequence itself:
For example:
#!/usr/bin/pythonFruits= ['Banana','Apple','Mango'] forIndexinchrange (len (fruits)):Print 'Current fruit:', Fruits[index]Print "Good bye!"
This will produce the following results:
Current Fruit:bananacurrent fruit:applecurrent Fruit:mangogood bye!
Here we take the help of Len (), built-in functionality, which provides the total number of elements in a tuple, as well as the range () built-in functions that give us the actual sequential traversal.
Original address: http://www.manongjc.com/article/971.html
Related reading:
Python Loop control break continue statement explanation
Python absolute value function abs () example
Python two ways to delete files and directories
Python os.system Execute system command
Python global variables and local variables explained
Python for Loop