Trying to get the random.choice ouput to work with if statement. This is the code:

Viewed 16
import numpy as np
import random
import time

animal = ["bird", "mammal", "fish", "insect", "reptile"]
#select weighted sample from list and put it into variable
rand_animal = (random.choices(animal, weights=(50, 20, 10, 10, 10), k=1))
print(rand_animal)
time.sleep(1)

#prints output based on the weighted selection
if rand_animal == "bird":
   print("CHIRP CHRIP")
else:
   print("Not a bird")

The problem when I run it, is that the else statement always prints Not a bird. Is there a way to call the random.choices k sample into another variable? Is that output not fixed?

1 Answers

In your code, You are trying to compare list and string.

By adding [0] position you will compare the first value of rand_animal with string.

Code:

#prints output based on the weighted selection
if rand_animal[0] == "bird":
    print("CHIRP CHRIP")
else:
    print("Not a bird")

Output:

['bird']
CHIRP CHRIP
Related