python-day9 (formal learning)

Copy depth

Let me talk about variable and immutable data types, based on the original value of the modification, the same id value change is variable data type; and the value changed id has changed, that is, to re-apply for a space to put a new value this is immutable data types.

Click to view the page source

copy

Is equivalent to a normal copy of the assignment is to assign a value to a variable to another variable name

l1=[1,2,3,[4,5,6]]
l2=l1
l1.append(7)
print(l1)
print(l2)

[1, 2, 3, [4, 5, 6], 7]
[1, 2, 3, [4, 5, 6], 7]

img

Shallow copy

Shallow copy module you need to import a copy of this copy is a new open memory list, but the list of all the elements point to address is still the same, if there is a variable list of data types, then the data in the immutable type of modification if the new list will be modified.

import copy
l1=[1,2,3,[4,5,6]]
l2=copy.copy(l1)
l1.append(7)
print(l1)
print(l2)
l1[3].append(8)
print(l1)
print(l2)

[1, 2, 3, [4, 5, 6], 7]
[1, 2, 3, [4, 5, 6]]
[1, 2, 3, [4, 5, 6, 8], 7]
[1, 2, 3, [4, 5, 6, 8]]

img

Deep copy

And a shallow copy of the same module also needs to import a copy, it is the presence of a deep copy of a list of new separate memory space, wherein the address element refers to the value of the variable is not the same, so no matter how they change the original list, the new list not change.

import copy
l1=[1,2,3,[4,5,6]]
l2=copy.deepcopy(l1)
l1.append(7)
print(l1)
print(l2)
l1[3].append(8)
print(l1)
print(l2)

[1, 2, 3, [4, 5, 6], 7]
[1, 2, 3, [4, 5, 6]]
[1, 2, 3, [4, 5, 6, 8], 7]
[1, 2, 3, [4, 5, 6]]

img

Exception Handling

What is unusual

An exception is the wrong signal occurs when the program is run, then an exception is thrown

Grammatical errors

# 语法错误示范一
if

# 语法错误示范二
def test:
    pass

# 语法错误示范三
class Foo
    pass

# 语法错误示范四
print(haha

logical error

# TypeError:int类型不可迭代
for i in 3:
    pass

# ValueError
num=input(">>: ") #输入hello
int(num)

# NameError
aaa

# IndexError
l=['egon','aa']
l[3]

# KeyError
dic={'name':'egon'}
dic['age']

# AttributeError
class Foo:pass
Foo.x

# ZeroDivisionError:无法完成计算
res1=1/0
res2=1+'str'

Unusual species

Common exceptions

  • AttributeError no attempt to access an object tree, such as foo.x, but no property x foo
  • IOError input / output is abnormal; substantially not open file
  • ImportError package or module can not be introduced; substantially path problem or error name
  • IndentationError 语法错误(的子类) ;代码没有正确对齐
  • IndexError 下标索引超出序列边界,比如当x只有三个元素,却试图访问x[5]
  • KeyError 试图访问字典里不存在的键
  • KeyboardInterrupt Ctrl+C被按下
  • NameError 使用一个还未被赋予对象的变量
  • SyntaxError Python代码非法,代码不能编译(个人认为这是语法错误,写错了)
  • TypeError 传入对象类型与要求的不符合
  • UnboundLocalError 试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量,导致你以为正在访问它
  • ValueError 传入一个调用者不期望的值,即使值的类型是正确的

其他异常

  • ArithmeticError
  • AssertionError
  • AttributeError
  • BaseException
  • BufferError
  • BytesWarning
  • DeprecationWarning
  • EnvironmentError
  • EOFError
  • Exception
  • FloatingPointError
  • FutureWarning
  • GeneratorExit
  • ImportError
  • ImportWarning
  • IndentationError
  • IndexError
  • IOError
  • KeyboardInterrupt
  • KeyError
  • LookupError
  • MemoryError
  • NameError
  • NotImplementedError
  • OSError
  • OverflowError
  • PendingDeprecationWarning
  • ReferenceError
  • RuntimeError
  • RuntimeWarning
  • StandardError
  • StopIteration
  • SyntaxError
  • SyntaxWarning
  • SystemError
  • SystemExit
  • TabError
  • TypeError
  • UnboundLocalError
  • UnicodeDecodeError
  • UnicodeEncodeError
  • UnicodeError
  • UnicodeTranslateError
  • UnicodeWarning
  • UserWarning
  • ValueError
  • Warning
  • ZeroDivisionError

Exception Handling

Early prevention

AGE = 10
while True:
    age = input('>>: ').strip()
    if age.isdigit():  # 只有在age为字符串形式的整数时,下列代码才不会出错,该条件是可预知的
        age = int(age)
        if age == AGE:
            print('you got it')
            break
>>: nick
>>: sdkf
>>: 2
>>: 10
you got it

Later prevention

If the error is not expected to be used try..except

#  举例
try:
    f = [
        'a',
        'a',
        'a',
        'a',
        'a',
        'a',
        'a',
    ]
    g = (line.strip() for line in f)
    print(next(g))
    print(next(g))
    print(next(g))
    print(next(g))
    print(next(g))
except StopIteration:
    f.close()
a
a
a
a
a

By the specified method to handle exceptions

s1 = 'hello'
try:
    int(s1)
except IndexError as e:
    print(e)
except KeyError as e:
    print(e)
except ValueError as e:
    print(e)
invalid literal for int() with base 10: 'hello'

Universal abnormal method

s1 = 'hello'
try:
    int(s1)
except Exception as e:
    print(e)

img

Throws an exception (basically useless)

try:
    raise TypeError('抛出异常,类型错误')
except Exception as e:
    print(e)

Assert (debugging, and now basically useless)

try:
    assert 1 == 2
except Exception as e:
    print(e)

img

File Handling

Here only pull a little bit, tomorrow or the day will be specific description.

Open to open a file with this method, there are three parameters, the first path is a path, the operation mode is the second mode, the third encoding mode is decoded.

such as:

f=open('compare.py','w',encoding='utf-8')
f.write('s')
f.close()

This is a file write operation, pay attention to the content written before overwrite files! ! !

img

Guess you like

Origin www.cnblogs.com/leaf-wind/p/11310120.html
Recommended