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


Messages In This Thread
Conditional not processing as intended (Colt Steele’s Udemy course) - by Drone4four - Nov-07-2019, 04:10 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
Question Common understanding of output processing with conditional statement neail 6 921 Sep-17-2023, 03:58 PM
Last Post: neail
  testing if a character in a string is an intended one Skaperen 2 2,698 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