Ali Tianchi Python Training Camp task 1

1. Bit operation

Example: Reverse 4 bitwise

print(bin(~4),~4)
#运行结果
-0b101 -5

Calculation: if the calculated 16-bit, 4 is converted into first binary : 0,000,000,000,000,100, each one its inverted to give the final result of complement : 1,111,111,111,111,011, then according complement to obtain the original code is : 1000 0000 0000 0101, converted to decimal is -5.

2. Data type and conversion

2.1 Use getcontext().prec to adjust the accuracy

Example: Make 1/3 reserve four digits.

import decimal
from decimal import Decimal
decimal.getcontext().prec=4
c=Decimal(1)/Decimal(3)
print(c)
#运行结果
0.3333

2.2isinstance(object,classinfo)

object -instance object.
classinfo -can be direct or indirect class names, basic types, or tuples composed of them. Determine whether an object is of a known type.

print(isinstance(2, int))
print(isinstance(5.7, float))
print(isinstance(True, bool))
print(isinstance('5.22', str))
#运行结果
True True True True

The difference between isinstance() and type() :

type() does not consider the subclass to be a parent type, and does not consider the inheritance relationship.

isinstance() will consider the subclass to be a parent class type, and consider the inheritance relationship.

If you want to judge whether two types are the same, isinstance() is recommended .
example:

class A:
    pass
 
class B(A):
    pass
 
print(isinstance(A(), A))    #True
print(type(A()) == A)        #True
print(isinstance(B(), A))    #True
print(type(B()) == A)        #False

3. Loop statement

3.1 while-else loop

while 布尔表达式:
	代码块
else:
	代码块

When the while loop is executed normally, the else output is executed . If the statement that jumps out of the loop is executed in the while loop, such as break , the content of the else code block will not be executed .
example:

count = 0
while count < 2:
	print("%d is  less than 2" % count)
	count = count + 1
	#break可直接跳出循环,不执行else语句
else:
	print("%d is not less than 2" % count)
	
# 0 is  less than 2
# 1 is  less than 2
# 2 is not less than 2

3.2enumerate() function

The enumerate() function is used to combine a traversable data object (such as a list, tuple, or string) into an index sequence, and list data and data subscripts at the same time. It is generally used in a for loop.

enumerate(sequence, [start=0])
sequence – A sequence, iterator, or other object that supports iteration.
start -the starting position of the subscript.

Example:

>>>seasons = ['Spring', 'Summer', 'Autumn', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Autumn'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))       # 下标从 1 开始
[(1, 'Spring'), (2, 'Summer'), (3, 'Autumn'), (4, 'Winter')]

Ordinary for loop

>>>i = 0
>>> seq = ['one', 'two', 'three']
>>> for element in seq:
	    print i, seq[i]
     	i +=1

0 one
1 two
2 three

for loop use enumerate()

>>>seq = ['one', 'two', 'three']
>>> for i, element in enumerate(seq):
...     print i, element
... 
0 one
1 two
2 three

4. Derivative

4.1 List comprehension

List comprehension format:

[ expr for value in collection [if condition]

Example:

x = [-4, -2, 0, 2, 4]
y = [a * 2 for a in x]
print(y) 

#[-8, -4, 0, 4, 8]

x = [[i, j] for i in range(0, 3) for j in range(0, 3)]
print(x)

# [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]

a = [(i, j) for i in range(0, 3) if i < 1 for j in range(0, 3) if j > 1]
print(a)

# [(0, 2)]

4.2 Tuple comprehension

Tuple comprehension format:

(expr for value in collection [if condition])

Example:

a=tuple(x for x in range(10))
print(a)

#(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

4.3 Dictionary comprehension

Tuple comprehension format:

{ key_expr: value_expr for value in collection [if condition] }

Example:

b = {
    
    i: i % 2 == 0 for i in range(10) if i % 3 == 0}
print(b)

# {0: True, 3: False, 6: True, 9: False}

4.4 Set comprehension

Tuple comprehension format:

{ expr for value in collection [if condition]

Example:

c = {
    
    i for i in [1, 2, 3, 4, 5, 5, 6, 4, 3, 2, 1]}
print(c)

# {1, 2, 3, 4, 5, 6}

4.5next() function

next() returns the next item in the iterator.
The next() function should be used together with the iter() function that generates iterators.
grammar:

next(iterable[, default])

iterable - iterable object
default -optional, used to set the default value to be returned when there is no next element. If it is not set and there is no next element, StopIteration will be triggered .

Example:

# 首先获得Iterator对象:
it = iter([1, 2, 3, 4, 5])
# 循环:
while True:
    try:
        # 获得下一个值:
        x = next(it)
        print(x)
    except StopIteration:
        # 遇到StopIteration就退出循环
        break
        
#1 2 3 4 5

5. Exception handling

5.1 try-except statement

format:

try:
	检测范围 
except Exception[as reason]:
	出现异常后的处理代码

Way of working:

  1. First, execute the try clause ( the statement between the keyword try and the keyword except
  2. If no exception occurs, ignore the except clause, and end after the try clause is executed.
  3. If an exception occurs during the execution of the try clause, the rest of the try clause will be ignored. If the type of the exception matches the name after except , the corresponding except clause will be executed. Finally execute the code after the try-except statement
  4. If an exception does not match any except , then the exception will be passed to the upper try .

Example:

try:
	f = open('test.txt')
	print(f.read())
	f.close()
except OSError:
	print('打开文件出错')
	
# 打开文件出错

A try statement may contain multiple except clauses to handle different specific exceptions. Only one branch will be executed at most.
example:

dict1 = {
    
    'a': 1, 'b': 2, 'v': 22} 
try:
	x = dict1['y']
except LookupError:
   	print('查询错误')
except KeyError:
   	print('键错误') 
else:
	print(x)
	
# 查询错误

The try-except-else statement tried to query the key-value pairs that were not in the dict , which caused an exception. This exception should belong to KeyError accurately , but because KeyError is a subclass of LookupError , and LookupError is placed before KeyError , the program executes the except code block first. Therefore, when using multiple except code blocks, you must adhere to the order of their specifications, from the most targeted exception to the most general exception.

An except clause can handle multiple exceptions at the same time, and these exceptions will be placed in parentheses as a tuple.
example:

try:
	...
except (OSError, TypeError, ValueError) as error:
	print('出错了!\n原因是:' + str(error))
	
# 出错了! 
# 原因是:unsupported operand type(s) for +: 'int' and 'str'

5.2 try-except-finally statement

format:

try:
	检测范围
except Exception[as reason]:
	出现异常后的处理代码
finally:
	无论如何都会被执行的代码

Regardless of whether an exception occurs in the try clause, the finally clause will be executed.

5.3 try-except-else statement

format:

try:
	检测范围 
except:
	出现异常后的处理代码 
else:
	如果没有异常执行这块代码

Use except without any exception type, this is not a good way, we can not identify specific exception information through the program, because it catches all exceptions.

5.4 raise statement

Use the raise statement to throw a specified exception.
example:

try:   
	raise NameError('HiThere') 
except NameError: 
	print('An exception flew by!')
	
# An exception flew by!

Guess you like

Origin blog.csdn.net/qq_43965708/article/details/108739459