Python Forum

Full Version: Conditional not processing as intended (Colt Steele’s Udemy course)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I’m trying to choose one element at random from a list with 6 food items and then categorizes the randomly selected item as either fruit, vegetable or protein. So I’ve imported the choice method from the random module and I’m using conditionals, booleans and disjunctions.

I came up with two different ways of completing this task:

from random import choice
food = choice(['apple','grape', 'celery', 'carrot', 'worm', 'cockroach'])
print(food)
if "apple" or "grape" in food:
    print("It's a fruit.")
elif 'celery' or 'carrot' in food:
    print("It's a vegetable.")
elif 'worm' or 'cockroach' in food:
    print("It's protein.")
And:

from random import choice
food = choice(['apple','grape', 'celery', 'carrot', 'worm', 'cockroach'])
print(food)
if food == "apple" or "grape":
    print("It's a fruit.")
elif food ==  'celery' or 'carrot':
    print("It's a vegetable.")
elif food == 'worm' or 'cockroach':
    print("It's protein.")
Here is some sample output:

Quote:carrot
It's a fruit.

I can see the list items chosen at random are different every time. So that produces the expected output. My problem, as you can see in the output above, the food item is "carrot" but it still shows "fruit" when I am expecting it to say: "vegetable". What's happening is that even if the first condition is not met, why does the script not proceed to the second or third conditional?

This is an exercise in Colt Steele’s Udemy course which I am doing for fun, not for credit with school.
You need to have an expression on each side of the or (see here for details). In this case, I would go with if food in ('apple', 'grape'): rather than using or.
if food == "apple" or "grape":
is always evaluated as True even if food is neither equal to "apple" nor equal to "grape"
as if "grape": returns as True.

You need to write such if-conditions as
if food == "apple" or food == "grape":
    print("It's a fruit.")
But the more pythonic way is to use what ichabod801 wrote:
if food in ["apple", "grape"]:
    print("It's a fruit.")
Thanks you both. This helps. My script now runs as intended.