我正在学习编码,我得到了创建程序的任务。 (摘自《 Python入门》,第4版,第8章,练习14。) 我已经创建了所有函数并全部调用了它们,但该程序将仅执行一个函数,其余函数均不返回。我想念什么?
def main():
gas_file=open('GasPrices.txt', 'r')
average_per_year(gas_file)
print()
average_per_month(gas_file)
print()
highest_lowers(gas_file)
print()
lowest_to_highest(gas_file)
print()
highest_to_lowest(gas_file)
gas_file.close()
以下是完整代码:https://pastecode.xyz/view/b007ccb0 我没有收到任何错误警告或任何东西
亲切的问候,朱尔斯
答案 0 :(得分:3)
您调用的第一个函数读到gas_file
的结尾,直到结尾。由于您将相同的文件句柄传递给所有其他函数,因此它们只会看到一个空文件。
如果您不是将复制并粘贴用于读取文件的代码复制到所有这些功能中,那么您的代码将起作用(并且比您尝试做的事情更简单,更快),因此,每个代码都试图重新读取文件并重复执行相同的工作,您只有一个函数将文件解析为一些有用的数据结构(如列表或值的字典),然后让所有其他函数仅从文件中读取数据。 / p>
类似的东西:
from typing import List, NamedTuple
class GasPrice(NamedTuple):
month: int
year: int
price: float
def read_prices(gas_file: str) -> List[GasPrice]:
"""Load a list of GasPrices from a file."""
with open(gas_file, 'r') as f:
return [
GasPrice(
int(line[:2]), # month
int(line[6:10]), # year
float(line[11:]) # price
)
for line in f
]
def main() -> None:
prices = read_prices('GasPrices.txt')
# ... do stuff with prices