-2

I'm trying to add to an array based on a condition. Can someone clarify why the if statement isn't working as I intend it to?

all_staff = ["Judith", "Harry", "Jonathan", "Reuben"]
new_staff = []


def person_finder(staff):
for x in staff:
    if x == "Reuben" or "Harry" or "Jonathan":
        new_staff.append(x)
    else:
        continue
    return new_staff


selected = person_finder(all_staff)


def the_men(people):
for x in people:
    print(x + " is a man")


the_men(selected)

This returns:

Judith is a man

3 Answers3

2

replace

if x == "Reuben" or "Harry" or "Jonathan":

with

if x == "Reuben" or x == "Harry" or x == "Jonathan":
Ramesh-X
  • 4,853
  • 6
  • 46
  • 67
1

Change this line :

if x == "Reuben" or "Harry" or "Jonathan":

to

if x == "Reuben" or x=="Harry" or x=="Jonathan":

Working code:

all_staff = ["Judith", "Harry", "Jonathan", "Reuben"]

new_staff = []


def person_finder(staff):
    for x in staff:
        if x == "Reuben" or x=="Harry" or x=="Jonathan":
            new_staff.append(x)
        else:
            continue
    return new_staff


selected = person_finder(all_staff)


def the_men(people):
    for x in people:
        print(x + " is a man")


the_men(selected)

output:

Harry is a man
Jonathan is a man
Reuben is a man
Aaditya Ura
  • 12,007
  • 7
  • 50
  • 88
1
all_staff = ["Judith", "Harry", "Jonathan", "Reuben"]


def person_finder(staff):
    new_staff = []
    for x in staff:
        if x in ["Reuben", "Harry", "Jonathan"]:
            new_staff.append(x)
        else:
            continue
    return new_staff


selected = person_finder(all_staff)


def the_men(people):
    for x in people:
        print(x + " is a man")


the_men(selected)
Rao Sahab
  • 1,161
  • 1
  • 10
  • 12