【问题标题】:return None in the end of the program in python [closed]在python中的程序末尾返回None [关闭]
【发布时间】:2022-01-24 10:02:03
【问题描述】:

在问题中,他们要求我从用户那里获取数字,然后求解一个二次方程。 我做到了,并在 Python Tutor 上查看,每次都返回 None,这是为什么呢?

def quadratic_equation(a,b,c):
import math
if a == 0:
    print("The parameter 'a' may not equal 0")
elif (b**2) - (4 * a * c) < 0:
    print("The equation has no solutions")
else:
### x1 mean with +
    x1 = ((-b) + (math.sqrt((b**2) - (4 * a * c)))) / (2 * a)
### x2 mean with - 
    x2 = ((-b) - (math.sqrt((b**2) - (4 * a * c)))) / (2 * a)
    if x1 and x2 is not None:
        return (f"The equation has 2 solutions: {x1} and {x2}")
    elif x1 is None:
        return (f"The equation has 1 solution: {x2} ")
    elif x2 is None:
        return (f"The equation has 1 solution: {x1} ")

def quadratic_equation_user_input():
numbers = (input("Insert coefficients a, b, and c: "))
num = []
for i in numbers.split():
    try:
        num.append(float(i))
    except ValueError:
        pass
a = num[0]
b = num[1]
c = num[2]
quadratic_equation(a,b,c)


print(quadratic_equation_user_input())

【问题讨论】:

  • 既然你用的是Python,想必你明白缩进会影响意思,缩进不好的Python没有意义,无法运行。不要让我们尝试猜测您正确缩进的代码是什么样的,请edit您的问题并解决它。
  • 方法的最后一行不是返回值。您需要明确地return quadratic_equation(a, b, c)。如果没有显式返回,您所经历的 Python 将 return None
  • 我试着在这里缩进,但我不知道怎么做,制表符在这里工作,我的文档我做得很好
  • 使用空格而不是制表符。

标签: python python-3.x return


【解决方案1】:

quadratic_equation_user_input 调用quadratic_equation 并忽略其返回值,因此返回默认返回值None

# Call function but ignore return value
quadratic_equation(a,b,c)

# No return in caller function -> default to None
# ....

你可能是说

return quadratic_equation(a,b,c)

quadratic_equation_user_input的末尾。

【讨论】:

    猜你喜欢
    • 2023-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-07
    • 2018-08-14
    • 2018-03-29
    • 1970-01-01
    相关资源
    最近更新 更多