0

I 'm getting the error "TypeError: Can't convert 'int' object to str implicitly" when using a for loop to create class instances.I'm fairly new to programming and haven't seen this error before

class Player(object):  
    properties = []
    def __init__( self, name, wealth, player_number):
        self.name = name
        self.wealth = wealth
        self.player_number = player_number
    def __repr__(self):
        return str(self.wealth)

players = {}

for x in range(0, Player_count):
    players["player_" + x] = Player(input("Name"), input("Starting Wealth"), x)

I'm getting the error when it reaches x

  • 1
    worth noting here that you don't need a dictionary, since a list will do the job of keeping a track of all the players (especially since you are only tracking them by a number, and lists already have an index) and as side effect it will also get rid of your error. – Burhan Khalid Aug 30 '13 at 21:39

2 Answers2

1

Turn the integer to a string explicitly then:

 players["player_" + str(x)] = Player(input("Name"), input("Starting Wealth"), x)

or use string formatting:

 players["player_{}".format(x)] = Player(input("Name"), input("Starting Wealth"), x)

You cannot just concatenate a string (player_) and an integer (the number between 0 and Player_count) referenced by x.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

You cannot add strings and numbers

Incorrect:

["player_" + x]

Correct:

['player_%d' % x']

Or the new format method:

['player_{0}'.format(x)]
Viktor Kerkez
  • 45,070
  • 12
  • 104
  • 85
  • Note that this is old-style string formatting, which is recommended against in new code, instead, use `str.format()`. E.g: `'player_{}'.format(x)`. – Gareth Latty Aug 30 '13 at 21:37
  • 1
    @ViktorKerkez: in a later revision, yes. :-) – Martijn Pieters Aug 30 '13 at 21:39
  • Give me a second :D before commenting ;) – Viktor Kerkez Aug 30 '13 at 21:40
  • I'm not sure I'd call the `format` method "new", given that it's been in the language since 2.6, 5-odd years ago. But I suppose the New Testament is still new after 2-odd millennia. :) – abarnert Aug 30 '13 at 21:47
  • @abarnert When you're still maintain software that runs on 2.4 and 2.5 as your day job, it falls into the "new" category ;) – Viktor Kerkez Aug 30 '13 at 21:51
  • @ViktorKerkez: I feel for you. At a previous job maybe 5 years ago, I had to figure out where to find Python 1.5 and how to build it on Fedora because my manager insisted that it would be less risk than doing the trivial one-liner change to get our build scripts running in Python 2.5… – abarnert Aug 30 '13 at 22:19