python--review two kinds of circulation

Source: Internet
Author: User

1. for x in ... a loop is a statement that puts each element into a variable and x then executes the indented block. iterate through each element of the list or tuple in turn.

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

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

If you want to calculate the sum of 1-100 integers, writing from 1 to 100 is a bit difficult, but fortunately Python provides a range() function that generates a sequence of integers that list() can then be converted to a list by a function. For example, range(5) the generated sequence is an integer starting from 0 and less than 5:

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

range(101)You can generate an integer sequence of 0-100, which is calculated as follows:

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

Practice:

The purpose of this exercise is not to understand the role of X ... After I wrote it, I felt more deeply.

2. While loop, as long as the condition is satisfied, it loops continuously and exits the loop when the condition is not satisfied.

For example, we want to calculate the sum of all the odd numbers within 100, which can be implemented with a while loop:

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

The loop internal variable is n continuously self-reducing until -1 it becomes, and the while condition is no longer satisfied, and the loop exits.

python--review two kinds of circulation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.