The while,for statement of the Python Loop statement

Source: Internet
Author: User
Below for you to share a Python circular statement of the WHILE,FOR statement, with a good reference value, I hope to be helpful to everyone. Come and see it together.





There are two types of loops in Python: For Loop and while loop. A For loop can traverse any sequence of items, such as a list or a string. The while statement is used to loop the execution of a program that, under certain conditions, loops through a program to handle the same tasks that require repeated processing.



Loop statements (there are two types):


While statement
For statement


While statement:



Problem: Enter an integer n to allow the program to output n rows:



Hello 1
Hello 2
.......
Hell N



While statement:



Function: Executes a statement or multiple statements repeatedly according to certain conditions



Grammar:



While truth-expression:



Statement Block 1 ...
Else
Statement Block 2 ...



Description


1, execute the truth expression First, and test the Boolean value to True or False
2, if the test value of the truth expression is true, the side executes statement 1, and then returns to the first step to repeat the test
3, if the test value of the truth expression is false. The statement block 2 in the ELSE clause is executed, and the execution of the while statement is ended, and if there is no else clause, the execution of the while statement is terminated directly.
The 4,ELSE clause section 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") #Executed here 10 times
i + = 1
#operation result
: [root@localhost data]#./test.py
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello


Considerations for the While statement:


1, to control the value of the loop truth expression to prevent a dead loop.
2, the cyclic condition is usually controlled by a loop variable in the truth expression.
3, usually in the loop statement block need to change the loop to control the number of cycles and the direction of the variable


Nesting of While loops:



The while statement itself is a statement that, like any other statement, can be nested in other compound statements (such as: if statement, while statement, for statement ...). Internal



The while statement is nested:



While truth-expression:
.......
While truth-expression 2:
......
Else
........
Else
........
Such as:



Enter a number to print a square of the specified width:
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
##### #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:



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



Description
1, when the break statement executes, the statement after the break of this loop statement will no longer execute
The 2,break statement is typically used in combination with the IF statement.
The ELSE clause of the loop statement will not be executed when the 3,break statement terminates the loop
The 4,break statement can only terminate the execution of the current loop, and will not jump out of nested outer-heavy loops if there is a loop nesting
The 5,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: #i = 5 o'clock End loop
Break
i + = 1
#operation result: [root@localhost data]#./test.py
Cycle Start i= 1
Cycle Start i= 2
Cycle Start i= 3
Cycle Start i= 4
Cycle Start i= 5



Dead Loop death loop:



1, the cycle is the cycle condition has been established
2, the dead loop usually terminates the loop with a break statement
3, the Else clause of the dead loop will never execute
such as: input some text with input, when input three * number, represents the input end, otherwise has been circulating.


s = ""
While True:
A = input ("Please enter text (* * * *)")
If a = = ' * * * ':
Break
S + = a + ' \ n '
# #operation result: [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) * * * #input end, exit loop
[Root@localhost data]#


Two: For statement (Loop statement)



function: A data element used to traverse an iterative object



Grammar:
The for variable list in iterates over an object:



Statement Block 1 ...
Else
Statement Block 2 ...



Syntax Description:



1, an iterative object is provided each time an element is assigned to a variable in the list of variables, the assignment is completed after the statement block 1, repeat this step,
2, when an iterative object is not able to provide data, execute the statement block 2 of the part of the ELSE clause, and then exit the loop.



Such as:


s = ' ABCDE '
For x in S:
Print (x)
Else
Print ("Continue with this article") #迭代对象不能够提供数据时, continue with this article in the Else
# #operation result: [root@localhost data]#./test.py
A
B
C
D
E
Continue with this article


3,else clause section can be omitted (same as while statement)



4, the ELSE clause partial statement Block 2 does not execute when the loop is terminated inside the statement,
An object that iterates over an object when it is able to retrieve the data element in turn



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 a For loop to nest the printed shape:
(Enter a number n (10 or less) to represent the width and height of the rectangle)
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


Five: Continue statement:



Function: Used in the Loop statement (while,for statement), no longer executes the statement after the continue in the loop, and starts a new loop again.



Description



1, executing the Continue statement in the while statement, jumps 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 take the next element from the iteration object, bind the variable and loop again.
Such as:


For I in range (5):
if i = = 3: #当i equals 3 o'clock, skip printing and proceed to the next loop.
Continue
Print (i)
#operation result
[Root@localhost data]#./test.py
0
1
2
4


Example:
Write a program that asks for the 5,7,11 of the number that cannot be divisible by the 1-100.


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:



Function: Used to create an iterative object (also called an integer sequence generator) that generates a series of integers. )
Call Format:
Range (stop)
Starts from zero, adds 1 after each integer, until stop (does not contain stop)
Range (Start,stop[,step]) starts with start, moves the step every time an integer is generated, until stop (does not contain stop, and step can be negative). )
Note: If you print range (5) or (print (5)), you will get a range (5) Instead of a list because it saves space and prevents too large lists from being generated.
Such as:



>>> Range (5)
Range (0, 5)
>>>
If you want to get a list in interactive mode, you can join 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 the use of else in the Python looping statement




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.