Latest web development tutorials

Python While Loops

Python programming while loop statement is used to execute the program, that is, under certain conditions, the loop executes certain procedures need to repeat the same task to handle the process. The basic form is:

while 判断条件:

Execute the statement can be a single statement or a block. Analyzing the condition can be any expression, any non-zero, non-empty (null) values ​​are both true.

When the judgment condition false false, the loop ends.

Executive flow chart is as follows:




count = 0
while (count < 9):
   print 'The count is:', count
   count = count + 1

print "Good bye!"

Running instance >>

The above code is executed the output:

The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!

When the while statement has two important commands continue, break to skip cycle, continue to skip this cycle, break is used to exit the loop, in addition to "determine the conditions" can also be a constant value representing the loop must be establishment, are used as follows:

# continue 和 break 用法

i = 1
while i < 10:   
    i += 1
    if i%2 > 0:     # 非双数时跳过输出
    print i         # 输出双数2、4、6、8、10

i = 1
while 1:            # 循环条件为1必定成立
    print i         # 输出1~10
    i += 1
    if i > 10:     # 当i大于10时跳出循环

Infinite loop

If the conditional statement is always true, infinite loop will execute it, following examples:

# -*- coding: UTF-8 -*-

var = 1
while var == 1 :  # 该条件永远为true,循环将无限执行下去
   num = raw_input("Enter a number  :")
   print "You entered: ", num

print "Good bye!"

Examples of the above output:

Enter a number  :20
You entered:  20
Enter a number  :29
You entered:  29
Enter a number  :3
You entered:  3
Enter a number between :Traceback (most recent call last):
  File "", line 5, in <module>
    num = raw_input("Enter a number :")

Note: The above infinite loop you can use CTRL + C to interrupt the cycle.

Recycled else statements

In python, for ... else expressed so mean, for statements and ordinary no difference, else the statement is executed in the case of the normal cycle of execution End (ie for not interrupted by the break out of the) of, while ... else is the same.


count = 0
while count < 5:
   print count, " is  less than 5"
   count = count + 1
   print count, " is not less than 5"

The above example output is:

0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5

Simple statement group

The syntax is similar to the if statement, the while loop if you are only one statement, and while you can write the statement on the same line, as follows:


flag = 1

while (flag): print 'Given flag is really true!'

print "Good bye!"

Note: The above infinite loop you can use CTRL + C to interrupt the cycle.