【问题标题】:Python: Printing the return of a functionPython:打印函数的返回
【发布时间】:2015-12-25 17:40:04
【问题描述】:

Python 2.7。下面的函数返回 True 或 False。我正在尝试打印此结果。现在我知道我可以将“return”替换为“print”,但我不想从函数内部进行打印。

def OR_Gate():                                              
  a = raw_input("Input A:")                                        
  b = raw_input("Input B:")                                        
  if a == True or b == True:                                      
      return True                                                  
  if a == False and b == False:                                    
      return False

print OR_Gate()

当我运行以下代码时,系统会提示我输入 a 和 b 的值,然后输出为“None”,而不是 True 或 False。如何打印函数 OR_Gate 的返回值?

【问题讨论】:

  • 比较 ab 与字符串,例如if a == 'True' or b == 'True':
  • a 或 b 永远不会是 True 或 False,它们是字符串
  • 问题是因为如果块的计算结果都不是True,函数到达末尾并返回None

标签: python python-2.7


【解决方案1】:

您将 booleansstrings True != "True"False != "False" 进行比较,因此您的函数返回 None,这是您未指定返回值时的默认值.您还可以使用in 使用"True" 来简化您的代码:

def OR_Gate():                                              
  a = raw_input("Input A:")                                        
  b = raw_input("Input B:")                                        
  return "True" in [a,b]

【讨论】:

    【解决方案2】:

    Padraic 有一个很好的答案。除此之外,如果您想将原始输入与一组字符进行比较以确定真实性,您可以执行以下操作:

    def OR_Gate():
        truevalues = ['true','t','yes','y','1']
        falsevalues = ['false','f','no','n','0']
        a = raw_input("Input A:")
        b = raw_input("Input B:")
    
        # if you want to have a one line return, you could do this
        # send back False if a and b are both false; otherwise send True
        # return False if a.lower() in falsevalues and b.lower() in falsevalues else True
    
        if a.lower() in truevalues or b.lower() in truevalues:
            return True
        if a.lower() in falsevalues or b.lower() in falsevalues:
            return False
    
    print OR_Gate()
    

    一些结果:

    $ python test.py
    Input A:t
    Input B:t
    True
    
    $ python test.py
    Input A:f
    Input B:t
    True
    
    $ python test.py
    Input A:f
    Input B:f
    False
    

    【讨论】:

    • 一些小的改进:不再检查Truetrue,而是将输入小写,例如a.lower() in truevalues。这样'tRue' 也被接受,我们必须减少比较。而不是做if something: return True // if (not something): return False,而是做return something
    【解决方案3】:

    我喜欢发布有趣的答案。来了一个:

    def OR_Gate():                                              
      return eval(raw_input("Input A:")) or eval(raw_input("Input B:"))
    

    但是,通过用户输入使用 eval() 可以直接访问 python interpeter。因此,如果此代码是网站项目等的一部分,则不应使用它。除此之外,我认为它很酷。

    【讨论】:

    • 正确的条件是a or b
    • eval(raw_input(...)) == input(...)
    • 这是正确的,但我想展示在使用 OP 之类的 raw_input 之后真正发生了什么。除此之外,你是绝对正确的。
    猜你喜欢
    • 2019-10-14
    • 1970-01-01
    • 2019-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多