0

Hi guys, trying to write a function that reads a text file and counts the periods in it and prints the answer. I keep getting an error saying that UnboundLocalError: local variable 'periods' referenced before assignment. I am not sure how to fix this. We must use a function to calculate the periods and we can not use built in things like .count, etc.

Here is my code:

def percount(myFile):
    for char in myFile:
        if char == '.':
            periods +=1
        return periods

myFile = open("inn.txt", "r")

p = percount(myFile)
print p
4
Contributors
5
Replies
8
Views
5 Years
Discussion Span
Last Post by bigredaltoid
0

Just a few corrections are needed, read the comments ...

def percount(myFile):
    # set period count to zero at start
    periods = 0
    # loop through each character in the text string
    for char in myFile.read():
        #print char, periods  # testing
        if char == '.':
            periods += 1
    # when done with the loop return period count value
    return periods

# create file handle
myFile = open("inn.txt", "r")

p = percount(myFile)
print p

Edited by vegaseat: ed

Comments
very detailed explanation
0

I made the corrections I believe but the code still returns 0 even though there are 19 periods in the document. Help?

def percount(myFile):

    periods = 0

    for char in myFile.read():

        if char == '.':
            periods +=1

        return periods

myFile = open("inn.txt", "r")

p = percount(myFile)
print p
0

I made the corrections I believe but the code still returns 0 even though there are 19 periods in the document. Help?

def percount(myFile):

    periods = 0

    for char in myFile.read():

        if char == '.':
            periods +=1

        return periods

myFile = open("inn.txt", "r")

p = percount(myFile)
print p

Carefully compare your code with vegaseat's code and the light will come...

@vegaseat: nice to see you again Mr moderator !

0

Wow that was a dumb mistake on my part. My apologies. Thank you for the help though. It works now :)

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.