Matt
Matt

Reputation: 3190

Why is my if statement in Python evaluating to False?

My task is to have the user input a year and use that input to search line-by-line within a text file for the total number of gold medals won that year by Olympian athletes. The text file contains thousands of entries sorted like this:

LAST_NAME
FIRST_NAME
YEAR
POSITION
\n

I thought the way to do it would be to make sure the year matches, and if it does, set the value of a variable called blockIsValid to True. The program would then check if the block is valid (so as to avoid considering the gold medals of other years) and if it is, check for a gold medal by looking for a one (the position, indicating gold). blockIsValid is then reset to False after the gold medal is recorded in the variable goldMedals.

The checking the year part works but it never finds gold and instead shows this every time:enter image description here [NOTE] We're supposed to check every single line which is why there are a bunch of lines that say "incorrect year!"

def findAnnualMedals(year):
    blockIsValid = None
    goldMedals = 0
    file = open('athletes.txt', encoding='utf-8')
    for currentLine, line in enumerate(file):
        if line.strip() == year:
            print("Correct year!")
            blockIsValid = True
        else:
            print("Incorrect year!")
            blockIsValid = False


        if blockIsValid == True:
            if line.strip() == "1":
                print("Gold!")
                goldMedals += 1

            else:
                print("Not gold!")
            blockIsValid = False

Upvotes: 1

Views: 130

Answers (1)

John Kugelman
John Kugelman

Reputation: 362037

This'll be easier if you rearrange the logic a bit. Put the gold medal check at the top in front of the year check.

foundYear = False

for currentLine, line in enumerate(file):
    if foundYear:
        if line.strip() == "1":
            print("Gold!")
            goldMedals += 1

        else:
            print("Not gold!")

        foundYear = False

    elif line.strip() == year:
        print("Correct year!")
        foundYear = True

    else:
        print("Incorrect year!")

Upvotes: 1

Related Questions