从代码中学Python语法五(持续更新)

__author__ = 'hunterhug'
# -*- coding:utf-8 -*-
import sys


def e1():
    try:
        f = open('myfile.txt')
        s = f.readline()
        i = int(s.strip())
    except IOError as err:
        print("I/O error: {0}".format(err))
    except ValueError:
        print("Could not convert data to an integer.")
    except:
        print("Unexpected error:", sys.exc_info()[0])
        raise


# try ... except 语句可以带有一个 else子句 ,
# 该子句只能出现在所有 except 子句之后。
# 当 try 语句没有抛出异常时,需要执行一些代码,可以使用这个子句。例如:

def e2():
    for arg in sys.argv[1:]:
        try:
            f = open(arg, 'r')
        except IOError:
            print('cannot open', arg)
        else:
            print(arg, 'has', len(f.readlines()), 'lines')
            f.close()


def e3():
    try:
        raise Exception('spam', 'eggs')
    except Exception as inst:
        print(type(inst))  # the exception instance
        print(inst.args)  # arguments stored in .args
        print(inst)
        print(inst.__str__())  # __str__ allows args to be printed directly,
        # but may be overridden in exception subclasses
        x, y = inst.args  # unpack args
        print('x =', x)
        print('y =', y)


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

def divide(x, y):
     try:
         result = x / y
     except ZeroDivisionError:
         print("division by zero!")
     else:
         print("result is", result)
     finally:
         print("executing finally clause")

def scope_test():
    def do_local():
        spam = "local spam"
    def do_nonlocal():
        nonlocal spam
        spam = "nonlocal spam"
    def do_global():
        global spam
        spam = "global spam"

    spam = "test spam"
    do_local()
    print("After local assignment:", spam)
    do_nonlocal()
    print("After nonlocal assignment:", spam)
    do_global()
    print("After global assignment:", spam)

scope_test()
print("In global scope:", spam)
# local 赋值语句是无法改变 scope_test 的 spam 绑定。
#  nonlocal 赋值语句改变了 scope_test 的 spam 绑定,
# 并且 global 赋值语句从模块级改变了 spam 绑定。

 

你可能感兴趣的:(从代码中学Python语法五(持续更新))