954,515 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Function that counts periods in a text file.

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
bigredaltoid
Light Poster
26 posts since Oct 2011
Reputation Points: 10
Solved Threads: 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
vegaseat
DaniWeb's Hypocrite
Moderator
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 

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
bigredaltoid
Light Poster
26 posts since Oct 2011
Reputation Points: 10
Solved Threads: 0
 

Line 10 is incorrectly indented inside the for loop.

pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

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 !

Gribouillis
Posting Maven
Moderator
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691
 

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

bigredaltoid
Light Poster
26 posts since Oct 2011
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You