简体   繁体   中英

Setting a conditional for a random item selected from a list in Python

I'm working on a text-based Choose Your Own Adventure game in Python for an online class. The game has a list of random "villains" that you may encounter. The original project just has you going to the cave and finding a magical sword that you use to fight the villain. I wanted to set it so that the "weapon" would change according to whatever villian is selected randomly for the list. I listed the code I came up with (below), but it is not recognizing the choice of creature. Instead, it is returning the sword each time. What am I doing wrong?

creatures = ["wicked fairy", "gorgon", "troll", "dragon", "small child", "Karen", "ex-wife"]
weapons = ["Sword of Ogoroth", "Nintendo Switch", "social media", "alimony"]
creature = random.choice(creatures)
items = []


    if {creature} == "wicked fairy" or "gorgon" or "troll" or "dragon":
        # print messages here
        items.append("sword")
    elif {creature} == "small child":
        # print messages here
        items.append("Switch")
    elif {creature} == "Karen":
        # print messages here
        items.append("phone")
    else: 
        # print messages here
        items.append("money")
    

# edited to pare down the code so that only the relevant sections were listed


I tried using random choice and conditional statements.

The core of the problem is that if you write:

if {creature} == "wicked fairy" or "gorgon" or "troll" or "dragon":

you have created a logical or of four items with only the first one being an actual comparison.

As a non-empty string evaluates in Python to True the 'condition' will always return True on "gorgon" as it is a non-empty string.

What you actually wanted to achieve was:

if creature in ["wicked fairy", "gorgon", "troll", "dragon"]:

And please don't forget to remove the curly braces in all the elif statements too as they are creating a Python set with one item in it what is not what you intend the code to do.

if creature == "wicked fairy" or creature == "gorgon" or creature == "troll" or creature == "dragon":

This works!

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