Answer to Question #302408 in Python for Daniel

Question #302408
# Various Icecream flavors
menu_item1 = "Chocolate"
menu_item2 = "Vanilla"
menu_item3 = "Strawberry"

order = input("\nWhich flavors would you like on your icecream today?\n\n" +
              "\n".join([menu_item1, menu_item2, menu_item3]) + "\n\n")

# Convert input to list of flavors.
order = order.lower().split()
plural = "s" if len(order) > 1 else " "
union = " and " if len(order) > 1 else " "
print("\nYou have selected " + ", " .join(order[:-1]) + union + order[-1] + " flavor" + plural)


Question: How do I fix the Extra space for 1 flavor of choice and duplicated words and comma's for 2 or more flavors of choice?


My Output: "You have selected Chocolate flavor"

My Output: "You have selected Chocolate, and and Vanilla flavors"

My Output: "You have selected Chocolate, , Vanilla, and and Strawberry flavors"


1
Expert's answer
2022-02-25T03:39:58-0500
# Various Icecream flavors
menu_item1 = "Chocolate"
menu_item2 = "Vanilla"
menu_item3 = "Strawberry"


order = input("\nWhich flavors would you like on your icecream today?\n\n" +
              "\n".join([menu_item1, menu_item2, menu_item3]) + "\n\n")


# Convert input to list of flavors.
order = order.lower().split(" ")
if(len(order)==1):
    print("You have selected",str(order[0]))
    
if(len(order)==2):
    print("You have selected",order[0],"and",order[1])
    
if(len(order)>2):
    s=""
    for r in range(0,len(order)-1):
        if(r<len(order)-2):
            s = s+order[r]+", "
        else:
            s = s+order[r]
    s = s + " and " + order[len(order)-1]
    print("You have selected",s)

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS