Reputation: 844
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)
Upvotes: 1
Views: 2747
Reputation: 212835
list
is a bad name for a variable. It masks the built-in list
.
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:
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."
Upvotes: 5
Reputation: 143047
Try this code instead of testing for True/False. Also see my comment above regarding using list
as a variable name (bad idea since that identifier is used by Python).
mylist = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
def find_prime(mylist, n):
if not n in mylist:
mylist.append(n)
print "I'ts in there now."
else: # n in mylist: has to be the case
print "It's in there already."
You don't need the original last else
, your choice is binary, either the number will be in the list or it won't.
Upvotes: 2
Reputation: 18531
Since the value is either going to be in the list or not, I don't think you need to check three options in your if/else logic.
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:
print "It's in there already."
else:
list.append(n)
print "It's in there now."
find_prime(list,3)
find_prime(list,53)
Upvotes: 2
Reputation:
Don't call your list list
. Call it mylist
or something else.
Use if not n in mylist
and if n in mylist
.
Upvotes: 2