gpt4 book ai didi

python - 关于 Python 中的作用域

转载 作者:太空宇宙 更新时间:2023-11-04 10:02:40 25 4
gpt4 key购买 nike

<分区>

在这段代码中,pelts 定义在 with 语句中以打开一个文件。命令“print”能够访问它(Python 2.7)。 withforwhile 等代码段是否不像函数那样限制范围?

def run_funct():
''' (input_type) -> output_type

Function docstring
'''

# Put the file into a file handler
with open('hopedale.txt') as hopedale_file:

# Read first line and move file cursor to the beginning of next line
hopedale_file.readline()

# We know that info lines begin on the second line, and 'startswith'
# a `#` symbol, skip these lines after processing the first one.
data = hopedale_file.readline().strip()
while data.startswith('#'):
data = hopedale_file.readline().strip()

# When the input line no longer begins with a '#' symbol, store
# the number of pelts on the first data line
pelts = int(data)

# Then process the rest of the lines with 'for ___ in'
for data in hopedale_file:
pelts += int(data.strip())

# Print pelts
print 'Number of pelts is:', pelts

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com