1

In this code, pelts is defined inside the with statement to open a file. The command 'print' is able to access it (Python 2.7). Do code sections like with, for, while not limit scope like a function would?

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
hikinthru
  • 49
  • 7

2 Answers2

3

In python only functions and classes defines new scopes. if, for, while, with etc do not!

Bakuriu
  • 98,325
  • 22
  • 197
  • 231
1

pelts is in the global scope so it is available outside with. with doesn't create its own scope.

QB_
  • 109
  • 7