Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Hanan Al-Mashhadani
7,769 PointsPython Program
Can someone tell me how i supposed to fix this program please!! i was trying to develop a program that will read each player’s name and golf score as keyboard input, and then save these as records in a file named 'golf.dat', Read the records from the golf.dat file and display them, and Find the lowest score and displays the player’s name and the score.
I couldn't display both the lowest score and the player's name :(
# main module/function
def main():
namesScoresList = []
max = None
min = None
print("Hi, Welcome to Golf Score Program")
print("_________________________________")
print()
# Enter input, leave blank to quit program
while True:
name = input("Player's name(leave blank for quit):").title()
if name == "":
break
score = input("Player's score:")
if name != "" and score != "":
namesScoresList.append("{} {}".format(name, score))
try:
num = float(score)
except:
print("Invalid Input")
# Program that reads each player's name and golf score as input
# and Save them to golf.txt
with open('golf.txt', 'w') as outfile:
outfile.write("\n".join(namesScoresList))
# opens the "golf.txt" file created in the Golf Player Input python
# read lines one by one, splits them and print
with open('golf.txt', 'r') as infile:
for line in infile:
# strip newline from field
name, score = line.strip().split(" ")
# prints the names and scores
print(name, " scored ", score)
# Display the lowest score
if min is None or num < min:
min = num
print('The lowest score is ', int(min))
# calls main function
main()
3 Answers
Ken LaRose
Python Web Development Techdegree Student 21,982 PointsIs the problem that you cannot tell whom the lowest score belongs to? I don't know if this is the best solution, but I would try to store the names and scores in a list of dictionaries like this: [{'name': 'ken', 'score': 25}, {'name': 'joe', 'score': 30}]. This way you can call up the scores with list_name[0]['score'] and you can reference the golfer's name at list_name[0]['name'].
One other thing I noticed is that num returns the last score entered, not the lowest score. You'll want to put in some code to iterate through the list of scores and compare them against each other.
Hanan Al-Mashhadani
7,769 PointsHi Ken, Thanks for replying, i was trying to make the program iterate through the list and find the lowest score and displays the player’s name that have the lowest score and his score, witch is the lowest score. so i tried to do it in this way, but it shows different results each time i run it.
# main module/function
def main():
namesScoresList = []
print("Hi, Welcome to Golf Score Program")
print("_________________________________")
print()
#Enter input, leave blank to quit program
while True:
name = input("Player's name(leave blank for quit):").title()
if name == "":
break
score = input("Player's score:")
if name != "" and score != "":
namesScoresList.append("{} {}".format(name, score))
try:
num = float(score)
except:
print("Invalid Input")
#Program that reads each player's name and golf score as input
#and Save them to golf.txt
with open('golf.txt', 'w') as outfile:
outfile.write("\n".join(namesScoresList))
#opens the "golf.txt" file created in the Golf Player Input python
#read lines one by one, splits them and print
with open('golf.txt', 'r') as infile:
for line in infile:
# strip newline from field
name, score = line.strip().split(" ")
# prints the names and scores
print(name, " scored ", score)
#Display the lowest and heighst score
lowestScore = namesScoresList[0]
heighstScore = namesScoresList[0]
for i in namesScoresList:
if i < lowestScore:
lowestScore = i
# print('The Lowest Score is ', minimum)
if i > heighstScore:
heighstScore = i
# print('The Heighst Score is ', maximum)
print ('The Lowest Score is:' , lowestScore)
print ('The Heighst Score is:' , heighstScore)
# calls main function
main()
Ken LaRose
Python Web Development Techdegree Student 21,982 PointsI believe the issues is that namesScoresList contains strings; therefore, you're comparing the first letters of the players names, not their scores. We'll need to isolate the scores from the player names in order to compare them. There's probably cleaner ways to do this, but just off the cuff here's what I'd suggest - when you import the data from golf.txt, add a line to create a list of dictionaries:
ADD LIST OF DICTIONARIES:
#### ADD: ####
score_cards = []
with open('golf.txt', 'r') as infile:
for line in infile:
# strip newline from field
name, score = line.strip().split(" ")
#### ADD: ####
score_cards += [{'name': name, 'score': int(score)}]
# prints the names and scores
print(name, " scored ", score)
Now you can do something like this:
FIND HIGH / LOW SCORES:
high_score = 0
low_score = 999
for score_card in score_cards:
if score_card['score'] > high_score:
high_score = score_card['score']
worst_game = score_card
if score_card['score'] < low_score:
low_score = score_card['score']
best_game = score_card
# TODO: how do you want to handle a tie between 2+ players?
print('The Highest Score is:', worst_game['name'], worst_game['score'])
print('The Lowest Score is:', best_game['name'], best_game['score'])
one thing we're doing here is making sure we find the min & max scores, but also saving the best & worst game - this allows us to keep the players' names so they can be printed out at the end.
A couple more things to consider
- how do you want to handle a tie between 2 players - or even a 3 way tie (or more!)?
- please consider if it is necessary to write to golf.txt in the first place. Right now it is not necessary because the file is completely overwritten each time the program runs. If your goal is to save a history of all the scores, then you'd want to append to your outfile instead of writing over the previous content