Slow Poke Slow Poke - 2 months ago 25
Python Question

My accumulator is registering as a string....SO LOST

My problem is probably simple as usual guys and gals, I've been working on this thing for 13 hours now and I can't get this this to accumulate the names variable.

I need it to count players that I have input data for. This is the error message I'm getting:

line 25, in main
name += 1
TypeError: Can't convert 'int' object to str implicitly


For this input/output:

You will be asked to enter players names and scores
When you have no more names, enter End

Enter Player's Name or end to end program:vxzcvzvc
Enter vxzcvzvc's golf score: 3
Enter Player's Name or end to end program:zcvxcxzvxzv5
Enter zcvxcxzvxzv5's golf score: 6
Enter Player's Name or end to end program:zcvxvczx
Enter zcvxvczx's golf score: 5
Enter Player's Name or end to end program:end
You have written end players records to golf.txt


This is my code:

def main():
#Program that reads each player's name and golf score as input
#Save to golf.txt
outfile = open('golf.txt', 'w')

#define name
name = 0
name += 1

# introduction to user explaining required information to be entered
print("You will be asked to enter players names and scores")
print("When you have no more names, enter End")
print("\n")

#Enter input, leave blank to quit program
while True:
name = input("Enter Player's Name or end to end program:")
if name == "end":
break
score = input("Enter "+ str(name)+"'s golf score: ")

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

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

#output for number of names recorded
print("You have written", name,"players records to golf.txt")
outfile.close()
main()

Answer

You need a separate variable for counting the number of scores that have been written:

def main():
    outfile = open('golf.txt', 'w')

    # Change this: 
    count = 0

    print("You will be asked to enter players names and scores")
    print("When you have no more names, enter End")
    print("\n")

    while True:
        name = input("Enter Player's Name or end to end program:")
        if name == "end":
            break
        score = input("Enter {}'s golf score: ".format(name))
        outfile.write(name + "\n")
        outfile.write(str(score) + "\n")
        # add this:
        count += 1

    # change this:
    print("You have written {} players records to golf.txt".format(count))
    outfile.close()

main()