TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'

ⅰ亾dé卋堺 提交于 2021-02-05 06:49:06

问题


I am just experimenting and having fun with Python 2.7 and I'm trying to write a quadratic equation solver. I had it working when the radicand is positive, but when it's negative im getting an error. even after this if else statement. it also doesnt work with big numbers. thanks for the help.

import math
a = raw_input("a = ")
b = raw_input("b = ")
c = raw_input("c = ")
float(a)
float(b)
float(c)
radicand = ((b**2)-4*a*c)
if radicand >= 0:
    print(((0-b) + math.sqrt((b**2)-4*a*c))/(2*a))
    print(((0-b) - math.sqrt((b**2)-4*a*c))/(2*a))
else:
    print "Imaginary Radical"

when i replace (b**2)-4*a*c with radicand i get an invalid syntax error and print is highlighted in red. the error message says TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'
thanks again for any insight you can provide...


回答1:


You should replace:

float(a)

with:

a = float(a)

and similarly for the other variables.

The statement float(a) doesn't actually turn a into a float, it simply casts it, as per the following transcript:

>>> a = raw_input("a? ")
a? 4.5

>>> type(a)
<type 'str'>

>>> float(a)
4.5

>>> type(a)
<type 'str'>

>>> a = float(a)

>>> type(a)
<type 'float'>

You can see that the type of a is still str immediately after performing float(a) but, when you execute thew assignment a = float(a), the type becomes float.




回答2:


the statement float(a) returns the float value of the string a. But if you do not assign to any other variable, then float(a) holds only for that particular line. In the next line, a is a string. So, assign the float value to a variable, say a itself.

a=float(a)

This will make a a float



来源:https://stackoverflow.com/questions/17056264/typeerror-unsupported-operand-types-for-or-pow-str-and-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!