python3: how do i ask a user for input to select a specific list, and then print the items in that specific list in a random order? and then repeat the program to ask the user if which list they would like to select
#lists of healthy food
Fruits = ['apples', 'oranges', 'pears']
Vegies = ['carrots', 'tomatoes', 'broccoli']
#lists of meats
Red_meat = ['steak', 'hamburgers']
White_meat = ['chicken', 'turkey']
import random
the code i have below just looks repetitive and annoying. there must be an easier way to print this as a string of text
****i would like to have the user asked for input (which list would you like to select from?****
#Healthy foods #
#then print out something along the lines of
OUTPUT: oranges, tomatoes, pears, carrots
print(random.choice(Fruits), end= " ")
print(random.choice(Vegies), end= " ")
print(random.choice(Fruits), end= " ")
print(random.choice(Vegies), end= " ")
then ask the user if it would like to run the same list again, or select a different list
#would you like to run this same list(yes or no)
if yes: (runs again)
if no: (Which list would you like to run?)
lists of meats:
print(random.choice(Red_meat), end= " ")
print(random.choice(White_meat), end= " ")
print(random.choice(Red_meat), end= " ")
print(random.choice(White_meat), end= " ")
OUTPUT: steak, turkey, hamburgers, chicken
again?
OUTPUT: hamburgers, chicken, steak, chicken
This does very non-bulletproof user input. It's suitable for a demo program but not for the real world.
To have a single print
call you need to build up a list of the data you want the user to see. I've given you a sample but there are lots of ways to do it.
The loop in display_list
may look a bit daunting but it is like that to make it easy to add new categories to Healthy_food
and Meats
. Your code has the fact that there are only 2 categories of each hard-coded into it.
import random
Healthy_food = dict(
#lists of healthy food
Fruits = ['apples', 'oranges', 'pears'],
Vegies = ['carrots', 'tomatoes', 'broccoli'],
)
Meats = dict(
Red_meat = ['steak', 'hamburgers'],
White_meat = ['chicken', 'turkey'],
)
All_food = {
1: Meats,
0: Healthy_food,
}
def display_list(choice): # choice can be 0: Healthy_food or 1: Meats
selection = []
for i in range(2): # gives 2 random choices from each category
for options in All_food[choice].values():
selection.append(random.choice(options))
print (' '.join(selection))
def interact():
response = input('Do you want a list of Meats or Healthy food, or Quit? ').lower()
while 'q' not in response and response != '':
while True:
display_list('meat' in response)
if 'y' not in input('Again? ').lower():
break
response = input('Do you want a list of Meats or Healthy food, or Quit? ').lower()
if __name__ == "__main__":
interact()
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments