1. 程式人生 > >Python入門學習筆記_2

Python入門學習筆記_2

for迴圈

使用zip()迭代

days = ['Monday', 'Tuesday', 'Wednesday']
fruits = ['banana', 'orange', 'peach']
drinks = ['coffee', 'tea', 'beer']
for day, fruit, drink in zip(days, fruits, drinks):
    print(day, ":drink", drink, "- eat", fruit, "- enjoy")
Monday :drink coffee - eat banana - enjoy
Tuesday :drink tea - eat orange - enjoy
Wednesday :drink beer - eat peach - enjoy
english = 'Monday', 'Tuesday', 'Wednesday'
french = 'Lundi', 'Mardi', 'Mercedi'
print(list(zip(english, french)))
print(dict(zip(english, french)))
[('Monday', 'Lundi'), ('Tuesday', 'Mardi'), ('Wednesday', 'Mercedi')]
{'Monday': 'Lundi', 'Tuesday': 'Mardi', 'Wednesday': 'Mercedi'}

range()生成自然數序列

for
x in range(0, 3): print(x, end = " ")
0 1 2 

推導式

列表推導式

number_list = list(range(1, 6))
print(number_list)
#常用
number_list = [number for number in range(0, 5)]
print(number_list)
number_list = [number - 1 for number in range(0, 5)]
print(number_list)
a_list = [number for number in range(1,6) if number %
2 == 1] print(a_list)
[1, 2, 3, 4, 5]
[0, 1, 2, 3, 4]
[-1, 0, 1, 2, 3]
[1, 3, 5]

元組推導式

rows = range(1, 4)
cols = range(1,3)
cells = [(row, col) for row in rows for col in cols]
print(cells)
[(1, 1), (1, 2), (2, 1), (2, 2), (3, 1), (3, 2)]

字典推導式

word = 'letters'
letter_counts = {letter : word.count(letter) for letter in set(word)}  #利用set()提高演算法效率
print(letter_counts)
{'t': 2, 'r': 1, 's': 1, 'l': 1, 'e': 2}

集合推導式

a_set = {number for number in range(1, 6) if number % 3 == 1}
print(a_set)
{1, 4}

生成器推導式

不存在元組推導式,只返回生成器物件

number_thing = (number for number in range(1, 6))
print(type(number_thing))  #返回了一個物件

number_list = list(number_thing)
print(number_list)
#只能使用一次便被銷燬
try_again = list(number_thing)
print(try_again)
<class 'generator'>
[1, 2, 3, 4, 5]
[]

函式

def agree():
    return True;
if agree():
    print("yes")
yes
  • None用法
thing = None
if thing is None:
    print("Nothing!")
else:
    print("Something")
Nothing!
  • 位置引數
def menu(wine, entree, dessert):
    return {"wine" : wine, "entree" : entree, "dessert" : dessert}
menu('cha', 'bagel', 'bor')
{'wine': 'cha', 'entree': 'bagel', 'dessert': 'bor'}
  • 關鍵字引數
menu('foc', dessert = 'flan', entree = 'fish')
{'wine': 'foc', 'entree': 'fish', 'dessert': 'flan'}
  • 指定預設引數值
def menu(wine, entree, dessert = 'pudding'):
    return {"wine" : wine, "entree" : entree, "dessert" : dessert}
  • 只有第一次呼叫時,列表為空
def duggy(arg, result = []):
    result.append(arg)
    print(result)
    
duggy('a')
duggy('b')  #再次呼叫為銷燬原列表
['a']
['a', 'b']
#解決一
def duggy(arg):
    result = []
    result.append(arg)
    print(result)
    
duggy('a')
duggy('b')
['a']
['b']
#解決二
def duggy(arg, result = None):
    if result is None:
        result = []
    result.append(arg)
    print(result)
    
duggy('a')
duggy('b')
['a']
['b']

使用*收集位置引數(以元組的方式返回)

def number_print(number1, number2, *args):
    print("number1 = ", number1)
    print("number2 = ", number2)
    print("others = ", args)
    
number_print(11, 15, 1, 2, 3, 4)
number1 =  11
number2 =  15
others =  (1, 2, 3, 4)

使用**收集關鍵字引數(以字典的方式返回)

def print_kwargs(**kwargs):
    print(kwargs)
    
print_kwargs(x = 1, y = 2, z = 3, i = 4, j = 5)
{'x': 1, 'y': 2, 'z': 3, 'i': 4, 'j': 5}

文件字串

def echo(anything):
    'echo returns its input argument'
    return anything

help(echo)
print("else:", echo.__doc__)
Help on function echo in module __main__:

echo(anything)
    echo returns its input argument

else: echo returns its input argument

函式呼叫函式

def add_args(arg1, arg2):
    print(arg1 + arg2)
    
def run_something_with_args(func, arg1, arg2):
    '呼叫add_args函式,arg1為add_args的第一個引數...'
    func(arg1, arg2)
    
run_something_with_args(add_args, 5, 9)

14
  • 使用*args和**kwargs
def sum_args(*args):
    return sum(args)

def run_with_args(func, *args):
    return func(*args)

run_with_args(sum_args, 1, 2, 3, 4, 5)
15

內部函式

def outer(a, b):
    def inner(c, d):
        return c + d
    return inner(a, b)

outer(1, 2)
3

閉包

def knight2(saying):
    def inner2():
        return "We are the knights who say: '%s'" % saying
    return inner2

a = knight2('white')
b = knight2('black')

print("a() = ", a())
print("b() = ", b())

a() =  We are the knights who say: 'white'
b() =  We are the knights who say: 'black'

匿名函式:lambda()函式

#定義一個普通函式
def edit_story(words, func):
    for word in words:
        print(func(word))
#定義一個列表和操作列表函式        
stairs = ['yellow', 'black', 'white', 'blue']
def enliven(word):
    return word.capitalize() + '!'
#普通呼叫
edit_story(stairs, enliven)

#使用lambda()函式
edit_story(stairs, lambda word : word.capitalize() + '!')
Yellow!
Black!
White!
Blue!
Yellow!
Black!
White!
Blue!

生成器

def my_range(first = 0, last = 10, step = 1):
    number = first
    while number < last:
        yield number
        number += step
        
        
ranger = my_range(1, 5)        
for x in ranger:
    print(x)
1
2
3
4

裝飾器

  • 函式定義
def document_it(func):
    def new_function(*args, **kwargs):
        print("Name: ", func.__name__)
        print("arg: ", args)
        print("kwargs: ", kwargs)
        result = func(*args, **kwargs)
        print("result: ", result)
        return result
    return new_function

  • 呼叫方法1
def add_ints(a, b):
    return a + b

cooler_add_ints = document_it(add_ints)
print(cooler_add_ints(3, 5))
Name:  add_ints
arg:  (3, 5)
kwargs:  {}
result:  8
8
  • 呼叫方法2
@document_it
def add_ints(a, b):
    return a + b

add_ints(3, 5)
Name:  add_ints
arg:  (3, 5)
kwargs:  {}
result:  8





8

一個函式可以有多個裝飾器

  • 定義一個新裝飾器
def square_it(func):
    def new_function(*args, **kwargs):
        result = func(*args, **kwargs)
        return result*result
    return new_function
Name:  new_function
arg:  (3, 5)
kwargs:  {}
result:  64





64
  • 順序1
@document_it
@square_it
def add_ints(a, b):
    return a + b

add_ints(3, 5)
Name:  new_function
arg:  (3, 5)
kwargs:  {}
result:  64





64
  • 順序2
@square_it
@document_it
def add_ints(a, b):
    return a + b

add_ints(3, 5)
Name:  add_ints
arg:  (3, 5)
kwargs:  {}
result:  8





64

全域性和區域性

animal = 'dog'
def change_animal():
    global animal
    animal = 'cat'
    print("animal is ", animal)
    
print(animal)
change_animal()
print(animal)
dog
animal is  cat
cat

locals()返回一個全域性名稱空間內容的字典

globals()返回一個全域性名稱空間內容的字典

animal = 'dog'
def change_local():
    animal = 'cat'
    print('locals: ', locals())
    
print(animal)
change_local()
print(animal)

print('globals: ', globals())

dog
locals:  {'animal': 'cat'}
dog
globals:  {'__name__': '__main__', '__doc__': 'Automatically created module for IPython interactive environment', '__package__': None, '__loader__': None, '__spec__': None, '__builtin__': <module 'builtins' (built-in)>, '__builtins__': <module 'builtins' (built-in)>, '_ih': ['', 'def knight2(saying):\n    def inner2():\n        return "We are the knights who say: \'%s\'" % saying\n    return inner2\n\na = knight2(\'white\')\nb = knight2(\'black\')\n\nprint("a() = ", a())\nprint("b() = ", b())', "#定義一個普通函式\ndef edit_story(words, func):\n    for word in words:\n        print(func(word))\n#定義一個列表和操作列表函式        \nstairs = ['yellow', 'black', 'white', 'blue']\ndef enliven(word):\n    return word.capitalize() + '!'\n#普通呼叫\nedit_story(stairs, enliven)", "#定義一個普通函式\ndef edit_story(words, func):\n    for word in words:\n        print(func(word))\n#定義一個列表和操作列表函式        \nstairs = ['yellow', 'black', 'white', 'blue']\ndef enliven(word):\n    return word.capitalize() + '!'\n#普通呼叫\nedit_story(stairs, enliven)\n\n#使用lambda()函式\nedit_story(stairs, lambda word : word.capitalize() + '!')", 'def my_range(first = 0, last = 10, step = 1):\n    number = first\n    while number < last:\n        yield number\n        number += step\n        \n        \nmy_range(1, 5)        ', 'def my_range(first = 0, last = 10, step = 1):\n    number = first\n    while number < last:\n        yield number\n        number += step\n        \n        \nranger = my_range(1, 5)        \nfor x in ranger:\n    print(x)', 'def document_it(func):\n    def new_function(*args, **kwargs):\n        print("Name: ", func.__name__)\n        print("arg: ", args)\n        print("kwargs: ", kwargs)\n        result = func(*args, **kwargs)\n        return result\n    return new_function\n\ndef add_ints(a, b):\n    return a + b', 'def document_it(func):\n    def new_function(*args, **kwargs):\n        print("Name: ", func.__name__)\n        print("arg: ", args)\n        print("kwargs: ", kwargs)\n        result = func(*args, **kwargs)\n        return result\n    return new_function\n\ndef add_ints(a, b):\n    return a + b', 'def document_it(func):\n    def new_function(*args, **kwargs):\n        print("Name: ", func.__name__)\n        print("arg: ", args)\n        print("kwargs: ", kwargs)\n        result = func(*args, **kwargs)\n        return result\n    return new_function\n\ndef add_ints(a, b):\n    return a + b\ncooler_add_ints = document_it(add_ints)\nprint(cooler_add_ints(3, 5))', 'def document_it(func):\n    def new_function(*args, **kwargs):\n        print("Name: ", func.__name__)\n        print("arg: ", args)\n        print("kwargs: ", kwargs)\n        result = func(*args, **kwargs)\n        print("result: ", result)\n        return result\n    return new_function\n\ndef add_ints(a, b):\n    return a + b\ncooler_add_ints = document_it(add_ints)\nprint(cooler_add_ints(3, 5))', 'def document_it(func):\n    def new_function(*args, **kwargs):\n        print("Name: ", func.__name__)\n        print("arg: ", args)\n        print("kwargs: ", kwargs)\n        result = func(*args, **kwargs)\n        print("result: ", result)\n        return result\n    return new_function\n\ndef add_ints(a, b):\n    return a + b', 'cooler_add_ints = document_it(add_ints)\nprint(cooler_add_ints(3, 5))', '@document_it\ndef add_ints(a, b):\n    return a + b\nadd_ints(3, 5)', 'def square_it(func):\n    def new_function(*args, **kwargs):\n        result = func(*args, **kwargs)\n        return result*result\n    return new_function\n\[email protected]_it\[email protected]_it\ndef add_ints(a, b):\n    return a + b\n\nadd_ints(3, 5)', '@document_it\[email protected]_it\ndef add_ints(a, b):\n    return a + b\n\nadd_ints(3, 5)', '@square_it\[email protected]_it\ndef add_ints(a, b):\n    return a + b\n\nadd_ints(3, 5)', 'animal = \'dog\'\ndef change_animal():\n    global animal\n    animal = \'cat\'\n    print("animal is ", animal)\n    \nanimal\nchange_animal()', 'animal = \'dog\'\ndef change_animal():\n    global animal\n    animal = \'cat\'\n    print("animal is ", animal)\n    \nprint(animal)\nchange_animal()', 'animal = \'dog\'\ndef change_animal():\n    global animal\n    animal = \'cat\'\n    print("animal is ", animal)\n    \nprint(animal)\nchange_animal()\nprint(animal)', "animal = 'dog'\ndef change_local():\n    animal = 'cat'\n    print(animal)\n    \nprint(animal)\nchange_local()", "animal = 'dog'\ndef change_local():\n    animal = 'cat'\n    print(animal)\n    \nprint(animal)\nchange_local()\nprint(animal)", "animal = 'dog'\ndef change_local():\n    animal = 'cat'\n    print('locals: ', locals())\n    \nprint(animal)\nchange_local()\nprint(animal)\n\nprint('globals: ', globals())"], '_oh': {4: <generator object my_range at 0x0000020C07CEC678>, 12: 8, 13: 64, 14: 64, 15: 64}, '_dh': ['D:\\Mydata\\STU\\Python\\FirstTest'], 'In': ['', 'def knight2(saying):\n    def inner2():\n        return "We are the knights who say: \'%s\'" % saying\n    return inner2\n\na = knight2(\'white\')\nb = knight2(\'black\')\n\nprint("a() = ", a())\nprint("b() = ", b())', "#定義一個普通函式\ndef edit_story(words, func):\n    for word in words:\n        print(func(word))\n#定義一個列表和操作列表函式        \nstairs = ['yellow', 'black', 'white', 'blue']\ndef enliven(word):\n    return word.capitalize() + '!'\n#普通呼叫\nedit_story(stairs, enliven)", "#定義一個普通函式\ndef edit_story(words, func):\n    for word in words:\n        print(func(word))\n#定義一個列表和操作列表函式        \nstairs = ['yellow', 'black', 'white', 'blue']\ndef enliven(word):\n    return word.capitalize() + '!'\n#普通呼叫\nedit_story(stairs, enliven)\n\n#使用lambda()函式\nedit_story(stairs, lambda word : word.capitalize() + '!')", 'def my_range(first = 0, last = 10, step = 1):\n    number = first\n    while number < last:\n        yield number\n        number += step\n        \n        \nmy_range(1, 5)        ', 'def my_range(first = 0, last = 10, step = 1):\n    number = first\n    while number < last:\n        yield number\n        number += step\n        \n        \nranger = my_range(1, 5)        \nfor x in ranger:\n    print(x)', 'def document_it(func):\n    def new_function(*args, **kwargs):\n        print("Name: ", func.__name__)\n        print("arg: ", args)\n        print("kwargs: ", kwargs)\n        result = func(*args, **kwargs)\n        return result\n    return new_function\n\ndef add_ints(a, b):\n    return a + b', 'def document_it(func):\n    def new_function(*args, **kwargs):\n        print("Name: ", func.__name__)\n        print("arg: ", args)\n        print("kwargs: ", kwargs)\n        result = func(*args, **kwargs)\n        return result\n    return new_function\n\ndef add_ints(a, b):\n    return a + b', 'def document_it(func):\n    def new_function(*args, **kwargs):\n        print("Name: ", func.__name__)\n        print("arg: ", args)\n        print("kwargs: ", kwargs)\n        result = func(*args, **kwargs)\n        return result\n    return new_function\n\ndef add_ints(a, b):\n    return a + b\ncooler_add_ints = document_it(add_ints)\nprint(cooler_add_ints(3, 5))', 'def document_it(func):\n    def new_function(*args, **kwargs):\n        print("Name: ", func.__name__)\n        print("arg: ", args)\n        print("kwargs: ", kwargs)\n        result = func(*args, **kwargs)\n        print("result: ", result)\n        return result\n    return new_function\n\ndef add_ints(a, b):\n    return a + b\ncooler_add_ints = document_it(add_ints)\nprint(cooler_add_ints(3, 5))', 'def document_it(func):\n    def new_function(*args, **kwargs):\n        print("Name: ", func.__name__)\n        print("arg: ", args)\n        print("kwargs: ", kwargs)\n        result = func(*args, **kwargs)\n        print("result: ", result)\n        return result\n    return new_function\n\ndef add_ints(a, b):\n    return a + b', 'cooler_add_ints = document_it(add_ints)\nprint(cooler_add_ints(3, 5))', '@document_it\ndef add_ints(a, b):\n    return a + b\nadd_ints(3, 5)', 'def square_it(func):\n    def new_function(*args, **kwargs):\n        result = func(*args, **kwargs)\n        return result*result\n    return new_function\n\[email protected]_it\[email protected]_it\ndef add_ints(a, b):\n    return a + b\n\nadd_ints(3, 5)', '@document_it\[email protected]_it\ndef add_ints(a, b):\n    return a + b\n\nadd_ints(3, 5)', '@square_it\[email protected]_it\ndef add_ints(a, b):\n    return a + b\n\nadd_ints(3, 5)', 'animal = \'dog\'\ndef change_animal():\n    global animal\n    animal = \'cat\'\n    print("animal is ", animal)\n    \nanimal\nchange_animal()', 'animal = \'dog\'\ndef change_animal():\n    global animal\n    animal = \'cat\'\n    print("animal is ", animal)\n    \nprint(animal)\nchange_animal()', 'animal = \'dog\'\ndef change_animal():\n    global animal\n    animal = \'cat\'\n    print("animal is ", animal)\n    \nprint(animal)\nchange_animal()\nprint(animal)', "animal = 'dog'\ndef change_local():\n    animal = 'cat'\n    print(animal)\n    \nprint(animal)\nchange_local()", "animal = 'dog'\ndef change_local():\n    animal = 'cat'\n    print(animal)\n    \nprint(animal)\nchange_local()\nprint(animal)", "animal = 'dog'\ndef change_local():\n    animal = 'cat'\n    print('locals: ', locals())\n    \nprint(animal)\nchange_local()\nprint(animal)\n\nprint('globals: ', globals())"], 'Out': {4: <generator object my_range at 0x0000020C07CEC678>, 12: 8, 13: 64, 14: 64, 15: 64}, 'get_ipython': <bound method InteractiveShell.get_ipython of <ipykernel.zmqshell.ZMQInteractiveShell object at 0x0000020C07BA1E48>>, 'exit': <IPython.core.autocall.ZMQExitAutocall object at 0x0000020C059DA7F0>, 'quit': <IPython.core.autocall.ZMQExitAutocall object at 0x0000020C059DA7F0>, '_': 64, '__': 64, '___': 64, '_i': "animal = 'dog'\ndef change_local():\n    animal = 'cat'\n    print(animal)\n    \nprint(animal)\nchange_local()\nprint(animal)", '_ii': "animal = 'dog'\ndef change_local():\n    animal = 'cat'\n    print(animal)\n    \nprint(animal)\nchange_local()", '_iii': 'animal = \'dog\'\ndef change_animal():\n    global animal\n    animal = \'cat\'\n    print("animal is ", animal)\n    \nprint(animal)\nchange_animal()\nprint(animal)', '_i1': 'def knight2(saying):\n    def inner2():\n        return "We are the knights who say: \'%s\'" % saying\n    return inner2\n\na = knight2(\'white\')\nb = knight2(\'black\')\n\nprint("a() = ", a())\nprint("b() = ", b())', 'knight2': <function knight2 at 0x0000020C07CDD620>, 'a': <function knight2.<locals>.inner2 at 0x0000020C07CDD378>, 'b': <function knight2.<locals>.inner2 at 0x0000020C07CDD598>, '_i2': "#定義一個普通函式\ndef edit_story(words, func):\n    for word in words:\n        print(func(word))\n#定義一個列表和操作列表函式        \nstairs = ['yellow', 'black', 'white', 'blue']\ndef enliven(word):\n    return word.capitalize() + '!'\n#普通呼叫\nedit_story(stairs, enliven)", 'edit_story': <function edit_story at 0x0000020C07CDD950>, 'stairs': ['yellow', 'black', 'white', 'blue'], 'enliven': <function enliven at 0x0000020C07CDD6A8>, '_i3': "#定義一個普通函式\ndef edit_story(words, func):\n    for word in words:\n        print(func(word))\n#定義一個列表和操作列表函式        \nstairs = ['yellow', 'black', 'white', 'blue']\ndef enliven(word):\n    return word.capitalize() + '!'\n#普通呼叫\nedit_story(stairs, enliven)\n\n#使用lambda()函式\nedit_story(stairs, lambda word : word.capitalize() + '!')", '_i4': 'def my_range(first = 0, last = 10, step = 1):\n    number = first\n    while number < last:\n        yield number\n        number += step\n        \n        \nmy_range(1, 5)        ', 'my_range': <function my_range at 0x0000020C07CDDC80>, '_4': <generator object my_range at 0x0000020C07CEC678>, '_i5': 'def my_range(first = 0, last = 10, step = 1):\n    number = first\n    while number < last:\n        yield number\n        number += step\n        \n        \nranger = my_range(1, 5)        \nfor x in ranger:\n    print(x)', 'ranger': <generator object my_range at 0x0000020C07CEC888>, 'x': 4, '_i6': 'def document_it(func):\n    def new_function(*args, **kwargs):\n        print("Name: ", func.__name__)\n        print("arg: ", args)\n        print("kwargs: ", kwargs)\n        result = func(*args, **kwargs)\n        return result\n    return new_function\n\ndef add_ints(a, b):\n    return a + b', 'document_it': <function document_it at 0x0000020C07CDDBF8>, 'add_ints': <function square_it.<locals>.new_function at 0x0000020C07CDD730>, '_i7': 'def document_it(func):\n    def new_function(*args, **kwargs):\n        print("Name: ", func.__name__)\n        print("arg: ", args)\n        print("kwargs: ", kwargs)\n        result = func(*args, **kwargs)\n        return result\n    return new_function\n\ndef add_ints(a, b):\n    return a + b', '_i8': 'def document_it(func):\n    def new_function(*args, **kwargs):\n        print("Name: ", func.__name__)\n        print("arg: ", args)\n        print("kwargs: ", kwargs)\n        result = func(*args, **kwargs)\n        return result\n    return new_function\n\ndef add_ints(a, b):\n    return a + b\ncooler_add_ints = document_it(add_ints)\nprint(cooler_add_ints(3, 5))', 'cooler_add_ints': <function document_it.<locals>.new_function at 0x0000020C07CDDE18>, '_i9': 'def document_it(func):\n    def new_function(*args, **kwargs):\n        print("Name: ", func.__name__)\n        print("arg: ", args)\n        print("kwargs: ", kwargs)\n        result = func(*args, **kwargs)\n        print("result: ", result)\n        return result\n    return new_function\n\ndef add_ints(a, b):\n    return a + b\ncooler_add_ints = document_it(add_ints)\nprint(cooler_add_ints(3, 5))', '_i10': 'def document_it(func):\n    def new_function(*args, **kwargs):\n        print("Name: ", func.__name__)\n        print("arg: ", args)\n        print("kwargs: ", kwargs)\n        result = func(*args, **kwargs)\n        print("result: ", result)\n        return result\n    return new_function\n\ndef add_ints(a, b):\n    return a + b', '_i11': 'cooler_add_ints = document_it(add_ints)\nprint(cooler_add_ints(3, 5))', '_i12': '@document_it\ndef add_ints(a, b):\n    return a + b\nadd_ints(3, 5)', '_12': 8, '_i13': 'def square_it(func):\n    def new_function(*args, **kwargs):\n        result = func(*args, **kwargs)\n        return result*result\n    return new_function\n\[email protected]_it\[email protected]_it\ndef add_ints(a, b):\n    return a + b\n\nadd_ints(3, 5)', 'square_it': <function square_it at 0x0000020C07CDDA60>, '_13': 64, '_i14': '@document_it\[email protected]_it\ndef add_ints(a, b):\n    return a + b\n\nadd_ints(3, 5)', '_14': 64, '_i15': '@square_it\[email protected]_it\ndef add_ints(a, b):\n    return a + b\n\nadd_ints(3, 5)', '_15': 64, '_i16': 'animal = \'dog\'\ndef change_animal():\n    global animal\n    animal = \'cat\'\n    print("animal is ", animal)\n    \nanimal\nchange_animal()', 'animal': 'dog', 'change_animal': <function change_animal at 0x0000020C07CDDD90>, '_i17': 'animal = \'dog\'\ndef change_animal():\n    global animal\n    animal = \'cat\'\n    print("animal is ", animal)\n    \nprint(animal)\nchange_animal()', '_i18': 'animal = \'dog\'\ndef change_animal():\n    global animal\n    animal = \'cat\'\n    print("animal is ", animal)\n    \nprint(animal)\nchange_animal()\nprint(animal)', '_i19': "animal = 'dog'\ndef change_local():\n    animal = 'cat'\n    print(animal)\n    \nprint(animal)\nchange_local()", 'change_local': <function change_local at 0x0000020C07CDD840>, '_i20': "animal = 'dog'\ndef change_local():\n    animal = 'cat'\n    print(animal)\n    \nprint(animal)\nchange_local()\nprint(animal)", '_i21': "animal = 'dog'\ndef change_local():\n    animal = 'cat'\n    print('locals: ', locals())\n    \nprint(animal)\nchange_local()\nprint(animal)\n\nprint('globals: ', globals())"}

異常處理

short_list = [1, 2, 3]
position = 5
try:
    short_list[position]
except:
    print('error!')
error!
while True:
    value = input('q to quit')
    if value == 'q':
        break
    try:
        position = int(value)
        print(short_list[position])
    except IndexError as error:
        print('IndexError')
    except Exception as other:
        print('Exception')
q to quit5
Exception
q to quitq

編寫異常

class UppercaseExcption(Exception):
    pass

words = ['a', 'b', 'C']
for word in words:
    if word.isupper():
        raise UppercaseExcption(word)
---------------------------------------------------------------------------

UppercaseExcption                         Traceback (most recent call last)

<ipython-input-5-6dfe130bfbde> in <module>()
      5 for word in words:
      6     if word.isupper():
----> 7         raise UppercaseExcption(word)


UppercaseExcption: C
  • 訪問異常物件本身
try