Home > Backend Development > Python Tutorial > for loop in Python

for loop in Python

高洛峰
Release: 2017-03-03 14:00:18
Original
2220 people have browsed it

A loop is a structure that causes the first program to be repeated a certain number of times. The conditions continue to repeat themselves. When the condition becomes false, the loop ends and control of the program is passed to the statements following the loop.

for loop:

A for loop in Python has the ability to iterate over a sequence of any item, such as a list or a string.

The for loop syntax is:

for iterating_var in sequence:
statements(s)
Copy after login

If a sequence contains a list of expressions, it is the first evaluate. The first item in the sequence is then assigned to the iteration variable iterating_var. Next, execute the block of statements. 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 followed by spaces after the same number of statements in a programming structure are considered part of a single code block. Python uses indentation as its method of grouping statements.

Example:

#!/usr/bin/python
for letter in 'Python': # First Example
print 'Current Letter :', letter
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # Second Example
print 'Current fruit :', fruit
print "Good bye!"
Copy after login

The above will output the result:

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 over the sequence index:

Another way to iterate over each item is by the offset index of the sequence itself:

For example:

#!/usr/bin/python
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print 'Current fruit :', fruits[index]
print "Good bye!"
Copy after login

This will produce the following results:

Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!

Here we take the help of len() inbuilt function which gives us the total number of elements in the tuple, and the range() inbuilt function gives us Actual sequential traversal.

The above is a brief analysis of the for loop in Python that the editor introduces to you. It is very good and has reference value. Friends who are interested should learn together!

For more articles related to for loops in Python, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template