[Tutor] role playing game - help needed
Peter Otten
__peter__ at web.de
Wed Dec 8 00:29:40 CET 2010
Al Stern wrote:
> I used the following code and got the following error.
The result of input is always a string.
> attributes["strength"] = input("\nHow many points do you want to assign to
> strength?: ")
Say you type 42 when you run your script. Then the above assignment is
effectively
attributes["strength"] = "42"
and when you loop over the values you try to add a string to an integer
which is what Python complains about:
>>> 42 + "42"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
To get an integer you have to convert the string explicitly:
>>> 42 + int("42")
84
The best place to do that is as early as possible, even before you put the
value into the dictionary:
attributes["strength"] = int(input(...))
(In a real application you'd guard against values that cannot be converted
to integers)
> #point allocation
> point_total = 0
> for val in values:
> point_total += val
> print (point_total)
>
> and get this error...
>
> Traceback (most recent call last):
> File "C:\Users\Public\Documents\My Python programs\role_playing_game1.py",
> line 26, in <module>
> point_total += val
> TypeError: unsupported operand type(s) for +=: 'int' and 'str'
More information about the Tutor
mailing list