if branch structure and for cycle knowledge combing on September 16

September 16

I. if Branch Structure

1. Process Control--Three Structures

1) Sequential structure (default)

Default sequential structure for program execution

Code executes from top to bottom, each code executes only once

2) Branch structure (if)

You can choose to execute a section of code (if) depending on whether the condition is valid or not.

3) Circulation structure (for/while)

Duplicate code execution

2. Sequential structure

print('How are you?')

print('how are you!')

print('hello!')

[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-Kw3CrQUH-16318055727) (E:Python 2106Knowledge Point Screenshot 9.16if Branch Structure and for LoopSequential Structure 1.png)]

print('Launcher loads static resources')
print('Check Network Status')
print('Connect iQIYI Server, Get Network Data')
print('prompt no network available')
print('Load Local Cached Data')

[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-HKSoY8g1-16318055729) (E:Python 2106Knowledge Point Screenshot 9.16if Branch Structure and for LoopSequential Structure 2.png)]

When this happens, not suitable for sequential structure in the execution process will have a choice, can not be written in such a sequential structure, you need to determine whether there is a network or not.

3.if branch structure

1) Single branch structure:

- To perform an operation if a condition is met, the condition is not met, and the operation is not executed with a single branch structure

Syntax: (Indentation occurs where there is a colon, and the same indentation is a block of code, which works the same as the block of code enclosed in c > Language {})

if condition statement:

Code snippet

(Generally, four spaces represent an indent, and pressing a tab key means four spaces and one indent)

Structure description:

1.if ----- Keyword, Fixed Writing

2. Conditional Statements - ----- Requirements: Any Resulting Expression

For example: specific data, variable already assigned, operation expression, letter > number call expression

(assignment statements have no result and cannot be placed in conditional statements)

3 Colon: --------- Must be in English, all symbols inside the program must be in English, > > Fixed writing must be written

4. Code snippet - --- one or more statements (at least one) that remain indented structurally and if

Code to execute when a condition is met

Execution process:

If xxx (conditional statement) is xxx (code snippet) (what if what)

First determine if the conditional statement is True (if the result of the conditional statement is not a Boolean value, first > to a Boolean value, if True, execute, otherwise the code snippet does not execute)

if 100:  #100 for a Boolean value of True
    print('A')
    print('B')
print('C')

Note: Assignment statements cannot be conditional statements for if branches, at least one statement is in the code snippet following if

if 0:  #0 to False
    print('A')
    print('B')
print('C')

Practice:

Exercise 1: Print based on age values'You can go online'
age = int(input('Please enter your age'))
if age >= 18:
    print('You can go online')
# Exercise 2: Print'Excellent'(over 90 points) according to the score value
score = int(input('Please enter your score'))
if score >= 90:
    print('excellent')

2) Double Branch Structure

------ Perform an action if a condition is met, or perform another action

Grammar:

if condition statement:

Code snippet 1 (the code that meets the criteria to execute)

else:

Code snippet 2 (code to execute if the condition is not met)

(same requirement as single-branched structure)

Execution process: xxx if xxx is xxx otherwise xxx

Practice:

Exercise: Print based on setting integer values'Odd Number'perhaps'Even numbers': 
num = 23
if num % 2 == 0:
    print('This number is even')
else:
    print('This number is odd')

# Method 2:
if num % 2:
    print('Odd Number')
else:
    print('Even numbers')

3) Multi-Branch Structure

- Do different things according to different conditions

Option 1:

Only the existence of multiple conditions can be solved: if one of them is true, then the relationship between the other conditions will never be true

#There are only a few conditions that can be solved: if one of them is true, then the other conditions will never be.

if Conditional statement 1:#The conditional statement behind conditional statement 1 does not determine that it will not execute.
    Code snippet 1
elif Conditional statement 2:#The latter condition judgment is executed if the former condition judgment is unsuccessful.
    Code snippet 2
elif  Conditional statement 3:
    Code snippet 3
    . . . . 
else: 
    Code snippet N
    

Option 2:

If there is no condition between which one is satisfied and the other is absolutely not

if Conditional statement 1:
    Code snippet 1
if Conditional statement 2:
    Code snippet 2
    . . . And so on
 Print Excellence by Score Range-90 Good score above-80-90 A score of 90, medium 60-79 Failed below 60 points
 num = int(input('Please enter your score'))
# Method 1:
if num > 90:
    print('excellent')
elif 90 >= num >=80:
    print('good')
elif 79 >= num >= 60:
    print('secondary')
else:
    print('Fail')
# Method 2: (Condition2 can only be judged if the multi-branch structure judgment condition is not established, so it is not necessary to <=90 because the range of condition 1 is not judged)
if num > 90:
    print('excellent')
elif num >= 80:
    print('good')
elif num >= 60:
    print('secondary')
else:
    print('Fail')

4.if nested statement - code snippet nested if statement inside if statement

# Exercise: Print the multiple of odd, even and 4 according to the specified number
# Odd number: the remaining 2 of the specified number is not zero
# Even number: the remaining 2 of the specified number is 0
# Multiplier of 4: the remaining 4 of the specified number is 0
print('------------------------------------------------------')
if num % 2:
    print('Odd Number')
else:
    if num % 4 == 0:
        print('4 Multiple of')
    else:
        print('Even numbers')

2. for cycle

1.for loop

Grammar:
for variable in Sequence:
    Circulatory body
 Explain:
1)for   -   Keyword Fixed Writing
2)variable   -   The variable name, either defined or undefined, is the same as the variable name used to define the variable
3)in     -   Keyword, Fixed Writing
4)sequence    -   Any container data type, such as string, list, tuple, dictionary, collection, iterator, generator, range etc.
              (Data types such as numbers, nulls, Booleans, etc. cannot be placed in in Back)
5): colon   -   Fixed Writing
6)Circulatory body   -    and for Keep one or more indented statements (at least one statement);
                Code that needs to be executed repeatedly is put into the loop, and for Keep indentation in the loop

Execution process: Let variables take values out of the sequence, one by one, until the completion, each value executes a loop.
(for The number of loops in a loop is related to the number of elements in the sequence)
Every letter or number in a string is an element

Execution process:
x = 'Arrowroot' Take a value to execute a loop
 Then the variable takes the next value and enters the second loop x= 'Chao',Then execute a loop
 Enter the third cycle x = 'N' Then execute the loop once
 Enter the fourth cycle x = 'B' Then execute the loop once more
 If there is no fifth value to choose from, the loop ends
 Previously, if a variable was assigned a value that did not affect the value taken in the desequence, the value taken in the sequence was assigned to a variable that overwrote the value originally stored in the variable.

2.range function - the function itself produces a sequence of numbers within a specified range

(N)Represents any positive integer
 Usage 1: range(N)  -  Generate 0~N-1 A sequence of numbers,[0,N)(Open interval parentheses not available)
            For example: range(4)The resulting numbers are: 0, 1, 2, 3 (four digits -).
Usage 2: range(M,N)  -  produce M reach N-1 A sequence of numbers,[M,N)(M Must be less than N,And they are all integers, otherwise they are empty sequences and do not loop at a time)
            For example: range(2,6)  -- The resulting numbers are: 2, 3, 4, 5,
                 range(-2,2) --  Generate numbers:-2, -1, 0, 1
                 Values taken from variables that may be used when using this method
                 See how many loops you can use N-M
 Usage 3: range(M,N,step)  -  Produce interval or[M,N),Each increase in the value obtained in this interval step(Step)
                          For example: range(1,10,2)  -  Value taken: 1,3,5,7,9
                          If step If the value is negative M greater than N And from M Value N Unmarried
                          range(10,1,-1)
                          
When loops are large, strings are not appropriate and there are too many elements to list
for x in range(100):
    print(x, '++++++++++++++++')
# Range (number of loops) Fill in parentheses with the number of loops, as many times as you want to write

for x in range(-4, 4):
    print(x)

for x in range(-4, 4,3):
    print(x)

3. Route 1: Summation

# Step 1: Define a variable with a default value of 0 (this variable is used to save the last sum)
# Step 2: Use the variables in the for loop to pull out all the data you need to sum in turn
# Step 3: Add a value to the saved sum variable for each value taken in the loop
# 1+2+3+. . . +100
sum1 = 0#Define a variable, take out a number and add one to and from it.
for x in range(1,101):
    sum1 += x
    print(sum1)
print(sum1)
'''
scores = [89,99,90,50]
sum1 = 0
for x in scores:   - String Assignment Variables
    sum1 += x
print(sum1)
'''

4. Route 2: Number of Statistics

# Count the number of even numbers between 20 and 100
# Method 1:
num = 0
for x in range(20, 101):
    if x % 2 == 0:
        num += 1
print(num)

# Method 2
num = 0
for x in range(20, 101, 2):
    num += 1
print(num)


# Exercise: Count the failing points
scores = [30, 89, 99, 90, 50]
num1 = 0
num2 = 0
num3 = 0
for x in scores:
    if x < 60:
        num1 += 1
    elif x >= 90:
        num3 += 1
    else:
        num2 += 1
print('Those who fail are:', num1, 'personal', sep='')
print('Passing people have:', num2, 'personal', sep='')
print('Excellent people have:', num3, 'personal', sep='')

, 50]

num1 = 0
num2 = 0
num3 = 0
for x in scores:
if x < 60:
num1 += 1
elif x >= 90:
num3 += 1
else:
num2 += 1
print('Failed People:', num1,'Personal', sep=')
print('Passed by:', num2,'Personal', sep=')
print('The best people are:', num3,'personal', sep=')

Keywords: Python Pycharm perl

Added by 2DaysAway on Fri, 17 Sep 2021 07:30:16 +0300