Nov-07-2019, 04:10 PM
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:
And:
Here is some sample output:
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.
I came up with two different ways of completing this task:
1 2 3 4 5 6 7 8 9 |
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." ) |
1 2 3 4 5 6 7 8 9 |
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." ) |
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.