To write: Python while loop

Source: Internet
Author: User

Objective:

Learn Python's while loop with a small script

Script one: Implement 1 to 100 number addition

#!/usr/bin/env python

Counter = 1//Assign a value to a variable, Python does not need to define a variable, python refers to a variable
sum100 = 0

While counter < 101://while Loop until the while is not less than 101, exit
SUM100 + = counter//equivalent to sum100 = sum100 + counter
Counter + = 1

Print sum100//output variable sum100

Script two: Output welcome zhangdl, must be input zhangdl to output

#!/usr/bin/env python

Username = raw_input ("username:")//Receive variable from screen

While username! = "ZHANGDL"://When not immediately looping, equal to not equal to the string, cannot be a variable, the variable will be error
Username = raw_input ("Username:")
Print "Welcome", username//Here is a string enclosed in double quotation marks, direct writing is a variable.

Script three: Python pays attention to the don ' t repeat yourself, all re-implementing script two, introducing the break statement

#!/usr/bin/env python

While true://Is true, always loops
Username = raw_input ("Username:")
If username = = "ZHANGDL"://until username equals ZHANGDL
Break//break Exit Loop

Print "Hi", username

Note: When you add an else to the back, the Execute ELSE statement is represented when the while end loop



This article is from the "Court of the Odd Tree" blog, please be sure to keep this source http://zhangdl.blog.51cto.com/11050780/1827546

To write: Python while loop

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.