Python - branch structure & loop structure

(1) Logical thinking at the bottom of the sentence

             Control statement: Combine statements into small logic modules that can complete certain functions. There are three categories: sequence, selection, and loop.

in:

 " Sequential structure " represents the logic of "do a first, then do b" . For example, find a girlfriend first, then call her girlfriend;

  marry, remarry;

1
The " Conditional Judgment Structure " represents the logic of "if...then..." . For example, if your girlfriend calls, answer the call quickly; if you see
Stop at a red light;
2
A " loop structure " represents the logic of "if...then repeat..." . For example, if you don't get through to your girlfriend's phone number, continue to make another call.
times; if you don't find someone you like, keep looking.

 

     As above, we were surprised to find that three flow control statements can express everything! We can try to split up various things we encounter in life. In fact, any software and program, as small as an exercise or as large as an operating system, essentially consists of " variation "
Quantity, selection statement, loop statement " .

(2) Selection structure ( conditional judgment structure )

    The selection structure decides which branch to execute by judging whether the condition is true . There are many forms of selection structures, which are divided into: single-branch, double-branch, and multi-branch.

single branch selection structure

Execute if the condition is met, otherwise not execute. The grammatical form of the single-branch structure of the if statement is as follows:

if condition expression :
statement / block
  Conditional expression: It can be logical expression, relational expression, arithmetic expression, etc.
Detailed explanation of conditional expressions
Ⅰ In selection and loop structures, the conditional expression evaluates to False as follows:
      False , 0 , 0.0 , null value None , empty sequence object (empty list, empty tuple, empty collection, empty dictionary, empty character
string), an empty range object, and an empty iterator object.
In all other cases, True . From this point of view, all legal expressions in Python can be regarded as conditional expressions, even expressions of function calls.
Ⅱ  In the conditional expression, there cannot be an assignment operator =
       In Python , the assignment operator = cannot appear in the conditional expression, which avoids the troubles caused by often mistakenly writing the relational operator == as the assignment operator = in other languages.
The following code will report a syntax error:
if 6 < c and (c=20):   #直接报语法错误!
print("赋值符不能出现在条件表达式中")
Statement / statement block: It can be one statement or multiple statements. For multiple statements, the indentation must be consistent

 

two-branch selection structure

The syntax of the double-branch structure is as follows:

if condition expression :
Statement 1/ Statement Block 1
else:
statement 2/ statement block 2

 

multi-branch selection structure 

The syntax format of the multi-branch selection structure is as follows:
if conditional expression 1:
Statement 1/ Statement Block 1
elif conditional expression 2:
statement 2/ statement block 2
...
elif conditional expression n :
statement n/ statement block n
[else:
statement n+1/ statement block n+1
]
Note: In the computer industry, when describing the grammatical format, brackets [ ] are usually used to indicate optional, not mandatory.
Multi-branch structure, there is a logical relationship between several branches, and the order cannot be reversed at will

Branch structure specific code:

#单分支结构
if 3: #整数作为条件表达式
 print("ok")
a = []   #列表作为条件表达式,由于为空列表,是
if a:
   print("空列表,False")
s = "False"  #非空字符串,是True
if s:
  print("非空字符串,是True")
c = 9
if 3<c<20:
    print("3<c<20")
if 3<c  and  c<20:
    print("3<c and c<20")
if True: #布尔值
    print("True")

#双分支结构
num = input("请输入一个数字")
if int(num)<10:
     print(num)
else:
    print("数字太大")

#多分支结构,且elif顺序不能调换
score = int(input("请输入分数"))
grade = ''
if score<60 :
    grade = "不及格"
elif  score<80 :
    grade = "及格"
elif  score<90 :
    grade = "良好"
elif  score<=100:
    grade = "优秀"
print("分数是{0},等级是{1}".format(score,grade))

select structure nesting

       The selection structure can be nested. When using it, you must pay attention to controlling the indentation of different levels of code blocks, because the indentation determines the affiliation of the code.

 

score = int(input("请输入一个在0-100之间的数字:"))
grade = ""
if score>100 or score<0:
    score = int(input("输入错误!请重新输入一个在0-100之间的数字:"))
else:
     if score>=90:
        grade = "A"
     elif score>=80:
        grade = 'B'
     elif score>=70:
        grade = 'C'
     elif score>=60:
        grade = 'D'
     else:
        grade = 'E'
print("分数为{0},等级为{1}".format(score,grade))

Ternary conditional operator

   Python 's ternary operator, used in some simple double-branch assignment situations. The syntax of the ternary conditional operator is as follows:
The value if the condition is true if ( conditional expression ) else the value if the condition is false
 
num = input("请输入一个数字")
if int(num)<10:
     print(num)
else:
    print("数字太大")
#上面代码,可以用三元条件运算符实现:这种写法更加简洁,易读
num = input("请输入一个数字")
print( num if int(num)<999 else "数字太大")

 

 (3) Loop structure

     Loop constructs are used to repeatedly execute one or more statements. Express such logic: if the conditions are met, the statements in the loop body are executed repeatedly. After each execution, it will judge whether the condition is True , and if it is True , the statement in the loop body will be executed repeatedly. The diagram is as follows:
       The statements in the loop body should at least contain statements that change the conditional expression, so that the loop tends to end; otherwise, it will become an infinite loop.

 

while loop

The syntax of     while loop is as follows:
while conditional expression:
loop body statement

for loop 

  The for loop is often used to traverse iterable objects. The syntax of the for loop is as follows:
for   variable   in   iterable object:
loop body statement

Iterable object traversal

Python contains the following types of iterable objects:
1 sequence. Contains: Strings, Lists, Tuples, Dictionaries, Sets
2 iterator object ( iterator )
3 generator function ( generator )
4 file objects

range object

The range object is an iterator object used to generate a sequence of numbers within a specified range. The format is:
range ( start , end [, step ])
     The generated sequence of numbers starts from start and ends at end ( end is not included ). If start is not filled in , it will start from 0 by default . step is an optional step size, which defaults to 1 . Here are a few typical examples:
for i in range(10) produces the sequence: 0 1 2 3 4 5 6 7 8 9
for i in range(3,10) produces the sequence: 3 4 5 6 7 8 9
for i in range(3,10,2) produces the sequence: 3 5 7 9

 

break statement

        The break statement can be used in while and for loops to end the entire loop. When there are nested loops, the break statement can only jump out of the nearest loop.
 while True:
    a = input("请输入一个字符(输入Q或q结束)")
    if a.upper()=='Q':
        print("循环结束,退出") 
        break
    else:
        print(a)

 

continue statement

       The continue statement is used to end this loop and continue to the next one. When multiple loops are nested, continue is also applied to the nearest loop.

else statement
       while , for loops can be accompanied by an else statement (optional). If the for and while statements are not terminated by the break statement, the else clause will be executed, otherwise it will not be executed. The syntax format is as follows:

 while  conditional expression:

loop body
  else :
  statement block
or:
for   variable   in   iterable object:
loop body
else :
statement block

Guess you like

Origin blog.csdn.net/qq_63976098/article/details/131597279