Home  >  Article  >  Backend Development  >  Use Python for loop examples to analyze what is a Python loop statement?

Use Python for loop examples to analyze what is a Python loop statement?

Tomorin
TomorinOriginal
2018-08-23 17:47:131458browse

Similar to Python judgment statements, there are also loop statements in Python, such as for, while, etc., in loop statements, if the conditions are not set accurately, it will enter an infinite loop. At this time, the page will report an error to the system, otherwise the computer will crash directly.

So what is a cycle?

For example, if we want to calculate 1 2 3, we can write the expression directly:

>>> 1 + 2 + 3
6

If we want to calculate 1 2 3... 10, we can barely write it out.

However, to calculate 1 2 3 ... 10000, it is impossible to write an expression directly.

In order for the computer to calculate thousands of repeated operations, we need loop statements.

There are two types of loops in Python. One is the for...in loop, which iterates out each element in the list or tuple in turn. See example:

names = ['Michael', 'Bob', 'Tracy']
for name in names:
   print(name)

Execution of this code will print each element of names in turn:

Michael
Bob
Tracy

So for x in...The loop is to substitute each element into the variable x , and then execute the statements of the indented block.

For example, if we want to calculate the sum of integers from 1 to 10, we can use a sum variable to accumulate:

sum = 0
for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
   sum = sum + x
print(sum)

If we want to calculate the sum of integers from 1 to 100 , it is a bit difficult to write from 1 to 100. Fortunately, Python provides a range() function, which can generate an integer sequence, and then use the list() function to convert it into a list. For example, the sequence generated by range(5) is an integer starting from 0 and less than 5:

>>> list(range(5))
[0, 1, 2, 3, 4]

The second type of loop is a while loop. As long as the conditions are met, it will continue to loop and exit the loop when the conditions are not met. For example, if we want to calculate the sum of all odd numbers within 100, we can use a while loop to implement it:

sum = 0
n = 99
while n > 0:
    sum = sum + n
    n = n - 2
print(sum)

The variable n inside the loop continues to decrement until it becomes -1, the while condition is no longer satisfied, and the loop exits.

The above is the detailed content of Use Python for loop examples to analyze what is a Python loop statement?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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