简体   繁体   中英

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

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

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM