简体   繁体   中英

How to call function with if statement that loops through a list? Python

brand new to programming here, and having a lot of trouble with a homework problem. Please excuse my lack of understanding and knowledge. Any help would be greatly appreciated! Thank you!! I'm trying to output an if statement, when one of the items I'm calling is not in the list, and the function should print out that item.

def sushi(order):
    toppings = ['salmon', 'tuna', 'whitefish']
    for item in toppings:
        if 'salmon' or 'tuna' or 'whitefish' in toppings:
            print('all set')
            break
        if not item in toppings:
            print('Add to this', toppings.append(order))
            print('all set')

sushi(['salmon', 'tuna'])
sushi(['salmon', 'tuna', 'tempura'])

I want it to output:

all set
Add to this tempura
all set

I believe what you are looking for is:

def sushi(order):
    toppings = ['salmon', 'tuna', 'whitefish']
    for item in order:
        if item not in toppings:
            print('Add to this', item)
    print("All set!")

>>> sushi(['salmon', 'tuna'])
All set!
>>> sushi(['salmon', 'tuna', 'tempura'])
Add to this tempura
All set!

The loop could be shortened by changing it to:

for item in [x for x in order if x not in toppings]:
    print('Add to this', item)

Your problems were:

1) for item in toppings:

I guess you wanted here order instead of toppings

2) if 'salmon' or 'tuna' or 'whitefish' in toppings:

here you probably wanted it to be: if 'salmon' in toppings or 'tuna' in toppings or 'whitefish' in toppings: . What you wrote is "if the string 'salmon' exists or the string 'tuna' exists or the string 'whitefish' is in toppings".

3) print('Add to this', toppings.append(order))

the method append does not return anything. maybe what you wanted is to add one line saying toppings.append(item) and then simply print item

I think this does what you want

def sushi(order):
    toppings = ['salmon', 'tuna', 'whitefish']
    for item in order:
        if item in toppings:
            pass
        else:
            print('Add to this', item)
            toppings.append(item)
    print('all set')
>>> sushi(['salmon', 'tuna'])
all set

>>> sushi(['salmon', 'tuna', 'tempura'])
Add to this tempura
all set


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM