简体   繁体   中英

How to make an if statement to check if all three items in list is present in another list

This is a bare sample of what I'm trying to build and I don't know why the combination of "wallet" and "ring" can pass as win.

I want the player to obtain all three items in order to win. Do you pose better solution to this?

import sys
inventory = []
def addtoInventory(item):
    inventory.append(item)

def room():
    print('you are in a living room, you say a card. Pick it up?')
    pickup = input()
    while pickup:
        if pickup == 'yes':
            addtoInventory("card")
            secondroom()
        else:
            print("you didnt pick it up")
            secondroom()
def secondroom():
    print('you are now in bedroom, theres a wallet, pick it up?')
    pickup = input()
    while pickup:
        if pickup == 'yes':
            addtoInventory("wallet")
            bathroom()
        else:
            print("you didnt pick it up")
            bathroom()
def bathroom():
    print('you are now in bathroom, theres a ring, pick it up?')
    pickup = input()
    while pickup:
        if pickup == 'yes':
            addtoInventory('ring')
            mall()
        else:
            print("you didnt pick it up")
            mall()
 
def mall():
    endgame = ["wallet", "card", "ring"]
    print('you are about to get a taxi to the pawn shop. do you have everything you need?')
    answer = input()
    print(inventory)
    while answer:
        if answer == 'yes':
            for item in endgame:
                if item not in inventory:
                    print("you lose")
                    sys.exit()
                else:
                    print("you won")
                    sys.exit()
            else:
                print("you lose")
                break

Your for loop: for item in endgame stops the program on the else condition after checking the first item in endgame. If you need all 3 items to be in the inventory, you should either wait for the end of the loop to declare a win, or check it all in one test (without a loop):

if all(item in inventory for item in endgame):
   print('you Win')
else:
   print('you Lose')
sys.exit()

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