Python Loop while,for Statement

Source: Internet
Author: User
Tags terminates


One





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).


Example: 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
#Run results: [[email protected] 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: # end loop when i = 5
                 break
         i + = 1
#Run results: [[email protected] 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



1, 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 (*** end)")
         if a == '***':
                 break
         s + = a + '\ n'
## Run result: [[email protected] data] # ./test.py
Please enter text (*** ends) a
Please enter text (*** ends) b
Please enter text (*** ends) v
Please enter text (*** ends) c
Please enter text (*** ends) d
Please enter text (*** end) *** #Enter three *** to end and exit the loop
[[email protected] 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 to execute this article") #When the iteration object cannot provide data, continue to execute this article in else
## Run result: [[email protected] data] # ./test.py
A
B
C
D
E
Continue 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:
[[email protected] 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:
[[email protected] 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: #When i is 3, skip printing and go to the next cycle.
                 continue
         print (i)
#operation result       
[[email protected] 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:
[[email prote


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]
>>>








Python Loop while,for 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.