# 1, Operator

## 1.1 + -- addition of two objects

+Operator is used to add two objects.

[example 1] number addition. In Python, we often use + to add values. Common applications are as follows:

```a = 13
b = 2
c = 4.0
d = 5.0
print(a + b)  # Add integers 15
print(c + d)  # Floating point number addition 9.0
print(a + c)  # Add integer and floating point numbers 17.0
print(a + .5)  # Add integers and floating-point numbers with zero omitted 13.5
```

[example 2] string addition. If the + on both sides of the string represents two data types in Python. Common applications are as follows:

```s1 = 'Amo'
s2 = 'Xiang'
print(s1 + s2)  # String splicing
print(s1 + ' ' + s2)  # Add space between 2 strings
print(s1 + '\n' + s2)  # Add line breaks between 2 strings
```

The program execution results are shown in the following figure:

[example 3] addition of tuples and lists. When tuples and lists are added with + to return the combined tuples and lists. Common applications are as follows:

```t1 = (1, 2, 3)
t2 = (4, 5, 6)
t3 = ('a', 'b', 'c')
t4 = ('d', 'e', 'f')
t5 = (('o', 'p', 'q'), ('x', 'y', 'z'))
print(t1 + t2)  # (1, 2, 3, 4, 5, 6)
# (1, 2, 3, 4, 5, 6, 'a', 'b', 'c', 'd', 'e', 'f')
print(t1 + t2 + t3 + t4)
# (1, 2, 3, 4, 5, 6, 'a', 'b', 'c', 'd', 'e', 'f', ('o', 'p', 'q'), ('x', 'y', 'z'))
print(t1 + t2 + t3 + t4 + t5)

print("*" * 90)
l1 = [1, 2, 3]
l2 = [4, 5, 6]
l3 = [['a', 'b', 'c']]
l4 = [['d', 'e', 'f']]
l5 = [['o', 'p', 'q'], ('x', 'y', 'z')]
print(l1 + l2)  # [1, 2, 3, 4, 5, 6]
# [['a', 'b', 'c'], ['d', 'e', 'f']]
print(l3 + l4)
# [1, 2, 3, 4, 5, 6, ['a', 'b', 'c'], ['d', 'e', 'f'], ['o', 'p', 'q'], ('x', 'y', 'z')]
print(l1 + l2 + l3 + l4 + l5)
```

Note: dictionaries and collections cannot be operated with "+".

## 1.2 - get a negative number or subtract one number from another

-The operator has two functions in Python. One is to use it as a negative sign to represent a negative number before a number; The other is used as a minus sign, which means the previous number minus the next one.

[example 1] is used as a minus sign. When used as a minus sign, note that negative is positive. Common applications are as follows:

```num1 = 4
num2 = -5
num3 = -6.0
print(-num1)  # -4
print(num2)  # -5
print(-num3)  # 6.0
```

[example 2] is used as a minus sign. When used as a minus sign, common applications are as follows:

```num1 = 5
num2 = 1
num3 = 10
num4 = 8.0
print(num1 - num2)  # 4
print(num1 - num3)  # -5
print(num1 - num4)  # -3.0
```

## 1.3 * -- multiply two numbers or return a string, list or tuple repeated several times

*The operator has two functions in Python. One is used as a multiplier, which means that two numbers are multiplied; The other is combined with integer n, which is used as a repetition symbol to represent that strings, lists and tuples are repeated N times.

[example 1] used as a multiplier. When used as a multiplier, common applications are as follows:

```num1 = 3
num2 = 4
num3 = 5.5
num4 = -6
print(num1 * num2)  # 12
print(num1 * num3)  # 16.5
print(num1 * num4)  # -18
```

[example 2] use * sign for string. Use "*" as the repetition symbol to print an isosceles triangle. The code is as follows:

```print(' ' * 2 + '*' + ' ' * 2)
print(' ' + '*' * 3 + ' ')
print('*' * 5)
```

[example 3] use the * sign for tuples. The "*" sign, as a repeating symbol, can also act on tuples.

```l1 = (1, 2, 3)
l2 = (('a', 'b', 'c'), ('d', 'e', 'f'))
# (1, 2, 3, 1, 2, 3, 1, 2, 3)
print(l1 * 3)
# (('a', 'b', 'c'), ('d', 'e', 'f'), ('a', 'b', 'c'), ('d', 'e', 'f'))
print(l2 * 2)
```

[example 4] use the * sign for the list. The "*" sign, as a repeating symbol, can also act on the list.

```l1 = [1, 2, 3]
l2 = [['a', 'b', 'c']]
board = [['-'] * 3 for i in range(3)]  # Use list parsing
# [1, 2, 3, 1, 2, 3, 1, 2, 3]
print(l1 * 3)
# [['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]
print(l2 * 3)
# [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]
print(board)
```

## 1.4 / -- division of two numbers

/Operator is used to divide two objects.

[example 1] realize the conversion between RMB and USD. It is known that 1 US dollar is converted into RMB 6.78 yuan, and the program is written to realize the function of converting RMB into US dollars. The code is as follows:

```exchange_rate = 6.78  # exchange rate
RMB = input('Please enter RMB amount:')
try:
US = float(RMB) / exchange_rate
print('The converted dollar is:{:.2f}'.format(US))
except ValueError:
print('Please enter the correct value type.')
```

The program execution results are shown in the following figure:

## 1.5 / / - returns the integer part of the quotient (rounded down)

//The operator is used for integer division and returns the integer part of the quotient. Pay attention to rounding down. For example, 8 / / 3 = 2.

[example 1] convert the description "seconds" into "minutes and seconds". In the examination system, the user's answer time needs to be recorded. Usually, the answer time is recorded in seconds. For example, it takes "100" seconds. In order to increase readability, you need to convert "100 seconds" into "1 minute 40 seconds". The following code can realize this function:

```def second_format(seconds):
minutes = seconds // 60 # count minutes
if minutes > 0:
seconds = seconds - minutes * 60  # Calculate seconds remaining
return minutes, seconds

i = 2
while i > 0:
seconds = input('Please enter the number of seconds:')
result = second_format(int(seconds))
print(f'{seconds}Seconds can be converted into{result[0]}branch{result[1]}second')
i -= 1
```

The program execution results are shown in the following figure:

[example 2] count the memory occupied by the program. Psutil is a cross platform library module, which can easily obtain the process of system operation and system utilization, including CPU, memory, disk, network and other information. Use the "pip install psutil" command to install the psutil module, then count the memory occupied by the program and convert it into MB unit size. The code is as follows:

```import os
import psutil

def show_memory_info(hint):
"""Show current Python Amount of memory occupied by the program"""
pid = os.getpid()
p = psutil.Process(pid)
info = p.memory_full_info()
memory = info.uss / 1024. / 1024  # 1MB = 1024KB = 1024B
print('{} memory used: {} MB'.format(hint, memory))

# How much memory does the test function occupy
show_memory_info('initial')
list_val = [i for i in range(10000000)]
show_memory_info('finished')
```

The program execution results are shown in the following figure:

## 1.6% - returns the remainder of division

%Operator is used to take modulus and return the remainder of division. For example, 8% 2 results in 0 and 8% 3 results in 2.

[example 1] negative numbers use% to find the remainder. Calculate the following division result:

```result1 = 8 % 3
result2 = -8 % 3
result3 = 8 % -3
result4 = 0 % -3  # 0
result5 = 0 % 6  # 0
print(f"8  % 3 The results are:{result1}")  # 2
print(f"-8 % 3 The results are:{result2}")  # 1
print(f"8 % -3 The results are:{result3}")  # -1
```

The above result may not meet the expectations of many people. This result is determined by Python mechanism. In Python, the remainder follows the following formula:

```r=a-n*(a//n)
# r=a-n*(a//n)
# 8 % 3 ==> a=8,n=3 ==> 8-3*(8//3) ==> 8-3*2 ==> 2
# Note: - 8 / / 3 rounding down during calculation, the result is - 3 instead of - 2.
# -8 % 3 ==> a=-8,n=3 ==> -8-3*(-8//3) ==> -8-3*(-3) ==> -8+9 ==> 1
# 8 % -3 ==> a=8,n=-3 ==> 8-(-3)*(8//-3) ==> 8+3*(-3) ==> 8-9 ==> -1
```

## 1.7 * * -- returns the power of a number

**Operator is used to return the power of a number. For example, 2 * * 2 results in 4 and 2 * * 3 results in 8.

[example 1] find the y power of x in three ways.

```import math

# Calculate the y-power of x
x = 10
y = 3
# Mode 1
print(x ** y)  # 1000
# Mode 2
print(pow(x, y))  # 1000
# Mode 3
print(math.pow(x, y))  # The return type is floating point type: 1000.0
```

## 1.8 = -- simple assignment

=Is a simple assignment operator. For example, a=1 means that the value 1 is assigned to the variable a.

[example 1] assignment of different types of data.

```# Common data type assignment
num = 123  # numerical value
str_val = "Amo"  # character string
tuple_val = (1, 2, 3)  # tuple
list_val = [1, 2, 3]  # list
dict_val = {"name": "Amo", "age": 18}  # Dictionaries
set_val = {1, 2, 3}  # aggregate

def fun():
print("Function assignment")

f = fun  # Function assignment
f()  # Calling function: function assignment

class Student:

def __init__(self):
print("Class assignment")

s = Student  # Class assignment
s()  # Class instantiation: class assignment
```

## 1.9 + = -- additive assignment

+=Is an additive assignment operator. For example, a +=1 is equivalent to a=a+1.

[example 1] calculate the cumulative sum of the values in the dictionary.

```basket = {"fruit": 45.80, "meat": 20.45, "juice": 10}  # Shopping cart data
total = 0  # Initial total price
# Mode 1:
total += item
print(f'The calculation result of mode 1 is{total}')
# Mode 2:
print(f'The calculation result of mode 2 is{total}')
```

[example 2] automatically convert numbers 0-9 into Chinese characters.

```numbers = input("Please enter 0-9 Number between:")
digits_mapping = {
"0": "Fatal Frame",
"1": "one",
"2": "two",
"3": "three",
"4": "four",
"5": "five",
"6": "land",
"7": "seven",
"8": "eight",
"9": "nine",
}

output = ""
for number in numbers:  # Traverse the input number
output += digits_mapping.get(number, "!") + " "  # Match the keys of the dictionary, and then connect the results together
print(output)
```

## 1.10 - = -- subtraction assignment

-=It is a subtraction assignment operator, similar to the addition operator. For example, a -=1 is equivalent to a=a-1.

[example 1] "every seven" game. "Every seven" is a puzzle game to exercise mental agility. The rule of the game is that everyone forms a circle, and then shout the number in order from 1. If the number is 7 or a multiple of 7, you can't shout the number, and you must do an action. Use Python to calculate the multiple of 7 within 200. For example, 7, 14, 28, etc. The code is as follows:

```value = 200  # Initial value
L = []
while value > 0:
if value % 7 == 0:  # If divided by 7
value -= 1
L.reverse()  # List inversion
print(L)  # Output list
```

## 1.11 * = -- multiplication assignment

"* =" is a multiplication assignment operator, similar to the addition operator. For example, a *=3 is equivalent to a = a*3.

[example 1] multiple types use multiplication assignment. The multiplication assignment operation is used for different types of data, and the code is as follows:

```# number
num = 5
num *= 3
print(num)  # 15
# character string
str_val = "Amo"
str_val *= 3
print(str_val)  # AmoAmoAmo
# tuple
tuple_val = (1, 2, 3)
tuple_val *= 3
print(tuple_val)  # (1, 2, 3, 1, 2, 3, 1, 2, 3)
# list
list_val = [1, 2, 3]
list_val *= 3
print(list_val)  # [1, 2, 3, 1, 2, 3, 1, 2, 3]
```

[example 2] calculate the number of wheat needed to fill up chess. Chess has a total of 64 squares. If you put one grain of wheat in the first small space, two grains in the second small space, and four grains in the third small space, and so on, each small space will add twice as much wheat as the previous small space until 64 squares are filled, how many grains are needed in total. The code is as follows:

```def getNumberOfWheat(grid):
"""
Get put grid Wheat number in grid time
:param grid: Lattice number
:return: Returns the amount of wheat when the grid is full
"""
g_sum = 0
numberOfWhearInGrid = 1  # Place 1 grain in the first grid
g_sum += numberOfWhearInGrid  # Total number of grains in the first lattice
for i in range(2, grid + 1):  # Start from the second grid and traverse each grid
numberOfWhearInGrid *= 2  # The next grid is twice as large as the previous one
g_sum += numberOfWhearInGrid  # Calculate the total number of grains in all grids
return g_sum

print(f"Need to fill 4 squares{getNumberOfWheat(4)}A piece of Wheat")  # Since the first grid is placed 1 by default, a total of 63 grids are calculated from the second
print(f'It takes 64 cells to fill{getNumberOfWheat(64)}A piece of Wheat')  # Since the first grid is placed 1 by default, a total of 63 grids are calculated from the second
```

## 1.12 / = -- division assignment operator

/=Is a division assignment operator. For example, a /=3 is equivalent to a = a/3.

[example 1] divide the elements in the list in batches in two ways.

```list_value = [1, 2, 3, 4, 5]
# Mode 1:
new_value = [i / 2 for i in list_value]  # Use list parsing
print(new_value)  # [0.5, 1.0, 1.5, 2.0, 2.5]
# Mode 2:
new_value = []
for i in list_value:
i /= 2  # Division assignment operation
new_value.append(i)  # Append to new list
print(new_value)  # [0.5, 1.0, 1.5, 2.0, 2.5]
```

## 1.13% = -- modulo assignment operator

%=Is a modulo operator. For example, a% = 3 is equivalent to a = a%3.

[example 1] batch module of elements in the list.

```list_value = [10, 11, 12, 13, 14, 15]
new_value = []
for i in list_value:
i %= 2  # Modular operation
val = 'Odd number' if i else 'even numbers'  # Ternary expression
new_value.append(val)  # Append to new list
print(new_value)  # ['even', 'odd', 'even', 'odd', 'even', 'even', 'odd']
```

## 1.14 * * = -- power assignment operator

"* * =" is a power assignment operator. For example, a **= 3 is equivalent to a = a**3.

[example 1] square the elements in the list in batches in three ways.

```list_value = [1, 2, 3, 4, 5]
# Mode 1:
new_value = [i ** 2 for i in list_value]  # Use list parsing
print(new_value)  # [1, 4, 9, 16, 25]
# Mode 2
new_value = []
for i in list_value:
i **= 2  # Power assignment operation
new_value.append(i)  # Append to new list
print(new_value)  # [1, 4, 9, 16, 25]
# Mode 3
new_value = list(map(lambda x: x ** 2, list_value))
print(new_value)  # [1, 4, 9, 16, 25]
```

## 1.15 / / = -- Take integer division assignment operator

"/ / =" is an integer division assignment operator. For example, a //= 3 is equivalent to a = a//3.

[example 1] batch integer assignment of elements in the list in three ways

```list_value = [1, 2, 3, 4, 5]
# Mode 1:
new_value = [i // 2 for i in list_value] # use list parsing
print(new_value)  # [0, 1, 1, 2, 2]
# Mode 2
new_value = []
for i in list_value:
i //= 2
new_value.append(i)  # Append to new list
print(new_value)  # [0, 1, 1, 2, 2]
# Mode 3
new_value = list(map(lambda x: x // 2, list_value))
print(new_value)  # [0, 1, 1, 2, 2]
```

## 1.16 = = -- equal operator

"= =" is an equal operator, which is used to compare whether objects are equal. Returns True if equal, False otherwise.

[example 1] = = operator is different from is. The "= =" operator is used to compare whether the values of objects are equal. If the values are equal, it returns True. However, it is necessary to judge whether the values are equal and the memory addresses are equal. The difference between them can be verified by the following code:

The intern mechanism has nothing to do with the length of the string. In the interactive mode, a new string will be applied for each line of string literal, but those containing only uppercase and lowercase letters, numbers and underscores will be interned, that is, a dict is maintained to make these strings globally unique. The above code needs to be input and run line by line at the Python command prompt, which is the above result. In pychart or IDLE, save the above code as a file and run it. The output is different. This is because the integer and string are stored as constants in pychar, so the assignment of the same integer in the same context will produce exactly the same result.

[example 2] if statement to determine whether they are equal.

```score = int(input('Enter score before:'))
if score == 100:
else:
```

## 1.17 != —— Not equal to operator

"! =" is an unequal operator, which is used to compare whether objects are unequal. Returns True if not equal, False otherwise.

[example 1] traverse the list and output information that is not equal to a certain value. Get the Chinese names of all companies in the company list whose English name is not "neusoft".

```list_val = [['neusoft', 'Neusoft Group Co., Ltd'],
['baidu', 'Baidu Online Network Technology Co., Ltd'],
['tencent', 'Shenzhen Tencent computer system Co., Ltd'],
['alibaba', 'Alibaba Network Technology Co., Ltd']]

list_new = []
for (name, val) in list_val:  # Traversal list
if name != "neusoft":  # Judgment is not equal to
list_new.append(val)  # Add to new list
# ['Baidu Online Network Technology Co., Ltd', 'Shenzhen Tencent computer system Co., Ltd', 'Alibaba Network Technology Co., Ltd.]
print(list_new)
```

## 1.18 > -- greater than operator

The ">" operator is used to compare object sizes. If the value of a is greater than b, a > b returns True, otherwise False.

[example 1] compare the size of number, string, tuple, list and set type data. The code is as follows:

```print(2 > 1)  # True
print(2.3 > 1.4)  # True
print('b' > 'a')  # True
print('abc' > 'abb')  # True
print((1, 2, 3) > (1, 2, 2))  # True
print([1, 2, 3] > [1, 2, 2])  # True
print({1, 2, 3} > {1, 2, 2})  # True
"""Note: when comparing the size, first compare the first element, ASCII Elements with large code values are relatively large. If the first element is the same, compare the second element, and so on."""
```

[example 2] judge whether the elevator is overloaded. It is known that the elevator is limited to 6 people. When there are more than 6 people, please prompt the overload information and the number of overloaded people. The code is as follows:

```person = ['Andy', 'Kobe', 'Jack', 'Jim', 'Mark', 'Tim', 'Bob']  # Elevator member list
stander_number = 6  # Elevator load number
number = len(person)  # Get the number of people in
if number > stander_number:  # If the number of people in the elevator exceeds the load
else:
print('Meet the requirements')
```

## 1.19 < -- less than operator

The '<' operator is used to compare object sizes. If the value of a is less than b, a < b returns True, otherwise False.

[example 1] convert reverse order index into positive order index. When slicing a sequence, it can be sliced in positive order or reverse order. Write a function to calculate the position of the index in reverse order in positive order. The code is as follows:

```def fixIndex(object, index):
if index < 0:
# If the index is on the right, convert it to the left
index += len(object) + 1
return index

list_val = [1, 2, 3, 4, 5]
index1 = fixIndex(list_val, -1)
index2 = fixIndex(list_val, -2)
index3 = fixIndex(list_val, -3)
index4 = fixIndex(list_val, -4)
index5 = fixIndex(list_val, -5)
print(f'The penultimate is the positive number{index1}individual')
print(f'The penultimate is the positive number{index2}individual')
print(f'The penultimate number is the positive number{index3}individual')
print(f'The penultimate number is the positive number{index4}individual')
print(f'The penultimate number is the positive number{index5}individual')
```

[example 2] get the smallest element in the list. In a list of all numbers, get the element with the lowest value. The code is as follows:

```numbers = [3, 6, 2, 8, 4, 10]
min_num = numbers[0]
for number in numbers:
if number < min_num:
min_num = number
print(f'The smallest element in the list is{min_num}')
```

## 1.20 > = -- greater than or equal to operator

The "> =" operator is used to compare object sizes. If the value of a is greater than or equal to b, a > = b returns True, otherwise False.

[example 1] judge whether the examination result is passed. The passing score of Chinese examination is 60 points. If the score is greater than or equal to 60 points, the score will pass, otherwise the score will fail. The code to realize this function is as follows:

```score = float(input('Please enter your score:'))
if score >= 60:
print('Congratulations, you passed the exam!')
else:
print('Unfortunately, I didn't pass the exam')
```

## 1.21 < = -- less than or equal to operator

The "< =" operator is used to compare object sizes. If the value of a is less than or equal to b, a < = b returns True, otherwise False.

[example 2] obtain even numbers in two ways.

```# Method 1: use list parsing formula
list_val = [i for i in range(21) if i % 2 == 0]
print(list_val)
# Method 2: use loop traversal
list_val = []
num = 0
while num <= 20:
if num % 2 == 0:  # Judge whether it can be divided by 2
list_val.append(num)  # Append even numbers to list
num += 1  # Variable self increment
print(list_val)
```

## 1.22 and -- and operator

The "and" operator is used to represent a logical and. For example, opt1 and opt2, if both opt1 and opt2 are True, return True; otherwise, return False.

[example 1] judge whether the elevator is overloaded.

```num = int(input('Please enter the number of people:'))
weight = float(input('Please enter the total weight:'))
if num <= 10 and weight <= 1000:
print('The elevator operates normally')
else:
```

## 1.23 or -- or operator

The 'or' operator is used to represent a logical or. For example, opt1 or opt2, if both opt1 and opt2 are no, it returns False, otherwise it returns True.

[example 1] use the or operator to judge the data outside a certain interval.

```num = float(input('Please enter the product sales volume:'))
if num > 500 or num < 20:
print('This product needs special attention!')
else:
print('The sales volume of this product is stable!')
```

## 1.24 not -- non operator

The 'not' operator is used to represent a logical non. For example, not opt returns True if opt is False and False if opt is True.

[example 1] judge whether the input value is an integer.

```str_val = input('please enter an integer:')
if not str_val.isdigit():
print('Format error')
else:
print(f'The integer you entered is{str_val}')
```

## 1.25 & -- bitwise and operator

Bitwise and operator: two values involved in the operation. If both corresponding bits are 1, the result of this bit is 1, otherwise it is 0.

[example 1] output the result of bitwise AND.

```a = 0b00111100
b = 0b00001101
# Note: the result of a & B is 0000 1100, which is converted to decimal 12.
print(a & b)  # 12
```

## 1.26 | -- bitwise OR operator

Bitwise OR operator: as long as one of the corresponding two binary bits is 1, the result bit is 1.

[example 1] output the result of bitwise OR.

```a = 0b00111100
b = 0b00001101
# Note: the result of a|b is 0011 1101, which is converted to decimal 61.
print(a | b)  # 61
```

## 1.27 ^ -- bitwise XOR operator

Bitwise exclusive or operator: when two corresponding binary bits are different, the result is 1.

[example 1] output the result of bitwise XOR.

```a = 0b00111100
b = 0b00001101
# Note: the result of a^b is 0011 0001, which is converted to decimal 49.
print(a ^ b)  # 49
```

## 1.28 ~ -- bitwise negation operator

Bitwise negation operator: negates each binary bit of data, that is, changes 1 to 0 and 0 to 1~ x is similar to - x-1.

[example 1] output the result of bit inversion.

```a = 0b00111100
# Note: the result of ~ a is 1100 0011, which is converted into complement 10111101 and decimal - 61.
print(~a)  # -61
```

## 1.29 < < -- move left operator

Move left operator: all binary bits of the operand are shifted to the left by several bits. The number of bits to be moved is specified by the number to the right of "< <". The high bit is discarded and the low bit is supplemented by 0.

[example 1] output the result of left movement operation.

```a = 0b00111100
# Note: shift Y bits left on the number x to get x * (2**y).
print(f'a The value of is{a}')  # The value of a is 60
print(f'a The result of moving 2 bits is{a << 2}')  # 240
print(f'a The result of moving 3 bits is{a << 3}')  # 480
```

## 1.30 > > -- move right operator

Move right operator: shift all binary bits of the operand on the left of "> >" by several bits to the right, and the number on the right of "> >" specifies the number of bits to move. If the sign bit is 0, the high bit is filled with 0 after moving to the right. If the sign bit is 1, the high bit is filled with 1.

[example 1] output the result of right movement operation.

```a = 0b00111100

# Note: shift Y bits right on the number x to get x / (2**y). Here is the quotient, not the remainder.
print(f'a The value of is{a}')  # 60
print(f'a The result of moving 2 bits is{a >> 2}')  # 15
print(f'a The result of moving 3 bits is{a >> 3}')  # 7
```

## 1.31 in -- find in the specified sequence

"In" operator means that it returns True if a value is found in the specified sequence, otherwise it returns False.

[example 1] judge whether the character is in the string.

```str_val = 'AmoXiang'
print('A' in str_val)  # True
print('Am' in str_val)  # True
print('ma' in str_val)  # False
```

[example 2] judge whether an element is in a tuple.

```tuple_val = (1, (2, 3), 4, 5)
print(1 in tuple_val)  # True
print((4, 5) in tuple_val)  # False
print((2, 3) in tuple_val)  # True
```

[example 3] judge whether the element is in the list.

```list_val = [1, (2, 3), 4, 5]
print(2 in list_val)  # False
print([4, 5] in list_val)  # False
print((2, 3) in list_val)  # True
```

[example 4] judge whether the element is in the dictionary.

```dict_val = {'name': 'Amo', 'age': 18}
print('name' in dict_val)  # True
print('age' in dict_val)  # True
print('Amo' in dict_val)  # False
```

[example 5] judge whether the element is in the set.

```set_val = {1, 2, 3, 'Amo', (1, 2, 3)}
print(1 in set_val)  # True
print((1, 2) in set_val)  # False
print('Amo' in set_val)  # True
print((1, 2, 3) in set_val)  # True
```

## 1.32 not in -- find in the specified sequence

"not in" operator means that it returns True if no value is found in the specified sequence, otherwise it returns False. It is the inverse of the "in" operator.

[example 1] delete duplicate elements in the list.

```numbers = [2, 2, 4, 6, 3, 4, 6, 1]
uniques = []
for number in numbers:
if number not in uniques:
uniques.append(number)
# [2, 4, 6, 3, 1]
print(uniques)
```

[example 2] judge whether the string information is legal. When registering the website, users are required to fill in the three fields of "real name", "mobile phone number" and "password". Use the "not in" operator to judge whether the registration information filled in by the user is correct. The code is as follows:

```res = []
# Judge whether it is completely filled in
if 'truename' not in res or 'phone' not in res or 'password' not in res:
print('You must fill in your real name, mobile phone number and password')
```

## 1.33 is -- judge whether two identifications are from the same object

Is is to judge whether two identifiers refer to an object. Returns True if the same object is referenced; otherwise, returns False.

[example 1] judge whether the empty string, empty tuple and empty list are None.

```def test_none(val):
if val is None:
print(f'{val} is None')
else:
print(f'{val} is not None')

test_none('')  # is not None
test_none(())  # () is not None
test_none([])  # [] is not None
test_none(test_none(''))  # None is None
```

## 1.34 is not -- judge whether two identifications are from the same object

Is not is used to judge whether two identifiers refer to different objects. If the referenced object is not the same object, the result is returned as True; otherwise, it is returned as False.

[example 1] judge whether to turn on the debugging mode.

```class Test(object):
def run(self, debug=None):
if debug is not None:
self.debug = bool(debug)

test = Test()
test.run(debug=True)
if test.debug:
print('Debug mode is on')
else:
print('Debug mode is off')
```

[example 2] use is not to avoid implicit judgment errors. In the if expression, if is and if not will automatically and implicitly convert the following objects into Boolean data. In some cases, it will lead to errors that are difficult to find. For example, the following code:

```def pay(name, salary=None):
if not salary:
salary = 8

pay("Amo", 0)
```

The program execution results are as follows:

Why? Because when the function accepts the salary parameter, it is assigned a value of 0. At this point, if not salary is True, so continue to execute the if statement. Next, use is not to modify the function to avoid errors caused by implicit conversion. The code is as follows:

```def pay(name, salary=None):
if salary is None:
salary = 8

pay("Amo", 0)  # Amo's hourly wage is 0 yuan
```

# 2, Process control

## 2.1 if statement – simple conditional judgment

Sometimes, we need to perform some operations when certain conditions are met, but do not perform any operations when conditions are not met. At this time, we can only use if statements. Python uses the if keyword to form the simplest selection statement. The basic form of the if statement is as follows:

```if expression:
Statement block
```

If the judgment condition is true, execute the statement block, otherwise skip directly.

[example 1] realize the judgment in the form of "if...". Through the if statement, if you are less than 12 years old, you can't play the game function of King glory. You are required to enter the age and use the if statement to judge whether it is less than 12. If it is less than 12, you will be prompted with "sorry, your age is too young to play the game of King glory!", The code is as follows:

```age = int(input('Please enter your age:'))
if age < 12:  # If the age is less than 12 years old
print('Sorry, you are too young to play the game of King glory!')
```

The running results of the program are shown in the figure below:

[example 2] judgment using and connection conditions. If you are over the age of 18 and under the age of 70, you can apply for a small car driver's license. The age can be more than 18 years old, i.e. more than two conditions; Under 70 years old, i.e. age < = 70. Use and to judge whether the two conditions are met. Input age > = 18 and age < = 70, and use the print() function to output "you can apply for a small car driver's license!", The code is as follows:

```age = int(input('Please enter your age:'))  # Enter age
# Abbreviation
# if 18 <= age <= 70:
if age >= 18 and age <= 70:  # Enter whether the age is between 18 and 70
print('You can apply for a small car driver's license!')
```

The running results of the program are shown in the figure below:

[example 3] judgment using or connection conditions. The commodities with daily sales of less than 10 and more than 100 shall be listed as key commodities. Use or to realize the judgment of two conditions, input the daily sales volume < 10 or input the daily sales volume > 100, and use the print() function to output "this commodity is the commodity of key concern!", The code is as follows:

```sales = int(input('Please enter the daily sales volume of goods:'))  # Enter daily sales volume of goods
if sales < 10 or sales > 100:  # Judgment conditions
print('This product is a focus product!')
```

The running results of the program are shown in the figure below:

[example 4] if statement and if... else statement are nested. It is required to enter an integer. First use the if statement to determine whether it is a valid integer. If so, convert it to integer, and then use the if... else statement to verify whether it is between 0 and 150. If so, output the number. Otherwise, the prompt code is as follows:

```number = input('Please enter an integer:')
if number.isdigit():  # Outer if statement
number = int(number)
if 0 <= number <= 150:  # Inner if statement
print(number)
else:
print('Not a valid result!')
```

The running results of the program are shown in the figure below:

[example 5] if statements, if... else and while statements are nested. Write a while loop. In this loop, you are required to enter an integer. First use the if statement to determine whether it is a valid integer. If so, convert it to an integer, and then use the if... else statement to verify whether it is between 0 and 150. If so, output the number and jump out of the loop. Otherwise, prompt and carry out the next loop. The code is as follows:

```while True:  # Outer for loop
number = input('Please enter an integer:')
if number.isdigit():  # Outer if statement
number = int(number)
if 0 <= number < 150:  # Inner if statement
print(number)
break  # Jump out of loop
else:
print('Not a valid score, please re-enter!')
```

The running results of the program are shown in the figure below:

[example 6] if statement and for statement are nested. Use the for statement to cycle through the string. In the loop body, use the if statement to judge whether the current character has been obtained. If not, it will be added to the new string and finally output the new string, so as to remove duplicate characters. The code is as follows:

```name = 'Zhang Wang, Li Wang, Chen Zhang, Li Wang, Chen Wang, Zhang'
newname = ''
for char in name:  # Outer for loop
if char not in newname:  # Inner if statement
newname += char
print(newname)
```

The running results of the program are shown in the figure below:

## 2.2 if... else statement -- two branch condition judgment

In Python, if... else statements are used to judge according to the given conditions and perform corresponding operations according to the judgment results (true or false). The syntax format of if... else statements is as follows:

```if expression:
Statement block 1
else:
Statement block 2
```

If means "if" and else means "otherwise", which is used to judge the condition. If the condition is met, execute statement block 1 after if; otherwise, execute statement block 2 after else. When using the if... Else statement, the expression can be a simple Boolean value or variable, a comparison expression or a logical expression.

[example 1] realize the judgment in the form of "if... Then... Otherwise...". Use the if... else statement to judge whether the motor vehicle driver has passed subject 2 of the test. The passing score is 80 points. If the score is greater than or equal to 80, it will prompt "pass the exam!", Otherwise, it will prompt "failed in the exam". The code is as follows:

```record = int(input('Please enter the test result of motor vehicle driver subject 2:'))
if record >= 90:  # Use if to judge whether the conditions are met
print('This achievement', record, 'branch\n Pass the exam!')
else:  # Do not meet the conditions
print('This achievement', record, 'branch\n Failed the exam!')
```

[example 2] nested if... else statements. The rule of "every seven ha ha" game is: when you encounter a number ending in the number 7 or the number of digits of 7, say "ha ha", otherwise directly say the number. The following is a nested if... else statement to input a number and output the corresponding content according to the rule. The code is as follows:

```number = input('Please enter an integer:')  # Enter the number to judge
if int(number) % 7 == 0:  # Determine whether it is a multiple of 7
print('ha-ha')
else:
if number.endswith('7'):  # Judge whether it ends with 7
print('ha-ha')
else:
print(number)
```

[example 3] if... else statements are nested with while statements. Save the student information in the dictionary and use the if statement to judge whether there is any student information to find. If it is found, enter and modify the student information through the while statement. When all the information is entered and there is no error, the loop will jump out and the modification result will be displayed. The code is as follows:

```student = {'id': '1001', 'name': 'Speechless', 'english': 98, 'python': 100, 'c': 96}
student_id = input('Please enter the student to modify ID number:')
if student['id'] == student_id:  # Judge whether it is the student to be modified
print('If you find this student, you can modify his information!')
while True:  # Enter the information to modify
try:
student['python'] = int(input('Please enter Python Achievements:'))
student['c'] = int(input('Please enter C Language achievement:'))
except Exception as e:
else:
break  # Jump out of loop
print(student)
print('Modification succeeded!')
else:
print('No information about the student was found!')
```

The running results of the program are shown in the figure below:

[example 4] if... else statements are nested with for statements. Use the nesting of if... else statement and for statement to traverse the student information and output it when the list is not empty. If the list is empty, a prompt will be given. The code is as follows:

```student = [{'id': '1001', 'name': 'Speechless', 'english': 98, 'python': 100, 'c': 96},
{'id': '1002', 'name': 'Qiqi', 'english': 100, 'python': 96, 'c': 97}]
if student:  # Outer if statement
for s in student:  # Inner for statement
print(s['id'], 'My name is', s['name'], 'English The result is', s['english'],
'Python The result is', s['python'], 'C Language achievement is', s['c'])
else:
print('No student information!')
```

The running results of the program are shown in the figure below:

[example 1] realize the judgment in the form of "if... Otherwise if... Otherwise if..." (similar to the Switch statement in Java). Output the corresponding air quality status according to the air quality index, refer to the air quality index range and the corresponding table of air quality status shown in the following table, input the air quality index of your city, and judge the air quality status.

The code is as follows:

```aqi = int(input('Please enter the air quality index of your city:'))  # Define an integer variable aqi to represent the air quality index
if 0 <= aqi <= 50:
print('Air quality: excellent')
elif 51 <= aqi <= 100:
print('Air quality condition: good')
elif 101 <= aqi <= 150:
print('Air quality: slight pollution')
elif 151 <= aqi <= 200:
print('Air quality: moderate pollution')
elif 201 <= aqi <= 300:
print('Air quality: severe pollution')
else:
print('Air quality: serious pollution')
```

[if... while] and [elif... Eli2]. Body Mass Index is calculated according to height and weight. Body Mass Index (BMI) is an important standard commonly used in the world to measure the degree of obesity and health. BMI = weight / height 2. The following table is the reference standard of BMI index in China.

Create a while loop in which two variables are defined: one is used to record height (in meters) and the other is used to record weight (in kilograms). Calculate BMI index according to the formula and judge weight status. The code is as follows:

```while True:
bmi = weight / (height * height)  # Calculate BMI index
# Judging body weight
if bmi < 18.5:
print('Yours BMI The index is:' + str(bmi))  # Output BMI index
print('Thin  ~@_@~')
elif bmi < 23.9:
print('Yours BMI The index is:' + str(bmi))  # Output BMI
print('normal (-_-)')
elif bmi < 28:
print('Yours BMI The index is:' + str(bmi))  # Output BMI index
print('Overweight ~@_@~')
else:
print('Yours BMI The index is:' + str(bmi))  # Output BMI index
print('Obesity ^@_@^')
```

[example 3] while, if and if... elif... else statements are nested. Use the if... elif... else statement to judge the menu item selected by the user. The code is as follows:

```import re  # Import regular expression module

print('''
X―――――――Student information management system――――――――[
│                                              │
│   =============== Function menu ============   │
│                                              │
│   1 Enter student information                             │
│   2 Find student information                             │
│   3 Delete student information                             │
│   4 Modify student information                             │
│   5 sort                                     │
│   6 Count the total number of students                           │
│   7 Show all student information                         │
│   0 Exit the system                                 │
│  ======================================  │
│  Description: by number or↑↓Direction key selection menu          │
^―――――――――――――――――――――――a
''')

if __name__ == '__main__':
flag = True  # Switch control
while flag:
option_str = re.sub(r'\D', '', option)  # Extract numbers
if option_str in ['0', '1', '2', '3', '4', '5', '6', '7']:  # Outer if statement
option_int = int(option_str)
if option_int == 0:  # Inner if statement
print('You have exited the student achievement management system!')
flag = False
elif option_int == 1:  # Enter student achievement information
# It's OK to implement each function here
# TODO 1.insert()
# Insert() = = > used to enter student achievement information
print('Enter student achievement information')
elif option_int == 2:  # Find student achievement information
# TODO 2
print('Find student achievement information')
elif option_int == 3:  # Delete student achievement information
print('Delete student achievement information')
elif option_int == 4:  # Modify student achievement information
print('Modify student achievement information')
elif option_int == 5:  # sort
print('sort')
elif option_int == 6:  # Count the total number of students
print('Count the total number of students')
elif option_int == 7:  # Show all student information
print('Show all student information')
```

## Elif. 3 - conditional elif... 2

When developing a program, if... elif... else statement can be used, which is a multi branch selection statement. The syntax format of if... elif... else statement is as follows:

```if Expression 1:
Statement block 1
elif Expression 2:
Statement block 2
elif Expression 3:
Statement block 3
...
else:
Statement block n
```

Elif is the abbreviation of else if. When using if... Elif... Else statement, first judge the expression 1 in the if statement. If the result of expression 1 is true, execute statement block 1, and then skip elif statement and else statement; If the result of expression 1 is false, statement block 1 is not executed, but the next elif is judged, and expression 2 in elif statement is judged. If expression 2 is true, statement block 2 is executed without subsequent elif and else statements. The statement block after else will be executed only when all the judgments are not tenable, that is, they are false. When using the if... Elif... Else statement, the expression can be a simple Boolean value or variable, a comparison expression or a logical expression.

## 2.4 for statement – loop

The for statement is a loop executed repeatedly in turn. It is generally suitable for enumerating or traversing sequences and iterating over elements in objects. The syntax format of the for statement is as follows:

```for Iterative variable in object:
Circulatory body
```

Parameter Description:

1. Iteration variable: used to save the read value;
2. Object: the object to be traversed or iterated, such as string, list, tuple, dictionary and other data structures;
3. Loop body: a set of statements that are repeatedly executed.

[example 1] to realize the accumulation from 1 to 100, you can use the following code:

```result = 0  # A variable that holds the cumulative result
for i in range(101):
result += i  # Realize accumulation function

print('1+2+3+......+100 The results are:', result)  # Output the result at the end of the cycle
```

[example 2] numerical cycle of specified range and step size:

```for i in range(1, 10, 2):
print(i, end=' ')  # 1 3 5 7 9
```

[example 3] traversal string:

```str1 = 'Don't give up easily'
for s in str1:
print(s)
```

[example 4] traverse the whole list:

```print('Forbes 2018 top five global rich list:')
name = ['Jeff・Bezos', 'Bill・Gates', 'Warren•Buffett ', 'bernard ・Arnott', 'Amancio・Ortega ']
for item in name:
print(item)
```

[example 5] realize numbered output through the for statement and enumerate() function:

```print('Forbes 2018 top eight global rich list:')
name = ['Jeff・Bezos', 'Bill・Gates', 'Warren•Buffett ', 'bernard ・Arnott', 'Amancio・Ortega ']
for index, item in enumerate(name):
print(index + 1, item)
```

[example 6] slice traversal list:

```phonename = ['Huawei', 'vivo', 'millet', 'OPPO', 'Samsung']  # Definition list
for name in phonename[1:4]:  # Slice traversal list
print(name)  # Output the value of the list element
```

[Example 7] traversal tuple:

```musicname = ('Better Off', 'Going Home', 'Breeze', 'The Spectre')  # Define tuples
for name in musicname:  # Traversal tuple
print(name)  # Output the value of each tuple element
```

[example 8] traversal set:

```setname = {'MIT', 'Stanford University', 'Harvard University', 'California Institute of Technology', 'Oxford'}
print('Ranking of world famous universities:')
for i in setname:
print('☛', i)
```

[Example 9] traverse the key value of the dictionary:

```dictionary = {'Speechless': '5 May 25', 'Qiqi': '10 August 8', 'Blue sea Cangwu': '7 June 27', }
for key, value in dictionary.items():
```

[example 10] for statement and for statement nesting

```row = 5  # Number of rows
for i in range(1, row + 1):  # Number of control rows
for j in range(row - i):  # Controls the number of spaces per line
print(" ", end="")  # nowrap
for j in range(1, 2 * i):  # Controls the number of * signs displayed on each line
print("*", end="")  # nowrap
print("")  # Forced line feed
```

[example 11] for statement and if statement are nested

```print('Python Application areas:')
fields = ['Data analysis', 'Internet worm', 'Web development', 'Game development', 'Cloud computing', 'artificial intelligence']
for index, fields in enumerate(fields):  # for statement
if index % 2 == 0:  # if statement
print(fields, end='\t')
else:
print(fields)
```

[example 12] for statement and while statement are nested

```row = 5  # Number of rows
for i in range(1, row + 1):  # Number of control rows
a = 1
while a <= i:
print('*', end='')  # nowrap
a += 1
print('')  # Forced line feed
```

## 2.5 for... else statement – loop

For... Else statement adds an else clause to the for statement, which is used to execute the specified code when the loop conditions are not met. The syntax format of the for statement is as follows:

```for Iterative variable in object:
Circulatory body
else:
Statement block
```

Parameter Description:

1. Iteration variable: used to save the read value;
2. Object: the object to be traversed or iterated, such as string, list, tuple, dictionary and other data structures;
3. Loop body: a set of statements that are repeatedly executed.
4. Statement block: a group of statements executed after the loop condition is not met. If the break statement is used to abort the loop, it is not executed.

[example 1] basic application of for... Else statement. Realize the accumulation from 1 to 100, and output the accumulation result in else clause. The code is as follows:

```result = 0  # A variable that holds the cumulative result
for i in range(101):
result += i  # Realize accumulation function
else:
print('1+2+3+......+100 The results are:', result)  # Output the result at the end of the cycle
```

[example 2] nested for... else statements. Use the nested for... else statement to output all prime numbers within 20. The code is as follows:

```for i in range(1, 20):  # Circular statement
for j in range(2, i):
if i % j == 0:  # If a number can be divided by numbers other than 1 and itself, it is not a prime number
break  # Jump out of for loop
else:
print(i, end='  ')  # Output prime
else:
print('Is a prime number.')
```

[example 3] in the for... Else statement, the else clause is executed when the loop conditions are not met, but if the break statement is used to stop the loop, the else clause is not executed. The code is as follows:

```menu = ['1', '2', '3', '4', '5', '6', '0']  # Menu number
for opt in menu:  # Circular statement
if opt == '0':
break  # Jump out of for loop
else:
```

## 2.6 while statement – loop

The while statement controls whether to continue to repeatedly execute the statements in the loop body through a condition. The syntax format of the while statement is as follows:

```Initialization statement # Similar to i=0
while Conditional expression:
Circulatory body
Conditional control statement  # Similar to i+=1
```

When the return value of the conditional expression is true, execute the statement in the loop body. After execution, re judge the return value of the conditional expression until the result returned by the expression is false, and exit the loop.

[example 1] use the while statement to realize a fixed number of cycles. Use the while statement to calculate the sum of 1 ~ 100 even numbers. The code is as follows:

```num = 1
result = 0
while num <= 100:  # while loop condition
if num % 2 == 0:
result += num
num += 1  # Variable self addition
print('1~100 The sum of even numbers is:', result)
```

Use the example of when statement and indefinite loop statement (2). Use the while statement to realize the number guessing game. The code is as follows:

```import random  # Import random number module

number = random.randint(1, 100)  # Generate random integers between 1 and 100
while True:  # Infinite loop
value = int(input('Please enter a number within 100:'))  # Enter number
if value > number:
print('High')
elif value < number:
print('Low!')
else:
print('Congratulations, you guessed right!')
break  # Exit loop
```

[example 3] use the while statement to nest with the while statement. Use the while statement and the while statement to nest and output the 99 multiplication table. The code is as follows:

```i = 1  # Initial value
while i <= 9:  # Outer loop (control rows)
j = 1
while j < i + 1:  # Inner loop (number of control columns)
result = i * j
print(str(i) + '*' + str(j) + '=', i * j, end='\t')  # nowrap
j += 1
print('')  # Forced line feed
i += 1
```

[example 4] use the while statement to nest with the for statement. When developing games with pygame module, it is often necessary to use the nesting of while statement and for statement to close the control form. The code is as follows:

```import pygame  # Import Pygame Library
import sys  # Import system module

pygame.init()  # Initialize Pygame
screen = pygame.display.set_mode((320, 240))  # Display window
while True:  # Outer while loop
# Get click event
for event in pygame.event.get():  # Inner for loop
if event.type == pygame.QUIT:  # If you click close form, the form will be closed
pygame.quit()  # Exit window
sys.exit()  # close window
```

## 2.7 while... else statement – loop

While... Else statement adds an else clause to the while statement, which is used to execute the specified code when the loop conditions are not met. The syntax format of the while... Else statement is as follows:

```Initialization statement # Similar to i=0
while Conditional expression:
Circulatory body
Conditional control statement  # Similar to i+=1
else:
Statement block
```

When the return value of the conditional expression is true, execute the statement in the loop body. After execution, re judge the return value of the conditional expression until the result returned by the expression is false, execute the statement in the statement block.

[example 1] when the while statement is used to implement an indefinite cycle, the number of cycles is output. Use the while statement to realize the number guessing game. It is required that there are only 5 opportunities at a time. When the opportunities are used up and have not been guessed correctly, end the program and prompt "your opportunities have been used up.", The code is as follows:

```import random  # Import random number module

number = random.randint(1, 100)  # Generate random integers between 1 and 100
count = 0  # frequency
while count < 5:  # Infinite loop
count += 1
value = int(input('Please enter a number within 100:'))  # Enter number
if value > number:
print('High')
elif value < number:
print('Low!')
else:
print('Congratulations, you guessed right!')
break  # Exit loop
else:
```

Note: else clause will be executed only when the loop conditions are not met. It will not be executed when using break statement to jump out of the loop.

## 2.8 break statement – terminates the current loop

The break statement is used to terminate the loop, that is, if the loop condition is established or the sequence has not been completely recursive, the execution of the loop statement will also be stopped. The common syntax format of break statement is as follows:

```if Conditional expression:
break
```

The conditional expression is used to judge when to call the break statement to jump out of the loop.

[example 1] use the break statement in the for statement.

```for i in range(1, 11):
if i == 5:
break  # break statement terminates the loop
print(i, end=' ')
```

[example 2] use the break statement in the while loop.

```num = 10
while True:  # while loop condition
num -= 1  # Variable self addition
print(num)  # Output the value of num
if num <= 6:
break
```

## 2.9 continue statement – terminate this cycle and enter the next cycle

The continue statement directly jumps to the next iteration of the loop during the execution of the statement block. That is, terminate the current cycle and execute the next cycle. The syntax format of the continue statement is as follows:

```if Conditional expression:
continue
```

The conditional expression is used to judge when to call the continue statement to jump out of the loop.

[example 1] use the continue statement in the for statement

```for i in range(1, 11):
if i == 2 or i == 8:
continue  # continue statement jumps out of this cycle and continues to the next cycle
print(i, end=' ')
```

[example 2] use the continue statement in the while loop

```num = 0  # Define variables and assign initial values
while num < 5:
num += 1  # Change the value of the variable
if num == 2:
continue
print('sum The value of is:', num)  # Output the value of sum
```

Note: break statements and continue statements can only be used in loops. Break statements and continue statements are nested in loops and only work on the nearest loop.

## 2.10 conditional expressions (ternary operators, ternary expressions)

Conditional expression is a concise assignment method in Python selection statements. It is often used in assignment statements. Its basic format is:

```a if b else c
```

If the judgment condition b is true, the result a when it is true is returned; otherwise, the result c when it is false is returned.

[example 1] apply conditional expressions to compare sizes.

```num1 = 100
num2 = 78
large = num1 if num1 > num2 else num2  # Find a larger number
print('%d and%d %d Larger.' % (num1, num2, large))
small = num1 if num1 < num2 else num2  # Find decimal point
print('%d and%d %d Smaller.' % (num1, num2, small))
```

When using a conditional expression, first calculate the intermediate condition (num1 > num2). If the result is True, return the value on the left of the if statement (num1), otherwise return the value on the right of else (num2). For example, if the expression above finds a large number, when the result is True, it returns the value of num1, that is, the result is 100.

[example 2] the application condition expression returns different information according to the calculation result. Use the conditional expression to judge whether a number can be divided by 2, and return whether it is odd or even according to the result. The code is as follows:

```number = int(input('Please enter a number:'))
result = 'Odd number' if number % 2 == 1 else 'even numbers'  # Conditional expression
print(number, 'yes' + result)
```

[example 3] apply conditional expressions to process optional parameters of user-defined functions.

```def demo(param=None):
return 'No parameters specified' if param is None else 'param The parameter value is――' + param

print(demo())  # The calling function does not specify parameters
print(demo('Don't give up easily'))  # Call the function and specify parameters
```

[example 4] conditional expressions with multiple conditions are used. Use a conditional expression to return whether the entered year is a leap year. The code is as follows:

```year = int(input('Please enter a number:'))
result = 'leap year' if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0 else 'Not a leap year'
print(year, result)
```

# 3, Program debugging and exception handling

## 3.1 assert statement – application assertion debugger

Assert means assertion in Chinese. It is generally used to verify the conditions that must be met at a certain time. The basic syntax of the assert statement is as follows:

```assert expression [,reason]
```

Parameter Description:

1. Expression: conditional expression. If the value of the expression is true, nothing will be done. If it is false, an assertion error exception will be thrown.
2. reason: optional parameter, used to describe the judgment conditions, in order to let others better know what problems have occurred.

[example 1] use assertion to debug the program. It is required to enter a number, and then use the assert statement to throw an exception on the null value entered. The code is as follows:

```number = input('Please enter a number:')
assert number != '', 'Cannot enter null value!'  # Throw an exception through assertion when the value is null
print('You entered:', number)
```

Run the program without inputting anything. When you directly press the < ENTER > key, the assertion error exception as shown in the following figure will be thrown.

[example 2] use assertion debugger in division operation. Define the division() function that performs division operation, and assert the debugger in this function. The code is as follows:

```def division():
num1 = int(input('Please enter the divisor:'))  # User input prompt and record
assert num2 != 0, 'Divisor cannot be 0'  # Application assertion debugging
result = num1 // num2 # performs a division operation
print(result)

if __name__ == '__main__':
division()  # Call function
```

Run the program, enter the divisor as 0, and the assertion error exception shown in the following figure will be thrown.

[example 3] Apply assertions and exception handling statements to handle exceptions.

```def division():
num1 = int(input('Please enter the divisor:'))  # User input prompt and record
assert num2 != 0, 'Divisor cannot be 0'  # Application assertion debugging
result = num1 // num2 # performs a division operation
print(result)

if __name__ == '__main__':
try:
division()  # Call function
except AssertionError as e:  # Handling AssertionError exception
print('\n Incorrect input:', e)
```

The running results of the program are shown in the figure below:

Note: where print can be used to assist in viewing, assertion can be used instead. The assert statement is valid only during debugging. We can close the assert statement by adding the - O (uppercase) parameter when executing the python command. After closing, you can ignore all assert statements as pass statements.

## 3.2 raise statement - throw exception

If a function or method may generate an exception, but you do not want to handle the exception in the current function or method, you can use the raise statement to throw an exception in the function or method. The basic format of raise statement is as follows:

```raise [ExceptionName[(reason)]]
```

ExceptionName[(reason)] is an optional parameter, which is used to specify the name of the exception thrown and the relevant description of the exception information. If omitted, the current error will be thrown as is. (reason) in the ExceptionName(reason) parameter can also be omitted. If omitted, no description information will be attached when throwing an exception.

Example: use raise statement to throw an exception

```def division():
num1 = int(input('Please enter the divisor:'))  # User input prompt and record
if num2 == 0:
raise ValueError('Divisor cannot be 0')
result = num1 // num2 # performs a division operation
print(result)

if __name__ == '__main__':
try:  # Catch exception
division()  # Call function
except ValueError as e:  # Handle ValueError exception
print('Input error:', e)  # Output error reason
```

[example 2]: use raise statement to throw different exceptions for different situations

```try:
if len(username) > 16:  # If the user exceeds 16 characters
raise ValueError('The user name input is illegal and cannot exceed 16 characters!')  # Throw ValueError exception
if not pwd.isalnum():
raise ValueError('The password input is illegal and cannot include characters other than numbers and letters!')  # Throw ValueError exception
except ValueError as e:
print(e)
```

The running results of the program are shown in the figure below:

## 3.3 try... except statement – catch exception

The try... Except statement is used to catch and handle exceptions. When in use, put the code that may cause exceptions in the try statement block and the processing results in the except statement block. In this way, when the code in the try statement block has errors, the code in the except statement block will be executed. If the code in the try statement block has no errors, the except statement block will not be executed. The specific syntax format is as follows:

```try:
block1
except [ExceptionName [as alias]]:
block2
```

Parameter Description:

1. block1: indicates a block of code where an error may occur.
2. ExceptionName [as alias]: optional parameter, used to specify the exception to be caught. Where, ExceptionName indicates the name of the exception to be caught. If as alias is added to the right, it indicates that an alias is specified for the current exception. Through this alias, the specific contents of the exception can be recorded. When using the try... Exception statement to catch exceptions, if the exception name is not specified after exception, it means that all exceptions are caught.
3. block2: indicates the code block for exception handling. Fixed prompt information can be output here, and the specific content of the exception can also be output through the alias.

Note: after using the try... except statement to catch exceptions, when the program makes an error, the program will continue to execute after outputting the error message.

[example 1] catch one exception at a time

```def division():
num1 = int(input('Please enter the divisor:'))  # User input prompt and record
result = num1 // num2 # performs a division operation
print(result)

if __name__ == '__main__':
try:  # Catch exception
division()  # Call the function of dividing apples
except ZeroDivisionError:  # Handling exceptions
print('Input error: divisor cannot be 0')  # Output error reason
```

The program execution results are shown in the following figure:

[example 2] capture multiple exceptions at one time

```def division():
num1 = int(input('Please enter the divisor:'))  # User input prompt and record
result = num1 // num2 # performs a division operation
print(result)

if __name__ == '__main__':
try:  # Catch exception
division()  # Call function
except (ZeroDivisionError, ValueError):  # Handling exceptions
```

The program execution results are shown in the following figure:

Note: if you need to catch more exceptions, you can continue to add exception names after ValueError and separate them with commas in English.

[example 3] use multiple except clauses to catch multiple exceptions respectively.

```def division():
num1 = int(input('Please enter the divisor:'))  # User input prompt and record
result = num1 // num2 # performs a division operation
print(result)

if __name__ == '__main__':
try:  # Catch exception
division()  # Call function
except ZeroDivisionError:  # Handling exceptions
print('\n Error: divisor cannot be 0!')
except ValueError as e:  # Handle ValueError exception
print('Input error:', e)  # Output error reason
```

Note: if you need to catch more exceptions, you can continue to add the exception clause.

[example 4] capture all exceptions at once.

```def division():
num1 = int(input('Please enter the divisor:'))  # User input prompt and record
result = num1 // num2 # performs a division operation
print(result)

if __name__ == '__main__':
try:  # Catch exception
division()  # Call function
except Exception as e:  # Handling exceptions
print('Error:', e)
```

The program execution results are shown in the following figure:

## 3.4 try... except... else statement – catch exception

The try... except... Else statement is also an exception handling structure. It adds an else clause on the basis of the try... except statement to specify the statement block to be executed when no exception is found in the try statement block. When an exception is found in a try statement, the contents of the statement block will not be executed. The syntax format is as follows:

```try:
block1
except [ExceptionName [as alias]]:
block2
else:
block3
```

Parameter Description:

1. block1: indicates a block of code where an error may occur.
2. ExceptionName [as alias]: optional parameter, used to specify the exception to be caught. Where, ExceptionName indicates the name of the exception to be caught. If as alias is added to the right, it indicates that an alias is specified for the current exception. Through this alias, the specific contents of the exception can be recorded.
3. block2: indicates the code block for exception handling. Fixed prompt information can be output here, and the specific content of the exception can also be output through the alias.
4. block3: a statement block executed when no exception is generated.

[example 1] catch the exception and give a prompt when there is no exception.

```def division():
num1 = int(input('Please enter the divisor:'))  # User input prompt and record
result = num1 // num2 # performs a division operation
return result

if __name__ == '__main__':
try:  # Catch exception
result = division()  # Call function
except ZeroDivisionError:  # Handling exceptions
print('\n Error: divisor cannot be 0!')
except ValueError as e:  # Handle ValueError exception
print('Input error:', e)  # Output error reason
else:  # Execute when no exception is thrown
print('The result is:', result)
```

The running results of the program are shown in the figure below:

[example 2] use the try... except statement to give a prompt when the student's grade is wrong, otherwise the input result will be output.

```while True:
try:  # Catch exception
python = int(input('Please enter Python Achievements:'))
c = int(input('Please enter C Language achievement:'))
except:  # Handling exceptions
print('Invalid input, not integer data,Please re-enter the information!')
continue  # Continue the cycle
else:  # Execute when no exception is thrown
print('English:', english, '\tPython: ', python, '\tC Language:', c)
break  # Jump out of loop
```

The running results of the program are shown in the figure below:

## 3.5 try... except... finally statement – catch exception

The complete exception handling statement should contain the finally code block. Generally, the code in the finally code block will be executed regardless of whether there are exceptions in the program. The basic format is as follows:

```try:
block1
except [ExceptionName [as alias]]:
block2
finally:
block3
```

The understanding of the try... except... Finally statement is not complicated. It is just one more finally statement than the try... except statement. If there are some code that must be executed in any case in the program, they can be placed in the block of the finally statement.

Note: the exception clause is used to allow exception handling. The cleanup code can be executed using the finally clause regardless of whether an exception is thrown or not. If limited resources are allocated (such as open files), the code that releases these resources should be placed in the finally block.

[example 1] when catching exceptions, apply the finally clause to output the specified prompt information.

```def division():
num1 = int(input('Please enter the divisor:'))  # User input prompt and record
result = num1 // num2 # performs a division operation
return result

if __name__ == '__main__':
try:  # Catch exception
result = division()  # Call function
except ZeroDivisionError:  # Handling exceptions
print('\n Error: divisor cannot be 0!')
except ValueError as e:  # Handle ValueError exception
print('Input error:', e)  # Output error reason
else:  # Execute when no exception is thrown
print('The result is:', result)
finally:  # Execute whether or not an exception is thrown
print('\n Division performed!')
```

The running result when the program does not throw an exception.

The running result when the program throws an exception.

[example 2] apply the try... except... finally clause when connecting to the database.

```import sqlite3  # Import sqlite3 module

try:
# Connect to SQLite database
# The database file is test DB. If the file does not exist, it will be automatically created in the current directory
conn = sqlite3.connect('test.db')
except Exception as e:  # Handling exceptions
print(e)
else:
try:
cursor = conn.cursor()  # Create a Cursor
# Execute an SQL statement to create the user table
cursor.execute('create table user(id int(10) primary key,name varchar(20))')
except Exception as e1:  # Handling exceptions
print(e1)
finally:  # Execute whether or not an exception is thrown
cursor.close()  # Close cursor
finally:  # Execute whether or not an exception is thrown
conn.close()  # Close Connection
```

The first time you run the above code, no exception is thrown. When you run the above code again, you will throw an exception because the data table already exists.

Keywords: Python list

Added by alexz on Thu, 10 Feb 2022 06:14:22 +0200