First go at python and I want to create a score sheet for a game with 4 players my first step is to get the name of each player put the names in a list then at the end print out the four names.
When run I get this error.
TypeError: ‘builtin_function_or_method’ object is not subscriptable
Here is the code i have.
num = 0
players = []
while num < 4:
PlayerName = input ("Enter a name ")
num = num + 1
players.append(PlayerName)
print [players]
There is the error. You are using a list as a subscript of an anonymous list.
print (players)
The above passes the list to the print() function.
Aside
I’m going to assume this is not a lesson related question so will move it to the Corner Bar.
Since a player will have a corresponding score property, it might be simpler to create a players dictionary:
players = {}
while len(players.keys()) < 4:
player_name = input("Enter player name: ")
players[player_name] = 0
for player in players:
print ({}: {}).format (player, players[player]))
Or you might want to use a list of dictionaries:
players = []
while len(players) < 4:
player_name = input("Enter player name: ")
players.append({'name': player_name, 'score': 0})
for player in players:
print ('Name : {}\nScore: {}'.format (player['name'], player['score']))
Thank you for the clear and detailed reply.
I did get it to work by removing the indent from the print function.
Will now go and play around with the two examples you have given to me.
Thanks again for the correction (i did keep getting syntax error)
If I could ask 2 more questions please in the dictionary code.
how can I get the name to clear after it has been entered and make it ready for the next inputted name.
How would I get the score to appear under each name instead of along side it, is there a carrage return code? Sorry got that all wrong the score does appear under each name it’s how to get the names in a line instead of on top of each other.
>>> players = []
>>> while len(players) < 4:
player_name = input("Enter player name: ")
players.append({'name': player_name, 'score': 0})
Enter player name: Joe
Enter player name: Jim
Enter player name: Bill
Enter player name: Bob
>>> for player in players:
print ('Name : {}\nScore: {}'.format (player['name'], player['score']))
Name : Joe
Score: 0
Name : Jim
Score: 0
Name : Bill
Score: 0
Name : Bob
Score: 0
>>>
>>> for player in players:
print ('Name : {} Score: {}'.format (player['name'], player['score']))
Name : Joe Score: 0
Name : Jim Score: 0
Name : Bill Score: 0
Name : Bob Score: 0
>>>
>>> for player in players:
print ('Name : {}\tScore: {}'.format (player['name'], player['score']))
Name : Joe Score: 0
Name : Jim Score: 0
Name : Bill Score: 0
Name : Bob Score: 0
>>>
Thanks for the help, will go away and study these so that I understand what is doing what, then I’ll move on to the next step (incrementing the scores after each player has had their turn)