cjm
cjm

Reputation: 844

Boolean check not working in function

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

Answers (4)

eumiro
eumiro

Reputation: 212835

  1. list is a bad name for a variable. It masks the built-in list.

  2. 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:

  3. 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

Levon
Levon

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

Matt Healy
Matt Healy

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

user647772
user647772

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

Related Questions