Reputation: 61
In Python 2.7:
a=80
b=100
def status(hp, maxhp):
print "You are at %r percent health." % hp*100/maxhp
status(a,b)
Returns:
TypeError: unsupported operand type(s) for /: 'str' and 'int'
I've already tried putting int() around each variable and each combination of variables.
Upvotes: 4
Views: 5451
Reputation: 62868
%
operator has higher precedence than *
or /
.
What you meant is:
"You are at %r percent health." % (hp * 100 / maxhp)
What you got is:
("You are at %r percent health." % hp) * 100 / maxhp
Edit: actually, I'm wrong. They have the same precedence and thus are applied left to right.
Upvotes: 8
Reputation: 14565
you need to wrap parens around the expression, so it is fully evaluated before trying to have the result substituted into the string.
something like:
print "my string with this '%d' value" % (hp * 100 / maxhp)
Upvotes: 1