此代码将成为检查数字是否为质数的程序的一部分。我知道它不是特别优雅,但我想让它只是为了体验而工作。我认为函数失败是因为 if/elif 上的逻辑错误,当我运行这段代码时,它似乎直接进入了 else 子句。这是语法问题,还是我不允许在 if 子句中进行逻辑检查?
list = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
def find_prime(list, n):
if n in list == False:
list.append(n)
print "I'ts in there now."
elif n in list == True:
print "It's in there already."
else:
print "Error"
find_prime(list, 3)
find_prime(list, 51)
请您参考如下方法:
list是一个错误的变量名。它屏蔽了内置的list。if n in list == True:没有执行您等待的操作:1 in [0, 1] == True返回False(因为,正如@Duncan 指出的那样,1 in [0,1] == True是1 in [0,1] and [0,1] = = 真)。使用if n in li:和if n not in li:没有理由出现
错误,因为元素在列表中或不在列表中。其他都是编程错误。
因此您的代码可能如下所示:
li = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
def find_prime(li, n):
if n in li:
print "It's in there already."
else:
li.append(n)
print "It's in there now."
