How can I read numbers as integers while also reading in names as strings from a data file?

87 Views Asked by At

Here's the code I wrote to put the names and numbers into a file:

def main():
    num_players = int(input("How many players are there?"))
    golf = open("golf.txt", 'w')
    for i in range(num_players):
        player_name = str(input("What is the player's name?"))
        player_score = int(input("What is their golf score?"))
        golf.write(player_name + '\n')
        golf.write(str(player_score) + '\n')
    golf.close()

main()

and the output:

Palmer
120
Nicholas
118
Dalton
150
Woods
122
Player
124

In the following code, I am trying to compare the scores to see whose golf score is the best and the worst. I keep getting an error because str object cannot be interpreted as an integer. How can I fix this?

def main():
    golf = open("golf.txt",'r')
    large = 125
    small = 119
    name=golf.readline()
    while name != '':
        for i in range(name):
            name = golf.readline()
            score = int(golf.readline())
            if score > large:
                large = score
                print(name,"is the worst at golf")
    while name != '':
        for i in range(name):
            name = golf.readline()
            score = int(golf.readline())
            if score < small:
                large = score
                print(name, "is the best at golf")

main()
3

There are 3 best solutions below

0
Kilian On
def main():
    file_reader = open("golf.txt",'r')
    raw_data = file_reader.read().split('\n')
    file_reader.close()
    data = list(zip(raw_data[::2], [int(i) for i in raw_data[1::2]]))

    # search for smallest
    si = 0
    sv = data[si][1]
    for i, v in enumerate(data):
        if v[1] < sv:
            sv = v[1]
            si = i

    # search for biggest
    mi = si
    mv = data[mi][1]
    for i, v in enumerate(data):
        if v[1] > mv:
            mv = v[1]
            mi = i

    print(f'{data[si][0]} is the worst player.')
    print(f'{data[mi][0]} is the best player.')
0
Arifa Chan On

Read() the file and filter out any empty string. Use zip() to generate pair of name and score based on start index and step. Compare large and small to int(score) and then print the corresponding name.

def main():
    large = 125
    small = 119
    with open('golf.txt') as file:
        golf = file.read().splitlines()
        golf = [line for line in golf if line != '']
        for name, score in zip(golf[0::2], golf[1::2]):
            if int(score) > large:
                print(name, "is the worst at golf")
            elif int(score) < small:
                print(name, "is the best at golf")

main()

# Nicholas is the best at golf
# Dalton is the worst at golf
1
Mark Tolonen On

Minimal changes to OP code, with comments:

with open("golf.txt") as golf: # make sure the file gets closed using with
    large = 0    # start small with largest
    small = 300  # start large with smallest

    # only one pass to read the file
    # compute small and large at the same time
    while name := golf.readline():  # while name is read... := is a newer feature of Python
        score = int(golf.readline()) # also read score
        if score > large:
            large = score
            worst = name.strip()  # make sure to save the worst name
        if score < small:
            small = score
            best = name.strip()   # and the best name

    # print results when done, not in the loop
    print(worst, "is the worst at golf")
    print(best, "is the best at golf")

Output:

Dalton is the worst at golf
Nicholas is the best at golf