Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Python While loop statement


May 10, 2021 Python2


Table of contents


The while statement in Python programming is used to loop a program, i.e. under certain conditions, a loop executes a program to handle the same tasks that need to be repeated. T he basic forms are:


while 判断条件(condition):
    执行语句(statements)……

An execution statement can be a single statement or a block of statements. The condition can be any expression, and any non-zero, or non-empty (null) value is True.

The loop ends when the condition is judged to be false.

The execution flowchart is as follows:

Python While loop statement

Gif demonstrates the Python while statement execution process

Python While loop statement




#!/usr/bin/python
count = 0 
while (count < 9): 
  print 'The count is:', count 
  count = count + 1 
print "Good bye!"

Try it out . . .

The above code executes 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!

There are two other important commands in the while statement, run to skip the loop, run to skip the loop, break to skip the loop, and break to exit the loop, in addition to the "judgment condition" can also be a constant value, indicating that the loop must be true, as follows:


# continue 和 break 用法
 
i = 1
while i < 10:   
    i += 1
    if i%2 > 0:     # 非双数时跳过输出
        continue
    print i         # 输出双数2、4、6、8、10
 
i = 1
while 1:            # 循环条件为1必定成立
    print i         # 输出1~10
    i += 1
    if i > 10:     # 当i大于10时跳出循环
        break

Unlimited loops

If the conditional judgment statement is true forever, the loop will execute indefinitely, as in the following example:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
var = 1
while var == 1:  # 该条件永远为true,循环将无限执行下去
   num = raw_input("Enter a number  :")
   print "You entered: ", num
 
print "Good bye!"

The above example output results:

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 "test.py", line 5, in <module>
    num = raw_input("Enter a number :")
KeyboardInterrupt

Note: The above infinite loops you can use CTRL-C to break the loop.



The else statement is cycled

In Python, while ... Else executes the else statement block when the loop condition is False:


#!/usr/bin/python
 
count = 0
while count < 5:
   print count, " is  less than 5"
   count = count + 1
else:
   print count, " is not less than 5"

The output of the above examples 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



A simple statement group

Similar to the syntax of an if statement, if you have only one statement in the while loop body, you can write the statement in the same line as while, as follows:

#!/usr/bin/python
 
flag = 1
 
while (flag): print 'Given flag is really true!'
 
print "Good bye!"

print "Good bye!

"Note: The above infinite loops you can use CTRL-C to break the loop.



The app instance

Pyhton removes spaces at the beginning and end of the string:

def trim(s):
    while s[:1] == ' ':
        s = s[1:]
    while s[-1:] == ' ':
        s = s[:-1]
    return s

str = '   W3cschool     '
print(trim(str))