Python Learning: Two loop statements for and while

Source: Internet
Author: User

1: First



2: Knowledge Summary

There are two types of Python loops, one is the for...in loop, and each of the elements in the list or tuple is iterated in turn to see an example:

names = [‘Michael‘, ‘Bob‘, ‘Tracy‘]for name in names:    print name

Executing this code will print names each element in turn:

michaelbobtracy  

so for x in ... The loop is to put each element into a variable x , and then executes the indented block of the statement.

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

sum = 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, such as range (5), which generates a sequence that is less than 0, starting from 5:

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

Range (101) can generate a sequence of 0-100 integers, calculated as follows:

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

Please run the above code on your own, to see if the result is 5050 of the students ' mental arithmetic.

The second loop is the while loop, which, as long as the condition is satisfied, loops continuously, exiting 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:

sum = 0n = 99while n > 0:sum = sum + N n = n-2print sum  Try 

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 Learning: Two loop statements for and while

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.