【问题标题】:How to return a boolean?如何返回布尔值?
【发布时间】:2019-11-30 23:57:37
【问题描述】:

我正在尝试测试一个功能。它必须以 3 个数字 a、b 和 c 作为其参数,并返回一个布尔值,指示 a² = b²+c² 是否。

a = int(input("a:"))
b = int(input("b:"))
c = int(input("c:"))

def test_pythagore():
    a**2 == b**2 + c**2

    return test_pythagore `    

我希望程序在不使用 print 的情况下将 true 或 false 作为布尔值返回。

【问题讨论】:

  • 返回什么?

标签: python return


【解决方案1】:

您必须返回比较的实际结果并为您的函数提供正确的输入。

def test_pythagore(a, b, c):
    return a**2 == b**2 + c**2

【讨论】:

    【解决方案2】:

    您需要将参数传递给函数,以便她知道她在操作什么:

    def test_pythagore(a, b, c):
    

    这定义了一个有 3 个参数的函数。

    现在您检查我们的条件是否为真,并将结果存储到一个变量中,以便稍后返回。

    def test_pythagore(a, b, c):
       result = c**2 == a**2 + b**2
       return result
    

    注意:你可以自己返回语句,但看到你有问题,让我们坚持返回变量

    所以整个代码如下所示:

    def test_pythagore(a, b, c):
       result = c**2 == a**2 + b**2
       return result
    
    # you chose to round to ints, why not
    a = int(input("a:")) 
    b = int(input("b:")) 
    c = int(input("c:"))
    
    variable = test_pythagore(a, b, c)
    print(variable)  # prints True or False
    
    

    看到您的代码,您可能应该尝试一些教程,谢天谢地官方 python 文档提供了这样的东西! https://docs.python.org/3/tutorial/index.html

    【讨论】:

      【解决方案3】:
          a = int(input("a:"))
          b = int(input("b:"))
          c = int(input("c:"))
      
          def test_pythagore(a,b,c):
              return a**2 == b**2 + c**2
      
          test_pythagore(a,b,c)
      

      【讨论】:

        【解决方案4】:

        有几件事需要改变。您的函数必须将参数作为参数提供。您可以在此处阅读函数的工作原理:https://www.w3schools.com/python/python_functions.asp

        下面的代码将运行该函数并将布尔值存储在一个名为 result 的变量中:

        a = int(input("a:"))
        b = int(input("b:"))
        c = int(input("c:"))
        
        def test_pythagore(a,b,c):
            return a**2 == b**2 + c**2
        
        result = test_pythagore(a,b,c)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-04-07
          • 2013-08-18
          • 2013-05-21
          • 2011-12-14
          • 2020-07-29
          • 2014-12-13
          • 1970-01-01
          相关资源
          最近更新 更多