The main purpose of loop in a program is to avoid unnecessary labor caused by repeated statements being typed multiple times. Therefore, we need to learn and master the loop programming technology under Python.
This section describes how to use the while LOOP body mechanism in Python. The syntax structure of the while condition loop body is as follows:
[Python]View plaincopy
- Conditon_variable_init
- While conditon:
- (TAB) statement1
- (TAB) statement1
- (TAB) statement1
- Etc.
- Condition_modify
The while condition loop body usually requires initialization of the condition (variable) before the while statement (1st rows). The condition in the while statement can be a Boolean expression or a relational operation expression, in the while clause, TAB is used to indent each statement. Generally, some judgments in the while clause use variables in the while clause (7th rows ), if the while statement is not corrected, it will be an infinite loop.
For example (print n times in a loop ).
[Python]View plaincopy
- Def pwhile (num ):
- C = 0
- While c <num:
- Print (c)
- C + = 1
- Def main ():
- N = int (raw_input ("plz input a num "))
- Pwhile (n)
- Main ()
Check the running result.
Note that the program has a type parameter num used to control the number of loops. row 2nd is a variable in the while LOOP body condition c <num, when c is smaller than num, The while statement (Row 4-5) can be executed. The first row is the print statement, and the second row is the correction condition of the loop body, which is used to control the number of while loops for a certain number of times.