关于Python中的范围

时间:2017-03-12 16:49:52

标签: python

在此代码中,peltswith语句中定义以打开文件。命令'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

2 个答案:

答案 0 :(得分:3)

在python中函数和类定义新范围。 ifforwhilewith

答案 1 :(得分:1)

pelts位于全局范围内,因此可在with之外使用。 with没有创建自己的范围。