food = ["pizza", "tacos", "lasagna", "watermelon", "cookies"]
plate = ""
for dish in food:
print(dish)
fav_dish = input("Is this your favorite dish? Y/N: ")
if fav_dish == "Y" and food[-1]:
plate = dish
elif fav_dish == "Y":
plate = dish ", "
print("I want " plate "!")
I am practicing my coding skills and I want the results to look like this.
I want pizza, tacos, and cake!
The results look like this:
pizza
Is this your favorite dish? Y/N: Y
tacos
Is this your favorite dish? Y/N: Y
lasagna
Is this your favorite dish? Y/N: N
watermelon
Is this your favorite dish? Y/N: N
cookies
Is this your favorite dish? Y/N: Y
I want pizzatacoscookies!
CodePudding user response:
You can create the variable plate as a list where you put the favorite dishes and then use the "".join() function.
You put in the commas the separator you want, and in the parenthesis the list to join. In your case:
print("I want " ", ".join(plate) "!")
CodePudding user response:
first make a list of selection, then operate on that list. This code ignores the case of an empty selection list and can be left as an exercise.
selected = []
for dish in food:
select = input(f'Is [{dish}] your favorite dish? Y/N: ')
if select == 'Y':
selected.append(dish)
# since the second option ignores the dish, you can dis include it from the list
if len(selected) > 1:
selected[-1] = f'and {selected[-1]}'
print('I want ', ', '.join(selected), '!', sep='')
CodePudding user response:
Make plate
a list, and append to it in the loop. In the end, you can use the following, which will output the correct commas and words:
", ".join(plate)