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

Recommended Answers

All 5 Replies

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
commented: very detailed explanation +13

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

Line 10 is incorrectly indented inside the for loop.

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 :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.