Python flow control - loop for, while

Loop structure

What is a circular structure

Repeat the loop structure is a piece of code blocks

Why use loop structures

Humans sometimes need to repeat something

So the program must have the appropriate mechanisms to control people's computers have the ability to do things this cycle

While Loop

while loop: for an unknown number of cycles of the scene, there must be an exit condition

Python programming while statement for executing a program loop, i.e., under certain conditions, implementation of certain program loop, the same processing task needs to repeat the process. The basic form:

while judgment conditions:
    Execute the statement ......

Execute statement may be a single statement or a block. Determination condition can be any expression, any non-zero, or non-null ( the value null) are true.

When the judgment condition false false, the cycle is ended.

Performing the following flow chart:

 

 // examples

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

Above the output code execution:

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!

continue and break usage

 

When there are two other important while statement command continue, break the cycle skip, continue for skipping the cycle, break it is used to exit the loop, in addition to "determination condition" may also be a constant, indicates the cycle must establishment, are used as follows:

i = 1
while i < 10:   
    I + 1 =
     IF I% 2> 0:      # skipped when the number of non-dual output 
        Continue 
    Print I          # output doubling 2,4,6,8,10 
 
I = 1
 the while 1:             # The cycling conditions must be established to a 
    Print I          # output 1 ~ 10
    i += 1
    IF i> 10:      # out of the loop when i is greater than 10 
        break

The pass statement

  The pass statement does nothing, generally as a placeholder or create a stub, pass statement does nothing, such as:

  while False:

    pass

pass role in the function of the statement

 

  When you're writing a program, execute the statement part of the idea is not yet complete, then you can use the pass statement placeholder, may also be used as a marker, the code had to be completed later. For example, the following:

 

  def iplaypython():

 

       pass

 

  Define a function iplaypython, but the function body part is not completed yet, do not write and can not empty the contents, so you can use pass instead of accounting positions.

pass effect statement cycle

 

  pass also commonly used in the preparation of an empty compound statement is the body, for example, you want an infinite loop of while, no action is required at each iteration, you can write:

 

    while True:

 

        pass

 

These are just an example, in reality, it is best not to write code, because the code block is executed pass to do anything that is not empty, then the python will enter an infinite loop.

// infinite loop (infinite loop)

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

Examples
 # ! / Usr / bin / Python 
# - * - Coding: UTF-8 - * - 
 
var = 1
 the while var == 1:   # This condition is always true, the loop will continue to perform unlimited 
   NUM = raw_input ( " the Enter A Number The : " )
    Print  " by You entered: " , NUM
 
print "Good bye!"
or
var = 1
 the while True:   # This condition is always true, the loop will continue to perform unlimited 
   NUM = raw_input ( " the Enter Number The A: " )
    Print  " by You entered: " , NUM
 
print "Good bye!"

# Examples of output results of the above: 
the Enter A Number: 20 is 
by You entered:   20 is 
the Enter A Number: 29 
by You entered:   29 
the Enter A Number: . 3 
by 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 loop you can use CTRL + C to interrupt the cycle.

Loop statement else use

In python in, while ... else else block executed in the loop when the 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"
Examples of the above 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

for loop

Python for loop can iterate any sequence of items, such as a list or a string.

grammar:

for loop syntax is as follows:

for iterating_var in sequence:
   statements(s)

//flow chart

 

// examples

Example. 1
 # ! / Usr / bin / Python 
# - * - Coding: UTF-. 8 - * -
 
for Letter in  ' the Python ' :      # first instance 
   Print ( ' the current letter: ' , Letter)
 
Fruits = [ ' Banana ' , ' Apple ' ,   ' Mango ' ]
 for Fruit in Fruits:         # second instance 
   Print ( ' Current fruit: ' , Fruit)
 
print ("Good bye!")

Examples of the above output:

Current letter: P
Current letters: y
Current letter: t
Current letter: h
Current letter: o
Current letters: n
Current fruit: banana
Current fruit: apple
Current fruit: mango
Good bye!
Further traversing the way through the execution cycle index, the following examples:

Example 2
#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
fruits = ['banana', 'apple',  'mango']
for index in range(len(fruits)):
   print ('当前水果 :', fruits[index])
 
print ("Good bye!")
Examples of the above output:

Current fruit: banana
Current fruit: apple
Current fruit: mango
Good bye!
The above examples we use the built-len () function and Range (), len () function returns the length of the list, i.e. the number of elements. range returns a sequence number.

Nested loop

nested for loop

for iterating_var in sequence:
   for iterating_var in sequence:
      statements(s)
   statements(s)

while loop nest

while expression:
   while expression:
      statement(s)
   statement(s)
You can be embedded in another loop the loop body, such as a while loop may be embedded in the for loop, and vice versa, you can embed in a for loop while loop.

Loop control statements

Loop control statements can change the order of statement execution. Python supports the following loop control statements:

Control statements

description

break statement

Terminates the loop during the execution of statement block, and jump out of the entire cycle

continue Statement

Terminates the current execution loop statement block, out of the cycle, the next cycle execution.

pass sentence

pass an empty statement, in order to maintain the integrity of the program structure.

 

Guess you like

Origin www.cnblogs.com/baicai37/p/12445148.html