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

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 5 Years Ago by vegaseat: ed

Comments
very detailed explanation

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

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 !

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.