Loop in Python

Loop in Python

To calculate 1 + 2 + 3, we can write the expression directly:

>>> 1 + 2 + 3
6

To calculate 1 +2 +3 + … +10, barely can write out.

However, to calculate 1 +2 +3 + … + 10000, it is impossible to write a direct expression.

In order for the computer to count thousands of repetitions, we need to loop the statement.

There are two loops of Python, one for … in loops, followed by each element in the list or tuple iteration, see example:

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

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

Michael
Bob
Tracy

So the for x in … loop is to replace each element into the variable x, and then execute the indented block statement.

And then we want to calculate the sum of the integers of 1-10, you can use a sum variable to do the cumulative:

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

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

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

range (101) can generate 0-100 integer sequence, calculated as follows:

sum = 0
for x in range(101):
    sum = sum + x
print(sum)

Please run the above code to see if the result is not the year Gaussian students calculate the 5050.

The second loop is a while loop, as long as the conditions are met, the cycle, conditions are not satisfied when the exit cycle.

For example, we have to calculate the sum of all odd and even within 100, you can use the loop to achieve:

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

In the cycle of internal variables n continue to self-reduction, until it becomes -1, no longer meet the while conditions, cycle out.