我是python的新手,我正在尝试写一个求解二次方程的程序。
问题是我不能把一个整数加到一个非类型的变量上,因为我已经决定把一个非类型的变量变成一个整数,但是我不能,我试了很多次都没有成功。
代码如下:
# MY FIRST PROJECT
import math
a = 1
b = -4
c = 1
D = b**2-4*a*c
print(D)
Z=print("the square root of D is: %f" % math.sqrt(D))
print(type(Z))
if D < 0:
print("the problem can't be solved in R because D is negative")
if D == 0 :
x = print(-b/2*a)
if D > 0:
print("the problem has two solutions")
y = print((-b+Z)/2*a)
k = print((-b-Z)/2*a)我一直得到的错误是:
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'发布于 2019-12-17 01:14:20
您的问题是由以下原因引起的:
Z=print("the square root of D is: %f" % math.sqrt(D))总是返回None的print is a function (就像所有没有要返回有意义的值的函数一样;省略或绕过用户定义函数的return也隐式返回None ),所以Z总是None。如果目标是将D的平方根赋给Z,则将其替换为:
Z = math.sqrt(D)
print("the square root of D is: %f" % Z)但是,应该将该代码移到块处理if D < 0:之后,因为如果提供了负输入,math.sqrt将引发ValueError。
https://stackoverflow.com/questions/59361241
复制相似问题