A question I have...

Chris Rebert clp2 at rebertia.com
Sat Oct 23 18:53:15 EDT 2010


On Thu, Oct 21, 2010 at 7:25 PM, Joe Shoulak <joepshoulak at yahoo.com> wrote:
> I'm trying to make a sports simulation program and so far everything has
> worked until I try entering:
>
> Score1 = (Team1Off + Team2Def)/2
>
> I get the error:
>
> TypeError: unsupported operand type(s) for /: 'str' and 'int'
>
> Can someone please explain to me what this means, why it doesn't work and
> what I can do to make it work?

Team1Off and Team2Def are strings (i.e. text); Python's string type is
called "str".

Adding two strings concatenates them; e.g. "abc" + "def" == "abcdef".

"int" is the name of Python's integer type. 2 is the integer in question.

You're trying to divide a string (the concatenation of Team1Off and
Team2Def) by an integer (2), which is nonsensical (What would it mean
to divide "The quick brown fox" by the number 2?); hence, Python
raises an error (TypeError) to inform you of this.

You need to convert Team1Off and Team2Def to numbers instead of
strings so you can do calculations involving them. This can be done by
writing:

Team1Off = int(Team1Off)

assuming Team1Off is a string representing a decimal integer; e.g.
"12345". If it instead represents a floating-point number (i.e. has a
decimal point; e.g. "1.23"), substitute "float" for "int". You will of
course need to also convert Team2Def using the same technique. Note
that ValueError will be raised if the string doesn't represent a
number.

You may also want to add the following to the start of your code so
that the results of divisions are what you expect:
from __future__ import division

If you haven't already, you should read the Python tutorial:
http://docs.python.org/tutorial/

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list