Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: unsupported operand type(s) for /: 'str' and 'int'

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.

like image 454
foltor Avatar asked Jan 15 '23 11:01

foltor


1 Answers

% 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.

Docs: operator precedence

like image 164
Pavel Anossov Avatar answered Jan 23 '23 17:01

Pavel Anossov