【问题标题】:function return none instead of return number函数返回无而不是返回编号
【发布时间】:2017-03-10 04:51:38
【问题描述】:

我创建了一个与 x 和 y 变量进行比较的函数。函数内部有很多嵌套的 elif 来比较 x 和 y 然后返回整数。现在的问题是,当它运行在某个elif语句时,虽然语句是正确的,但它并没有执行该语句。

def convertTo(self, x, y):
    if( x == 0 & y == 0):
        return 0
    if( x == 0 & y == 1):
        return 1
    if( x == 0 & y == 2):
        return 2
    if( x == 0 & y == 3):
        return 3
    if( x == 1 & y == 0): 
        return 4 # Didn't return this line even though x = 1 and y = 0
    else
        return None

def main():
    self.convertTo(0,0)
    self.convertTo(0,1)
    self.convertTo(0,2)
    self.convertTo(0,3)
    self.convertTo(1,0) # return None? Why?

【问题讨论】:

  • 你试过and而不是&吗?
  • @tobias_k 运算符优先级不同。
  • 短路?可能是?只是一个问题......无论如何,我们怎么知道返回了什么?代码没有输出任何东西
  • 请注意,您的 if/else 结构很奇怪。应该是一系列if/elif/else。但是您也可以完全删除else: return None,因为无论如何这是默认设置。
  • 我认为操作的顺序是在比较之前执行按位运算符

标签: python if-statement


【解决方案1】:

您应该使用 and 而不是 &,因为 & 是按位与。

在 Python 中链接多个条件通常使用 if-elif-else 语句完成,如下所示:

if a and b:
   # a and b both was true
elif a and not b:
   # a was true, but b wasn't
else:
   # none of the conditions matched

在您的代码中,如果不是每个 if 中的 return 语句,并且您正在检查相同的两个变量,那么两个 if 语句可能会评估为 true。

if a:
   # this will run if a was true
if b:
   # regardless of a this will run if b was true
else:
   # regardless of a this will only run if b was false

另外,看看这个:https://docs.python.org/3/tutorial/controlflow.html

【讨论】:

    【解决方案2】:

    在 Python 中,“&”和“and”做两种不同的事情。 "and" 是你应该使用的,"&" 是二元运算符。

    如果 a = 0011 1100

    b = 0000 1101

    然后

    a&b = 0000 1100

    http://www.tutorialspoint.com/python/python_basic_operators.htm

    【讨论】:

    • 但这本身并不是全部的解释。
    • 但这并不能解释为什么在这种情况下它会失败,毕竟True & True 仍然是正确的。关键点确实是运算符优先级。
    【解决方案3】:

    您正在执行链式相等比较,但并没有按照您的想法进行。首先执行按位的&,因为它的优先级高于==

    替换:

    x == 1 & y == 0
    # 1 == 1 & 0 == 0
    # 1 == 0 == 0  False!
    

    与:

    x == 1 and y == 0
    

    见:Operator precedence

    【讨论】:

    • 这个,基本上解析为x == (1 & y) == 0
    • 又名成人 PEMDAS!
    猜你喜欢
    • 2018-03-08
    • 1970-01-01
    • 2013-09-17
    • 1970-01-01
    • 1970-01-01
    • 2019-05-26
    • 2015-03-03
    • 2016-05-28
    • 1970-01-01
    相关资源
    最近更新 更多