Python loop while, for statement

one

Loop statement (there are two kinds):

while statement

for statement

while statement:

Question: Input an integer n, let the program output n lines:

hello 1

hello 2

.......

hell n

while statement:

Function: Repeatedly execute a statement or multiple statements according to certain conditions

grammar:

while truth expression:

Statement block 1...

else:

Statement block 2...

illustrate:

1, first execute the truth expression, test the boolean value is True or False

2. If the test value of the truth expression is True, execute statement 1, and then return to the first step to repeat the test

3, if the test value of the truth expression is False. Then execute the statement block 2 in the else clause, and then end the execution of the while statement. If there is no else clause, then directly end the execution of the while statement.

4. The else clause part can be omitted (similar to the if statement).

Such as: print 10 lines of hello
i = 1 #Create and initialize a variable i that controls the while loop
while i <= 10:
        print("hello") #execute 10 times here
        i += 1 
#Run result: [root@localhost data]# ./test.py 
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello

Notes on the while statement:

1. To control the value of the true value expression of the loop to prevent an infinite loop.

2. The loop condition is usually controlled by the loop variable in the truth expression.

3. Usually, the loop needs to be changed in the loop block to control the number of loops and the direction of variables.


Nesting of while loops:

The while statement itself is a statement, and like other statements, it can be nested in other compound statements (such as: if statement, while statement, for statement....inside)


Nested while statement shows:

while truth expression:

.......

while truth expression 2:

......

else:

........

else:

........

Such as:

Enter a number to print a square of the specified width:

Such as: input: 5

n = int(input("Enter a number:"))
j = 1
while j <= n:
    i = 1
    while i <= n:
        print(i,end=' ')
        i += 1
    print()
    j += 1 
######operation result:
1 2 3 4 5 
1 2 3 4 5 
1 2 3 4 5 
1 2 3 4 5 
1 2 3 4 5


break statement:

Role: used in loop statements (while, for statements) to terminate the execution of the current loop statement.

illustrate:

1. When the break statement is executed, the statement after the break statement of this loop will no longer be executed

2. The break statement is usually used in combination with the if statement.

3. When the break statement terminates the loop, the else clause of the loop statement will not be executed

4. The break statement can only terminate the execution of the current loop. If there is a loop nesting, it will not jump out of the nested outer loop.

5. The break statement can only be used inside a loop statement (while or for statement)

Such as:

i = 1
while i < 10:
        print("loop start i=",i)
        if i == 5: #end the loop when i = 5
                break
        i += 1
#Run result: [root@localhost data]# ./test.py 
loop start i=1
loop start i=2
loop start i=3
loop start i=4
loop start i=5

Infinite loop death loop:

1. An infinite loop refers to a loop in which the loop condition is always established

1. An infinite loop is usually terminated with a break statement

3. The else clause of the infinite loop will never execute

For example: use input to enter some text, when three * signs are entered, it means the input is over, otherwise it keeps looping.

s = ""
while True:
        a = input("Please enter text (*** end)")
        if a == '***':
                break
        s += a + '\n'
##Running result: [root@localhost data]# ./test.py 
Please enter text (End of ***)a
Please enter text (end of ***)b
Please enter text (END ***)v
Please enter text (*** end)c
Please enter text (End of ***)d
Please enter text (***end)*** #Enter three *** to end, exit the loop
[root@localhost data]#


two:

for statement (loop statement)

Role: used to traverse the data elements of an iterable object

grammar:

for variable list in iterable:

Statement block 1...

else:

Statement block 2...


Syntax Description:

1. The iterable object provides one element at a time and assigns it to the variables in the variable list in turn. After the assignment is completed, execute statement block 1, and repeat this step.

2. When the iterable object cannot provide data, execute the statement block 2 of the else clause part, and then exit the loop.

Such as:
s = 'ABCDE' 
for x in s: 
        print(x)
else:   
        print("Continue to execute this item") #When the iterative object cannot provide data, continue to execute this item in else
##Running result: [root@localhost data]# ./test.py 
A
B
C
D
E
continue with this

                3. The else clause part can be omitted (similar to the while statement)

4. When the loop is terminated with break inside the statement, the statement block 2 of the else clause part will not be executed,

            An iterable object refers to an object that can sequentially obtain data elements

Four:

for loop nesting: same as while loop nesting

Such as:

for x in "ABC":
        for y in "123":
                print(x + y)
##operation result:
[root@localhost data]# ./test.py 
A1
A2
A3
B1
B2
B3
C1
C2
C3

Classic no loop nesting example:

                Use for loop nesting to print the following graphics:

(Enter a number n (within 10) to represent the width and height of the rectangle) 

For example: Input: 5

1 2 3 4 5

  2 3 4 5 6

  3 4 5 6 7 

  4 5 6 7 8 

  5 6 7 8 9 

n = int(input("Enter a number:"))
for i in range(1, n +1):
    for j in range(i, i + n):
        print(j,end=' ')
    else:
        print()
        
#operation result:
[root@localhost data]# ./test.py 
Enter a number: 5
1 2 3 4 5 
2 3 4 5 6 
3 4 5 6 7 
4 5 6 7 8 
5 6 7 8 9

Fives:

continue statement:

Function: used in the loop statement (while, for statement), the statement after the continue in this loop is no longer executed, and a new loop is restarted.

illustrate:

1. Execute the continue statement in the while statement, which will directly jump to the truth expression of the while statement to re-evaluate the loop condition.

2. Execute the continue statement in the for statement, which will take the next element from the iterable object, bind the variable and loop again.

Such as:

for i in range(5):
        if i == 3: #When i is equal to 3, skip printing and go to the next loop.
                continue
        print(i)
#operation result       
[root@localhost data]# ./test.py 
0
1
2
4

Example:

Write a program to find the sum of the numbers between 1 and 100 that are not divisible by 5, 7, and 11.

s = 0 
for i in range(1,101):
    if (i % 5) == 0 or (i % 7) == 0 or (i % 11) == 0:
        continue
    s += i
print(s)
#operation result:
[root@localhost data]# ./test.py 
3007

six:

range function:

Role: used to create an iterable object that generates a series of integers (also called an integer sequence generator.)

Call format:

range(stop)

Start from zero, add 1 each time an integer is generated, and operate until stop (excluding stop)

range(start,stop[,step]) starts from start, and moves step after generating an integer each time until stop (stop is not included, and step can be negative.)

          Note: If you print range(5) or (print(range(5))) directly, you will get range(5) instead of a list. This is because it saves space and prevents overly large lists from being generated.

    Such as:

>>> range(5)     
range(0, 5)
>>>

       If you want to get a list in interactive mode, you can add list to the front to do it, as follows:

Example:

>>> list(range(5))      
[0, 1, 2, 3, 4]
>>> list(range(1,6))    
[1, 2, 3, 4, 5]
>>> list(range(10,0,-1))
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> list(range(1,10,2)) 
[1, 3, 5, 7, 9]
>>> list(range(5,0,-2))
[5, 3, 1]
>>>



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324688136&siteId=291194637