python study notes (four)-process control

What is the purpose of learning the control process? The control flow can realize very complex code logic, it can realize more intelligent functions

Conditional statements

Python conditional statements are basically the same as other languages, and the code block to be executed is determined by the execution result (True or False) of one or more statements.

The Python programming language specifies any non-zero and non-null values ​​as True, and 0 or null as False.

Basic form of if statement

In Python, the basic form of an if statement is as follows:

if 判断条件:
    执行语句……
else:
    执行语句……

Python language has strict indentation requirements, so you also need to pay attention to indentation here, and don't miss the colon :

The judgment condition of if statement can be expressed by> (greater than), <(less than), == (equal to), >= (greater than or equal to), and <= (less than or equal to).
Example:

results=59
if results>=60:
    print ('及格')
else :
    print ('不及格')
 
 运行结果:
 不及格

As mentioned above, non-zero values, non-empty strings, non-empty lists, etc. are judged as True, otherwise it is False. So it can also be written like this:

num = 6
if num:
    print('Hello Python')
    
运行结果:
Hello Python

What if we numchanged to an empty string it?

if '':
    print('hello python')

Obviously, an empty string is False, the statement does not meet the conditions, it will not execute the print('Hello Python')code.

Note: In the condition judgment code colon :, the contents of the next line must be indented. If you don't indent, you will get an error. Colon and indentation is a kind of syntax. It will help Python distinguish the levels between codes and understand the logic and sequence of conditional execution.

The form of multiple judgment conditions in the if statement

Sometimes, we can’t have only two judgment sentences, and sometimes we need more than one. For example, in the above example, if the value is greater than 60, then we have to judge that the value greater than 90 is excellent, and the value between 80 and 90 is good. ?

At this time, multiple judgment conditions of the if statement are needed.

Syntax format:

if 判断条件1:
    执行语句1……
elif 判断条件2:
    执行语句2……
elif 判断条件3:
    执行语句3……
else:
    执行语句4……

Examples:

results = 89

if results > 90:
    print('优秀')
elif results > 80:
    print('良好')
elif results > 60:
    print ('及格')
else :
    print ('不及格')
运行结果:
良好

If statement multiple conditions are judged at the same time

What should we do when we encounter multiple conditions sometimes?

For example, when the test scores of java and python are required to be greater than 80 points, it is considered excellent. What should I do at this time?

At this time we can combine orand anduse.

or (or) means that the condition is successful when one of the two conditions is true

and (and) means that only when two conditions are met at the same time, the judgment condition is successful.

E.g:

java = 86
python = 68

if java > 80 and  python > 80:
    print('优秀')
else :
    print('不优秀')

if ( java >= 80  and java < 90 )  or ( python >= 80 and python < 90):
    print('良好')
    
输出结果:
不优秀
良好

Note: If there are multiple conditions, you can use parentheses to distinguish the order of judgment. The judgments in the parentheses are executed first. In addition, the priority of and and or is lower than the judgment symbols such as> (greater than), <(less than), that is, greater than and Less than if there are no parentheses, it will be judged first than and or.

if nested

What does if nesting mean?

Just like the literal meaning, it means that if statements can be nested in if statements.

For example, the example mentioned above can also be written with if nesting.

Example:

a = 81
b = 20

if a > 80:
    if b > 90:
        print('优秀')
    else:
        print('及格')
else:
    print('差')

输出结果:
及格

Of course, this is just to illustrate that if conditional statements can be nested. If this is the requirement, it is not recommended to use if nesting in this way, because the amount of code is too much, and the nesting is too much, and it is not convenient to read the code.

By default, it is executed from top to bottom, and the whole scan is performed first, and it will be executed if there is no syntax error.

Code example:

a=int(input('请输入您的身高(cm):'))
if a>=179:
    print('男神身高')
elif a == 178:
	print('标准身高')
elif 160 < a < 178:
	print('中等身高')
else:
	print('身高不可说')

运行示例:
请输入您的身高(cm)181
男神身高

Trinocular operation (syntactic sugar)

Syntactic sugar: Sugar-coated grammar British computer scientist Peter John Landa, generally speaking, the use of syntactic sugar can increase the readability of the program, thereby reducing the chance of program code errors.

Syntax format: 值1 if 判断语句 else 值2
(Explanation: the statement holds the execution value 1 does not hold the execution value 2)

a = 4
if a > 5:
    print(True)
else:
    print(False)
    
# 三目运算符 
print(True) if a>5 else print(False)
b = True if a > 5 else False

执行结果:
False
False

# 糖->节省代码格式
# 装饰器

loop statement

General programming languages ​​have loop statements. Why?
Then ask yourself, what are we doing with the program?
It must be to facilitate our work and optimize our work efficiency. Computers are different from human beings. Computers are neither afraid of hardship nor tired, nor do they need to rest, and they can keep doing it. You have to know that computers are best at doing repetitive things. So at this time we need to use loop statements, loop statements allow us to execute a statement or statement group multiple times.

Python provides for loop and while loop.
There is another problem here. What should I do if I want it to stop after running a hundred times?
At this time, you need to use some statements to control the loop:

Loop control statement description
break Terminate the loop, and jump out of the entire loop
continue Terminate the current loop, jump out of this loop, and execute the next loop
pass pass is an empty statement to maintain the integrity of the program structure

These control statements are for us to tell the program when to stop and when not to run the loop.

while loop

The function of the while loop is the same as the for loop.

Let's first take a look at what the While loop statement looks like.

# 计算1-100 的和。高斯求和
count = 1
sum1 = 0
while count<=100:
    sum1 = sum1+ count
    count = count + 1
print(sum1)

执行结果:
5050

while loop nested syntax

while expression:
   while expression:
      statement(s)
   statement(s)

Sometimes, we only want to count the sum of odd numbers between 1 and 100. That is to say, when count is an even number, that is, a double number, we need to jump out of the current loop and don’t want to add it. At this time, we can use break. E.g:

count = 1
sum = 0
while (count <= 100):
    if ( count % 2 == 0):  # 双数时跳过输出
        count = count + 1
        continue
    sum = sum + count
    count = count + 1
print(sum)

执行结果:
2500

for iteration loop

Basic syntax format:

for iterating_var in sequence:
   statements(s)
#sequence:可迭代对象

Then we can write an example to test it according to this basic grammatical format:

for i in 'hello':
    print(i)

执行结果:
h
e
l
l
o

From the printing results, it is to string helloa character printed.

What if we change the string to a dictionary dict?

dict1 = {
    
    'name':'李四','age':'18','from':'福建'}
for i in dict1:# i 是key
    print(i+':',dict1[i])

执行结果:
name: 李四
age: 18
from: 福建

for traverse the list to double-element instance:

#取列表值——遍历列表
#双元素
l = [(1, 2), (3, 4), (5, 6)]
for x, y in l:
    print(x, y)

l = [(1, 2), (3, 4), (5, 6)]
for x, y in enumerate(l):
    print(x, y)

执行结果:
1 2
3 4
5 6
0 (1, 2)
1 (3, 4)
2 (5, 6)

for loop nested syntax

Examples:

for num in range(10,15):  # 迭代 10 到 20 之间的数字
   for i in range(2,num): # 根据因子迭代
      if num%i == 0:      # 确定第一个因子
         j=num/i          # 计算第二个因子
         print ('%d 是一个合数' % num)
         break            # 跳出当前循环
   else:                  # 循环的 else 部分
      print ('%d 是一个质数' % num)

执行结果:
10 是一个合数
11 是一个质数
12 是一个合数
13 是一个质数
14 是一个合数

Of course, there is also used the for … elsestatement.

In fact, the statements in the for loop are no different from ordinary ones. The statements in the else will be executed after the loop is executed normally (that is, the statements in the else will not be executed when the for terminates the loop through break).

Of course there for … elsewill be while … else. They all mean the same thing.

range() function

The or loop is often used in conjunction with the range() function.

If you don't know the range() function, we can understand it directly through a program.

for i in range(3):
    print(i)

执行结果:
0
1
2

Using the range(x) function, you can generate a sequence of integers from 0 to x-1.

If it is range(a,b)a function, you can generate a sequence of integers a closed left and right open.

In fact, in the example range(3)it can be written range(0,3), the result is the same.

In fact, we use the range() function to run a piece of code repeatedly n times.

Here is a question. You carefully observe the range() function. What are the common characteristics of the one-parameter or two-parameter ones mentioned above?

I don’t know if you have found out that it increments by 1 each time.

range(3) That is, 0, 1, 2, and increment by 1 each time.

range(3,6) That is, 3, 4, and 5 are incremented by 1 each time.

Can it not increment by 1 every time?

For example, I want to increment by 2?

In the preparation of the program, you will definitely encounter such a demand. And since the development of python, the range function will certainly have this kind of function.

So the range function also has a three-parameter.

For example range(0,10,2), it means: counting from 0 to 10 (not taking 10), with an interval of 2 each time.

The difference between for loop and while loop

As mentioned before, if one grammar can express a function, there is no need to use two grammars to express it.

Since they are both loops, there must be a difference between for loops and while loops.

When do you use for loops and while loops?

  • The for loop is mainly used when iterating over an iterable object.
  • The while loop is mainly used in the case of repeated execution that needs to meet certain conditions to be true. (Infinite loop + break exit, etc.)
  • In some cases, for loops and while loops can be used interchangeably.

Examples of for and while can be used interchangeably:

for i in range(0, 10):
    print(i)


i = 0
while i < 10:
    print(i)
    i = i + 1

Case study

1. Print the nine-nine multiplication table

# 打印九九乘法表
for i in range(1, 10):
        for j in range(1, i+1):
            # 打印语句中,大括号及其里面的字符 (称作格式化字段) 将会被 .format() 中的参数替换,注意有个点的
            print('{}x{}={}\t'.format(i, j, i*j), end='')  
        print() #这里有换行的意思

Results of the:

1x1=1	
2x1=2	2x2=4	
3x1=3	3x2=6	3x3=9	
4x1=4	4x2=8	4x3=12	4x4=16	
5x1=5	5x2=10	5x3=15	5x4=20	5x5=25	
6x1=6	6x2=12	6x3=18	6x4=24	6x5=30	6x6=36	
7x1=7	7x2=14	7x3=21	7x4=28	7x5=35	7x6=42	7x7=49	
8x1=8	8x2=16	8x3=24	8x4=32	8x5=40	8x6=48	8x7=56	8x8=64	
9x1=9	9x2=18	9x3=27	9x4=36	9x5=45	9x6=54	9x7=63	9x8=72	9x9=81	

2. Determine whether it is a leap year

# 判断是否是闰年
year = int(input("请输入一个年份: "))
if (year % 4) == 0 and (year % 100) != 0 or (year % 400) == 0:
    print('{0} 是闰年' .format(year))
else:
     print('{0} 不是闰年' .format(year))

Execution example results:

请输入一个年份: 2020
2020 是闰年

Guess you like

Origin blog.csdn.net/qq_46485161/article/details/115269418