Python Forum
Conditional not processing as intended (Colt Steele’s Udemy course)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Conditional not processing as intended (Colt Steele’s Udemy course)
#1
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.
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
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.")
Reply
#4
Thanks you both. This helps. My script now runs as intended.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question Common understanding of output processing with conditional statement neail 6 823 Sep-17-2023, 03:58 PM
Last Post: neail
  testing if a character in a string is an intended one Skaperen 2 2,622 Feb-27-2018, 02:51 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020