在Python中定义不等函数

2024-04-18 17:55:34 发布

您现在位置:Python中文网/ 问答频道 /正文

所以任务是想象python没有!=内建,并编写一个不等于的函数,该函数接受两个参数并给出与!=操作员。在

我给他写了以下代码:

def not_equal(x, y):
     if x == 0 or y == 0: #avoid error message for dividing by 0
         if ((y+1)/(x+1)) == 1:
             equal = False
     elif x/y == 1:
         equal = False
     else:
         equal = True
     return equal

并测试了以下测试用例:

^{pr2}$

前两个有效,但后两个错误消息如下:

Traceback (most recent call last):
  File "/Users/dvanderknaap/Desktop/My Python Programs/hw2.py", line 73, in <module>
    print not_equal(0, 3)
  File "/Users/dvanderknaap/Desktop/My Python Programs/hw2.py", line 67, in not_equal
    return equal
UnboundLocalError: local variable 'equal' referenced before assignment

为什么?在


Tags: 函数pyfalsereturnifmylinenot
3条回答

为什么做这么复杂的事?!毕竟假设是!=消失了,但我看不到{},所以它应该还在那里!-)在

def not_equal(a, b):
    return not (a==b)
if x == 0 or y == 0: #avoid error message for dividing by 0
         if ((y+1)/(x+1)) == 1:
             equal = False

print not_equal(0, 3)
print not_equal(4, 0)

这个,把它们放到你的if语句中

^{pr2}$

因此,除非x和y=0,否则您的if语句永远不会被处理。在

当您以x或y的形式提供0时,将触发以下代码:

if x == 0 or y == 0: #avoid error message for dividing by 0
     if ((y+1)/(x+1)) == 1:
         equal = False

现在,对于(0,4),Python检查(4+1)/(0+1)是否等于1,并且因为它不等于,所以它从不将equal设置为任何值。在

相关问题 更多 >