Published 2021-12-02

Functions - 函数

函数的定义

函数的定义是一个特殊的可复用的代码块,它的第一行必须是函数的声明,第二行开始是函数的实现。

#定义函数
def sumcount(n):
    '''
    Returns the sum of the first n integers
    '''
    total = 0
    while n > 0:
        total += n
        n -= 1
    return total
#调用函数
a = sumcount(100)

标准函数

python 中的标准函数是一些内置的函数,通过import调用。

import math
x = math.sqrt(10)

import urllib.request
u = urllib.request.urlopen('http://www.python.org/')
data = u.read()

错误和异常

错误和异常是 python 中的两个主要概念,错误是指程序运行过程中发生的错误,异常是指程序运行过程中抛出的异常。例如:

>>> int('N/A')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'N/A'
>>>

捕获、处理异常

异常可以通过tryexcept来捕获,也可以通过tryfinally来处理。

for line in f:
    fields = line.split()
    try:
        shares = int(fields[1])
    except ValueError:
        print("Couldn't parse", line)
    ...