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