1

I'm writing a program that loads a list of data from a file and I need the program to differentiate if the data in the line is either a string or an integer. However in the code I have done the program doesn't differentiate numbers from strings.

An example of the list of data I have:

HAJOS
ALFRED
1896
1

My code:

def medalsYear():
  times = 1
  totalGold = 0
  totalSilver = 0
  totalBronze = 0
  while times <= 5:
    alpha = fob.readline() #reads file line by line#
    print(alpha)
    times = times + 1
    if type(alpha) == int:
        if alpha == 1:
            totalGold = totalGold + 1
            print("gold medal won")
        elif alpha == 2:
            totalSilver = totalSilver + 1
            print("silver medal won")
        elif alpha == 3:
            totalBronze = totalBronze + 1
            print("bronze medal won")
        else:
            pass
    else:
        print('is a string')
  print(totalGold, "Gold medals won")
  print(totalSilver, "Silver medals won")
  print(totalBronze, "Bronze medals won")

My problem is that when the program reads a line that has an integer, it doesn't determine correctly if the line contains an integer and from there run through the corresponding if statement. Currently my output looks like this.

HAJOS
is a string
ALFRED
is a string
1896
is a string
1
is a string

is a string
0 Gold medals won
0 Silver medals won
0 Bronze medals won
done
3
  • 1
    As your output shows, all the values are in fact strings. When you read data from a file like that, you are always reading strings. If you want to convert them to ints, you would need to do that yourself. Commented Sep 19, 2014 at 19:02
  • 1
    Hint: int(alpha) will convert alpha to a integer or throw a ValueError if it can't. Commented Sep 19, 2014 at 19:04
  • if alpha.isdigit() will also work Commented Sep 19, 2014 at 19:18

2 Answers 2

2

Data read from a file is always going to be a string. You'll need to try and convert those lines, not test their type:

try:
    alpha = int(alpha)
    if alpha == 1:
        totalGold = totalGold + 1
        print("gold medal won")
    elif alpha == 2:
        totalSilver = totalSilver + 1
        print("silver medal won")
    elif alpha == 3:
        totalBronze = totalBronze + 1
        print("bronze medal won")
except ValueError:
    print('is a string')

int() will raise a ValueError when alpha cannot be interpreted as an integer number. The exception, if raised, causes Python to jump to the except ValueError: block instead of executing the rest of the try: suite.

Sign up to request clarification or add additional context in comments.

3 Comments

ahh much better than my (now deleted) answer ... way to read the question ... :P +1
@JoranBeasley: editing a question into some semblance of shape helps with the comprehension. :-)
I just tried implementing that into my code and it worked for the most part. The only issue though is withing using that exactly it doesn't update the totalmount of medals won in any case. It does correctly convert the strings to integers however. Edit: Nevermind, there was just a syntax error on my part.
0

You can make a dict where the keys are "1","2" and "3" to correspond to gold, silver, bronze and use dict.get.

with open(infile) as f:
    times = 1
    medal_dict = {"1": 0, "2": 0, "3": 0}
    while times <= 5:
        alpha = f.readline().rstrip()  #reads file line by line#
        times += 1
        if medal_dict.get(alpha) is not None:
            medal_dict[alpha] += 1
        else:
            print("is a string")
    print(medal_dict["1"], "Gold medals won")
    print(medal_dict["2"], "Silver medals won")
    print(medal_dict["3"], "Bronze medals won")

Which outputs:

(1, 'Gold medals won')
(0, 'Silver medals won')
(0, 'Bronze medals won')

If you want to print when a medal is won through the loop:

with open(infile) as f:
    times = 1
    medal_dict = {"1": [0,"gold"], "2": [0,"silver"], "3": [0,"bronze"]}
    while times <= 5:
        alpha = f.readline().rstrip()  #reads file line by line#
        print(alpha)
        times += 1#
        check = medal_dict.get(alpha)
        if check is not None:
            medal_dict[alpha][0] += 1
            print("{} medal won".format(check[1]))
        else:
            print("is a string")
    print(medal_dict["1"][0], "Gold medals won")
    print(medal_dict["2"][0], "Silver medals won")
    print(medal_dict["3"][0], "Bronze medals won")

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.