布尔检查在功能中不起作用 [英] Boolean check not working in function
问题描述
此代码将成为程序的一部分,该程序将检查数字是否为质数.我知道它不是特别优雅,但我想让它仅出于体验而工作.我认为该函数失败了,因为if/elif上的逻辑是错误的,当我运行此代码时,它似乎直接进入了else子句.这是语法问题,还是不允许我在if子句中进行逻辑检查?
This code will be part of a program that will check if a number is prime or not. I know it's not particularly elegant, but I want to get it working simply for experience. I think that the function is failing because the logic on the if/elif is wrong, when I run this code, it seems to just go straight to the else clause. Is this a syntax problem, or am I not allowed to do logic checks in if clauses?
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
.
list
is a bad name for a variable. It masks the built-inlist
.
if n in list == True:
不会执行您要等待的操作:1 in [0, 1] == True
返回False
(因为,正如@Duncan指出的那样,1 in [0,1] == True
是1 in [0,1] and [0,1] == True
的简写).使用if n in li:
和if n not in li:
if n in list == True:
doesn't do what you await: 1 in [0, 1] == True
returns False
(because, as @Duncan notes, 1 in [0,1] == True
is shorthand for 1 in [0,1] and [0,1] == True
). Use if n in li:
and if n not in li:
没有必要使用Error
,因为元素在列表中或不在列表中.还有什么是编程错误.
No reason for an Error
, since an element is in the list or it is not in the list. Anything else is programming error.
因此您的代码应如下所示:
So your code could look like this:
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."
这篇关于布尔检查在功能中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!