# 3.1 脚本

### 什么是脚本？

# program.py

statement1
statement2
statement3
...


### 定义变量

def square(x):
return x*x

a = 42
b = a + 2     # Requires that a is defined

z = square(b) # Requires square and b to be defined


### 定义函数

def read_prices(filename):
prices = {}
with open(filename) as f:
for row in f_csv:
prices[row[0]] = float(row[1])
return prices


oldprices = read_prices('oldprices.csv')


### 什么是函数？

def funcname(args):
statement
statement
...
return result


def foo():
import math
print(math.sqrt(2))
help(math)


Python 中没有特殊语句（这使它很容易记住）。

### 函数定义

def foo(x):
bar(x)

def bar(x):
statements

# OR
def bar(x):
statements

def foo(x):
bar(x)


foo(3)        # foo must be defined already


### 自底向上的风格

# myprogram.py
def foo(x):
...

def bar(x):
...
foo(x)          # Defined above
...

def spam(x):
...
bar(x)          # Defined above
...

spam(42)            # Code that uses the functions appears at the end


### 文档字符串

def read_prices(filename):
'''
Read prices from a CSV file of name,price data
'''
prices = {}
with open(filename) as f:
for row in f_csv:
prices[row[0]] = float(row[1])
return prices


### 类型注解

def read_prices(filename: str) -> dict:
'''
Read prices from a CSV file of name,price data
'''
prices = {}
with open(filename) as f:
for row in f_csv:
prices[row[0]] = float(row[1])
return prices


## 练习

# report.py
import csv

'''
Read a stock portfolio file into a list of dictionaries with keys
name, shares, and price.
'''
portfolio = []
with open(filename) as f:

for row in rows:
stock = {
'name' : record['name'],
'shares' : int(record['shares']),
'price' : float(record['price'])
}
portfolio.append(stock)
return portfolio
...


...

# Output the report

headers = ('Name', 'Shares', 'Price', 'Change')
print('%10s %10s %10s %10s'  % headers)
print(('-' * 10 + ' ') * len(headers))
for row in report:
print('%10s %10d %10.2f %10.2f' % row)
...


### 练习 3.1：将程序构造为函数的集合

• 创建打印报告的函数 print_report(report)
• 修改程序的最后一部分，使其仅是一系列函数调用，而无需进行其它运算。

### 练习 3.2：为程序执行创建一个顶层函数

portfolio_report('Data/portfolio.csv', 'Data/prices.csv')


>>> portfolio_report('Data/portfolio2.csv', 'Data/prices.csv')
... look at the output ...
>>> files = ['Data/portfolio.csv', 'Data/portfolio2.csv']
>>> for name in files:
print(f'{name:-^43s}')
portfolio_report(name, 'Data/prices.csv')
print()

... look at the output ...
>>>


### 说明

Python 使在有一系列语句的文件中编写相对无结构的脚本变得很轻松。总体来说，无论何时，尽可能地利用函数通常总是更好的选择。在某些时候，脚本会不断增加，并且我们希望它更有组织。另外，一个鲜为人知的事实是，如果使用函数，Python 的运行会更快一些。

posted @ 2021-02-28 21:52  codists  阅读(221)  评论(0编辑  收藏  举报