4 Process Control 4.5 compare for loop and while loop

Source: Internet
Author: User

4.5.2 calculates the sum of the numbers entered by the user

The following program lets the user enter some numbers and then prints out the sum of those numbers.

① This is the version that uses the For loop:

# forsum.py
n = Int (input (' How many numbers to sum? '))
Total = 0
For I in range (n):
s = input (' Enter number ' + str (i + 1) + ': ')
Total = total + int (s)
Print (' The sum is ' + str (total))

650) this.width=650; "title=" Forsum.png "alt=" Wkiom1czkipxltaxaabcyg1ewtu892.png "src=" http://s3.51cto.com/wyfs02/ M02/7f/4f/wkiom1czkipxltaxaabcyg1ewtu892.png "/>

② This is the version that uses the while loop

# whilesum.py
n = Int (input (' How many numbers to sum? '))
Total = 0
i = 1
While I <= N:
s = input (' Enter number ' + str (i) + ': ')
Total = total + int (s)
i = i + 1
Print (' The sum is ' + str (total))

650) this.width=650; "title=" Whilesum.png "alt=" Wkiol1czkykwiwgyaaaod64hq7a153.png "src=" http://s2.51cto.com/ Wyfs02/m02/7f/4d/wkiol1czkykwiwgyaaaod64hq7a153.png "/>

Similarly, the while loop version is more complex than the for loop version.

This article is from the "Advanced Technology" blog, so be sure to keep this source http://vipnoon.blog.51cto.com/7589908/1766609

4 Process Control 4.5 compare for loop and while loop

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.