[Python study notes] 10 most complete summary of control statements

This series of notes for learning Python for yourself, if there are errors, please correct me

Select result

The selection structure determines which branch to execute by judging whether the condition is true. There are many forms of selection structure, divided into: single branch, double branch, and multiple branches. The flow chart is as follows:

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-9jFYUifK-1610702861337)(.\images\image-20210115152646962.png)]

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-RcXKw5zK-1610702861353)(.\images\image-20210115152744007.png)]

Single branch selection structure

The grammatical form of the single branch result of the if statement is as follows:

if conditional expression:

​ Statement/Block

among them:

  1. Conditional expressions: can be logical expressions, relational expressions, arithmetic expressions, etc.
  2. Statement/statement block: It can be one statement or multiple statements. Multiple statements, indentation must be aligned
num = input('请输入一个数字:')
if int(num)<10:
    print(num)

Detailed Explanation of Conditional Expressions

In the selection and loop structure, the value of the conditional expression is False as follows:

False 0 0.0 Null value None, empty sequence object (empty list, empty set, empty dictionary, empty string), empty range object, empty iteration object

All other cases are True.

if 3: #整数作为条件表达式
    print('ok')    
    
a = [] #列表作为表达式 空列表为False
if a:
    print('空列表 False')    
    
s = 'False' #非空字符串
if s:
    print('非空字符串')    
    
c = 9
if 3<c and c<20:
    print("3<c and c<20")


if True: #布尔值
    print("True")  

Conditional expressions cannot have assignment operators =

Double branch selection structure

if conditional expression:

​ Statement block/statement

else:

​ Statement

num = input('请输入一个数字')
if int(num)<10:
    print(num)
else:
    print('数字太大')    

Ternary conditional operator

Python provides a ternary operator, used in some simple double-branch assignment situations, the ternary conditional operator syntax:

The value if the condition is true if (conditional expression) else the value when the condition is false

num = input('请输入一个数字')
print(num if int(num)<10 else '数字太大')  

Multi-branch selection structure

if conditional expression 1:

​ Statement/Block

elif conditional expression 2:

​ Statement/Block

else:

​ Statement/Block

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-zI3Enszj-1610702861355)(.\images\image-20210115160316557.png)]

score = int(input('请输入分数'))
grade = ''
if score<60:
    grade = '不及格'
elif score>=60 and score<70:
    grade='及格'
elif score>=70 and score<80:
    grade = '良好'   
else:
    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 subordination of the code.

if expression 1:

​ Statement block 1

​ if expression 2:

​ Statement block 2:

​ else:

​ Statement block

else:

​ Statement block

Cyclic structure

The loop structure is used to repeatedly execute one or more statements. Expression logic: If the conditions are met, the statements in the loop body are executed repeatedly. After each execution, it will be judged whether the condition is True, and if it is True, the loop will be repeated.

[External link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-IIricoFW-1610702861357)(.\images\image-20210115161743080.png)]

The statement in the loop body should at least contain a statement that changes the conditional expression, so that the loop tends to end, otherwise, it will become an endless loop.

while loop

while 判断条件(condition):
 执行语句(statements)……
n = 100
 
sum = 0
counter = 1
while counter <= n:
    sum = sum + counter
    counter += 1
 
print("1 到 %d 之和为: %d" % (n,sum))

Infinite loop

We can achieve an infinite loop by setting the conditional expression to never be false

var = 1
while var == 1 :  # 表达式永远为 true
   num = int(input("输入一个数字  :"))
   print ("你输入的数字是: ", num)
 
print ("Good bye!")

You can use CTRL+C to exit the current infinite loop.

The infinite loop is very useful for real-time client requests on the server.

for loop and iterable object traversal

The for loop is usually used to traverse an iterable object. The syntax format of for loop is as follows:

for variable in iterable object:

​ Loop body statement

Iterable object

  1. Sequence: the ancestor of a list of strings
  2. dictionary
  3. Iterator alignment
  4. Generator object
for x in list('slp'):
    print(x)
    
d = {
    
    'name':'slp','age':18,'address':'bj'}
for x in d: #遍历所有的key
    print(x)
    
for x in d.keys():#遍历字典所有的key
    print(x)
    
for x in d.values():#遍历字典所有的value
    print(x)
        
for x in d.items():#遍历字典所有的键值对
    print(x)    
    

range object

The range object is an iterator object that uses a sequence of numbers to generate a specified range. The format is: range(start,end [,step])

    
sum_all=0
sum_even=0
sum_odd=0
for num in range(101):
    sum_all +=num
    if num%2 ==0:
        sum_even+=num
    else:
        sum_odd+=num
        
print(sum_all,sum_even,sum_odd)    

Nested loop

A loop can be embedded in another loop, generally called a nested loop, or multiple loops

eg: print 99 multiplication table:

for m in range(1,10):
    for n in range(1,m+1):
        print(m,'*',n,'=',m*n ,end='\t')
    print('')
    

break statement

The break statement can be used in while and for loops to end the entire loop. When there is nesting, the break statement can only jump out of the nearest loop

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-nB6cRFES-1610702861364)(.\images\E5A591EF-6515-4BCB-AEAA-A97ABEFC5D7D.jpg)]

while True:
    a = input('输入Q退出')
    if a.upper() == 'Q':
        print('退出')
        break
    else:
        print('继续')

continue statement

continue is used to end this loop and continue to the next time. The nesting is also the application and the most recent loop.

[External link image transfer failed. The origin site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-aqfENPtv-1610702861366)(.\images\8962A4F1-B78C-4877-B328-903366EA1470.jpg)]

n = 5
while n > 0:
    n -= 1
    if n == 2:
        continue
    print(n)
print('循环结束。')
empNum = 0
salarySum = 0;
salarys = []       
while True:
    s = input('请输入员工的工资(q或Q结束)')
    if s.upper() =='Q':
        print('录入完成 退出')
        break;
    if float(s)<0:
        continue;
    empNum+=1
    salarys.append(float(s))
    salarySum +=float(s)
    
print('员工数{0}'.format(empNum))
print('录入薪资',salarys)
print('平均薪资{0}'.format(salarySum/empNum))

pass statement

Python pass is an empty statement to maintain the integrity of the program structure.

pass does not do anything, it is generally used as a placeholder statement,

Loop code optimization

  1. Minimize unnecessary calculations inside the loop
  2. In the nested loop, try to reduce the count of the inner loop, and lift it outward as much as possible
  3. Local variable query is faster, try to use local variables

Other optimization methods

  1. Concatenate multiple strings, use join instead of +
  2. Insert and delete elements in the list, try to operate at the end

Use zip() to iterate in parallel

We can use the zip() function to iterate multiple sequences in parallel, and the zip() function will stop when the shortest sequence is used up

names = ('a','b','c')
ages =(16,10)
jobs = ('teacher','programmer','drive')
for name,age,job in zip(names,ages,jobs):
    print("{0}--{1}--{2}".format(name,age,job))

Search [Zixin] on WeChat or scan the QR code below to make friends and make progress together. The article is continuously updated. At present, I am organizing the study notes of Python hundred battles, and I look forward to more updates in the future.

Guess you like

Origin blog.csdn.net/weixin_51656605/article/details/112680115