05 _ loop statement

Source: Internet
Author: User
01. Three major procedures of the program
  • There are three process methods in program development:
    • Sequence--From top down, Sequential Code Execution
    • Branch-- Determines whether to execute the code based on conditionsBranch
    • Loop-- LetDuplicate specific codeRun
02. whileBasic usage of loops
  • The function of loop is to makeSpecified CodeRepeated execution
  • whileThe most common application scenarios of loops are:Code to be executedFollowSpecified number of times RepeatedRun
2.1 whileBasic statement syntax
Initial Condition setting-usually the while condition of the counter that is executed repeatedly (determine whether the counter has reached the target number of times): When the condition is met, when the condition 1 is met, when the condition 2 is met, the task 3... (Omitted )... processing condition (counter + 1)

Note::

  • whileThe statement and indentation areComplete code block
The first WHILE LOOP

Requirement

  • Print 5 times Hello Python
#1. define the number of repeated counter I = 1 #2. use the while condition while I <= 5: # print ("Hello Python ") # process counter I I = I + 1 print ("I = % d" % I after the loop ends)

Note: After the loop ends, the value of the previously defined counter condition still exists.

Endless loop

For programmer reasons,ForgotInside the loopModify the judgment condition of a loop, Resulting in continuous execution of the loop and the program cannot be terminated!

2.2 value assignment operator
  • In python, use=You can assign values to variables.
  • To simplify code writing during arithmetic operations,PythonIt also provides a seriesArithmetic OperatorsCorrespondingValue assignment operator
  • Note:Spaces are not allowed in the assignment operator.

| Operator | description | instance |
| = | Simple value assignment operator | C = A + B assigns the result of A + B to C
| + = | Addition and value assignment operator | C + = A is equivalent to C = C +.
|-= | Subtraction value assignment operator | C-= A is equivalent to C = C-.
|= | Multiplication and value assignment operator | C= A is equivalent to C = C *
|/= | Division assignment operator | C/= A is equivalent to C = C/.
| // = | Assign values by Division | C // = A is equivalent to C = C //
| % = | GetModule(Remainder) value assignment operator | C % = A is equivalent to C = C %
|= | Power assignment operator | C= A is equivalent to C = C **

2.3 counting method in Python

There are two common counting methods:

  • Natural notation(From1First) -- more in line with human habits
  • Program counting(From0Start) -- counting starts from 0 for almost all programming languages.

Therefore, when writing a program, you should try to develop the habit:Unless otherwise specified, the cycle count starts from 0.

2.4 cyclic computing

In program developmentExploitation cycle Repeated computingRequirements

In this case, you can:

  1. InwhileDefines a variable aboveStore the final calculation result
  2. Inside the loop body, each cycle usesLatest calculation results,UpdatePreviously Defined variables

Example

  • Calculate 0 ~ Sum of all numbers between 100
### Calculate 0 ~ Sum of all numbers between 100 #0. result = 0 #1. variable record cycles defining an integer I = 0 #2. start loop while I <= 100: Print (I) # Every loop, add result + = I # To process counter I + = 1 print ("0 ~ Result of the sum of numbers between 100 = % d "% result)
03. Break and continue

breakAndcontinueIs a keyword specifically used in a loop

  • break When a condition is met, Exit the loop, and no longer execute subsequent repeated code
  • continue When a condition is met, Do not execute subsequent repeated code

breakAndcontinueOnlyCurrent cycleValid

3.1 break
  • In the loop Process, IfAfter a condition is met,NoHope againContinue execution, You can usebreakExit Loop
I = 0 while I <10: # exit the loop when a certain condition of break is met, and no repeated code is executed # I = 3 if I = 3: break print (I) I + = 1 print ("over ")

breakValid only for the current cycle

3.2 continue
  • In the loop Process, IfAfter a condition is met,NoHopeExecute the loop code, but do not want to exit the loop, You can usecontinue
  • That is, in the entire loop,Only some conditions, You do not need to execute the loop code, but other conditions must be executed.
I = 0 while I <10: # When I = 7, you do not want to execute the code that needs to be repeated if I = 7: # Before using continue, you should also modify the counter # Otherwise the endless loop I + = 1 continue # re-executed code print (I) I + = 1
  • Note: Usecontinue,Special attention should be paid to the Code for conditional processing., Accidentally appearsEndless loop

continueValid only for the current cycle

04. whileLoop nesting 4.1 loop nesting
  • whileNesting is:whileThere iswhile
While condition 1: when conditions are met, things done 1 when conditions are met, things done 2 when conditions are met 3... (Omitted )... while condition 2: when conditions are met, things done 1 when conditions are met, things done 2 when conditions are met 3... (Omitted )... processing Condition 2 processing condition 1
4.2 loop nested drill-step 5 of the 9 th multiplication table: Print stars with nesting

Requirement

  • Output five rows consecutively on the console*, The number of asterisks in each row increases sequentially
*  **  ***  ****  *****  
  • Print with string *
#1. Define a counter variable. Starting from number 1, the loop will be more convenient ROW = 1 while row <= 5: Print ("*" * row) Row + = 1
Step 2: Print stars with nested loops

Knowledge PointPairprintFunction usage is enhanced

  • By default,printAfter the function outputs the content, a line break is automatically added to the end of the content.
  • If you do not want to add a line break at the end, you canprintAdded content after function output, end=""
  • Where""You can specifyprintAfter the function outputs the content, continue the content you want to display.

  • The syntax format is as follows:

# Print ("*", end = "") # simple line feed print ("")

end=""Indicates that the output content to the console will not wrap after it is finished.

Hypothesis Python Not providedString*OperationConcatenated string

Requirement

  • Output five rows consecutively on the console*, The number of asterisks in each row increases sequentially
*  **  ***  ****  *****    

Development procedure

  • 1> complete simple output of five lines of content
  • 2> analyze*What should I do?
    • The number of stars displayed in each row is the same as that of the current row.
    • Nest a small loop to process each rowColumnStar display
Row = 1 while row <= 5: # suppose Python does not provide a string * operation # inside the loop, add another loop, implement the star print Col = 1 while Col <= row: Print ("*", end = ") COL + = 1 # after each row is output, add another line feed print ("") Row + = 1
Step 2: multiplication table

RequirementOutput the 9-9 multiplication table in the following format:

1 * 1 = 1     1 * 2 = 2   2 * 2 = 4     1 * 3 = 3   2 * 3 = 6   3 * 3 = 9     1 * 4 = 4   2 * 4 = 8   3 * 4 = 12  4 * 4 = 16    1 * 5 = 5   2 * 5 = 10  3 * 5 = 15  4 * 5 = 20  5 * 5 = 25    1 * 6 = 6   2 * 6 = 12  3 * 6 = 18  4 * 6 = 24  5 * 6 = 30  6 * 6 = 36    1 * 7 = 7   2 * 7 = 14  3 * 7 = 21  4 * 7 = 28  5 * 7 = 35  6 * 7 = 42  7 * 7 = 49    1 * 8 = 8   2 * 8 = 16  3 * 8 = 24  4 * 8 = 32  5 * 8 = 40  6 * 8 = 48  7 * 8 = 56  8 * 8 = 64    1 * 9 = 9   2 * 9 = 18  3 * 9 = 27  4 * 9 = 36  5 * 9 = 45  6 * 9 = 54  7 * 9 = 63  8 * 9 = 72  9 * 9 = 81  

Development procedure

* 1. Print 9 rows of stars

*   *****          ****          *****                                ******           *******                    ******** *********                         

* 2. Set*Replace with the corresponding row and column to multiply

# Define the start row = 1 # print up to 9 rows while row <= 9: # define the start column Col = 1 # print the maximum row column while Col <= row: # End = "", indicating that the output ends without line breaks # "\ t" can output a tab on the console, align print ("% d * % d = % d" % (COL, row, row * col), end = "\ t") when outputting text ") # Number of columns + 1 Col + = 1 # line feed print ("") # number of rows + 1 row + = 1

Escape characters in strings

  • \tOutputTabTo assist in text outputVerticalKeep alignment
  • \nOutputLine Break

TabThe function isVerticalAlign text by Column

| Escape Character | description
| \\| Backslash
| \ '| Single quotes
| \ "| Double quotation marks
| \ N | line feed
| \ T | horizontal Tab
| \ R | enter

05 _ loop statement

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.