Home >Backend Development >Python Tutorial >Detailed explanation of while and for statements in Python loop statements

Detailed explanation of while and for statements in Python loop statements

不言
不言Original
2018-04-23 15:18:382876browse

The following is a detailed explanation of the while and for statements of Python loop statements. It has a good reference value and I hope it will be helpful to everyone. Let’s take a look together

There are two kinds of loops in Python, namely: for loop and while loop. A for loop can iterate over any sequence of items, such as a list or a string. The while statement is used to execute a program in a loop, that is, under certain conditions, execute a certain program in a loop to handle the same task that needs to be processed repeatedly.

Loop statement (there are two types):

while statement
for statement

while statement:

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

hello 1
hello 2
.....
hell n

while statement:

Function: Repeat one or more statements according to certain conditions

Syntax:

while truth expression:

Statement block 1...
else:
Statement block 2...

Instructions:

1, first execute the truth expression, test the Boolean value is True or False
2, if the truth expression is tested If the value is True, execute statement 1, then return to step 1 and repeat test
3, if the test value of the truth expression is False. Then execute statement block 2 in the else clause, and then end the execution of the while statement. If there is no else clause, directly end the execution of the while statement.
4, the else clause part can be omitted (similar to if statement).

For example: print 10 lines of hello

i = 1 #Create and initialize a variable i that controls the while loop
while i <= 10:
PRINT ("Hello")#Perform 10 times here
i = 1
# Operation Result: [root@localhost data]#./test.py
stelo
hello
hello
hello
hello
hello
hello
hello
hello
hello

## Notes on the while statement:


1. Control the value of the loop’s truth expression to prevent an infinite loop.

2, usually use loop variables in truth expressions to control loop conditions.
3, usually the loop needs to be changed within the loop statement block to control the number of loops and the direction of the variables

The nesting of while loops:


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

while statement nesting diagram:


while truth expression:

..........
while truth expression 2:
......
else:
... .....
else:
.....
For example:

Enter a number and print a square with the specified width:

For example: 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


Run 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:


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


Note:
1. When the break statement is executed, the statements after the break of this loop statement 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 nested loop, it will not jump out of the nest. External heavy loop
5, the break statement can only be used inside a loop statement (while or for statement)

For example:


i = 1
while i < 10:
     ("Start of loop i=",i)
If i == 5: #End the loop when i = 5
Break
i = 1
#Run result: [root@localhost data] # ./test.py
Start of loop i= 1
Start of loop i= 2
Start of loop i= 3
Start of loop i= 4
Start of loop i= 5


Death loop:


1, an infinite loop refers to a loop in which the loop condition is always true
2, an infinite loop usually uses the break statement to terminate the loop
3, The else clause of the infinite loop will never be executed

For example: use input to input some text. When three * signs are entered, it means the input is finished, otherwise it will keep looping. ###

s = ""
while True:
a = input("Please enter text (***end)")
if a == '***':
BREAK
s = a '\ n'
## Run results: [root@localhost data]#./test.py
Please enter text (*** end) a
Please enter text (***End)b
Please enter text(***End)v
Please enter text(***End)c
Please enter text(***End)d
Please enter text( ***End)*** #Enter three *** to end and exit the loop
[root@localhost data]

#2: for statement (loop statement)

Function: Used to traverse the data elements of iterable objects

Syntax:
for variable list in iterable object:

Statement block 1 ......
else:
Statement block 2......

Syntax description:

1, the iterable object is provided one at a time The elements are assigned 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 statement block 2 in the else clause part and then exit. cycle.

For example:

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

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

4. When break is used to terminate the loop inside the statement, the else clause part of statement block 2 will not be executed.
            Iterable objects refer to objects that can obtain data elements in sequence

Four: for Loop nesting:

is the same as while loop nesting

For example:

for 123 ":
PRINT (x y)
## Run results:
[root@localhost data]#./test.py
a1
a2
# B1
B2
B3
C1
C2
C3


Classic example of loop nesting

## 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( )
             
#Run 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



5: continue statement:

Function: Used in loop statements (while, for statements), the statements after continue in this loop will no longer be executed, and a new loop will be restarted.

Instructions:

#1. Execute the continue statement in the while statement and jump directly to the truth expression of the while statement to re-judge the loop condition.
2. Executing the continue statement in the for statement will remove an element from the iterable object, bind the variable, and loop again.

For example:



for i in range(5):

If i == 3: #When i equals 3, skip printing and proceed to the next loop.
Continue

PRINT (i)
# Run results
[root@localhost data]#./test.py
0
1
4 ## 4 ## 4


##Example:
Write a program to find the sum of numbers between 1-100 that are not divisible by 5,7,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)
#Running result:
[root@localhost data]# ./test.py
3007



Six: range function:

Function: Used to create an iterable object that generates a series of integers (also called an integer sequence generator.)
Calling format:
range(stop)
Start from zero, each generation Add 1 after an integer, operate until stop (excluding stop)
range (start, stop[, step]) starts from start, and moves step after generating an integer each time, until stop (excluding stop, And step can be a negative number.)
Note: If you print range(5) or (print(range(5))) directly, you will get range(5) instead of a list. This is to save space and prevent An overly large list is generated.
For example:

>>> range(5)
range(0, 5)
>>>
If you want to get it in interactive mode List, you can add list to the front, 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]
> >>

Related recommendations:

Summary of usage of else in Python loop statements

The above is the detailed content of Detailed explanation of while and for statements in Python loop statements. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn