Turn string from a file into integer to use in new code

Viewed 56

I wrote a dual program for a golf tournament. First takes in the name of the golfer and their score. Second calls that data and prints it. My problem is that when I call the score I want to convert it to an integer because I need to print whether that score was under par, par, or over par, instead of actually printing the score. So how do I convert it to an integer once its called? And then, where do I put my if_else statement to convert that integer into under par, par, over par?

here is what I have so far

#FIRST PROGRAM CODE

outfile = open('golf.txt', 'w')

#Enter input, leave blank to quit program

while True:
    name = input("Player's first and last name(leave blank to quit):")
    if name == "":
        break
    score = input("Player's score:")

#write to file golf.txt
    outfile.write(name + "\n")

    outfile.write(str(score) + "\n")

outfile.close()
#SECOND PROGRAM CODE

# main module/function

def main():

# opens the "golf.txt" file
# in read-only mode

    infile = open('golf.txt', 'r')

# reads the player  from the file

    name = infile.readline()

    while name != '':

# reads the score  

        score = infile.readline()

# strip newline from field

        name = name.rstrip('\n')
        score = score.rstrip('\n')

# prints the names and scores

        print(name + " scored " + score)

# read the name field of next record

        name = infile.readline()

# closes the file    

    infile.close()

# calls main function

main()
2 Answers

You can do a int(score) to convert it to int and the you can just make a new function which accepts the score and returns the string to print.

For example:

def get_result(score):
  if(int(score) == par):
    return "par"
  elif(int(score) < par):
    return "under par"
  else:
    return "over par"

I have no idea how golf stuff works but just add whatever you need. And then you can just print(name + " scored " + get_result(score)).

Assuming you also have a variable for the golf course par this is what I would quickly do after reading the file lines for name and score:

gc_par = 72  # declare this before the "while" loop

# After printing the name and score:

score_num = int(score)  # This transforms the score string to an integer number

if score_num > gc_par:
   print("Over par")
elif score_num < gc_par:
   print("Under par")
else:
   print("Par")

# Then you continue to read the next name from file
Related