0

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()
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
  • `isnumeric()` https://www.geeksforgeeks.org/python-string-isnumeric-method/ – Pedro Lobito Nov 04 '22 at 00:00
  • 2
    it would make more sense to write the name and score on the same line separated with a comma: `golf.write(f"{player_name},{player_score}")` . This will make the process of importing the data easier. – ScottC Nov 04 '22 at 00:28
  • 1
    The file consists of alternating string/int pairs. You, however, read one line before the loop, which means the rest of the file is alternating int/string pairs. But in the loop, you assume there are still alternating string/int pairs. – chepner Nov 04 '22 at 01:21

3 Answers3

2

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
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
0
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.')
Kilian
  • 21
  • 2
0

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
Arifa Chan
  • 947
  • 2
  • 6
  • 23