patternpythonModerate
Drink order program
Viewed 0 times
drinkorderprogram
Problem
I'm looking to improve my code to make it more efficient, such as shortening it but continuing to gain the same output, or to add some more complex functions into the code.
restart ='Y'
while restart not in ('N', 'n', 'NO', 'no'):
print ("Making A Cup Of Tea")
num_orders = int(input("How many for Tea? "))
print ("there are", num_orders, "People for tea")
orders = []
for i in range(num_orders):
b = input ("Person %i, Would you like Sugar? YES/NO " % (i + 1))
sugar = None
if b in ("YES", "Y", "y", "yes"):
sugar = input("How many sugars? ")
else:
print ("Okay No sugar")
milk = input("How Much Milk Would You Like? SMALL/MEDIUM/LARGE ")
print ("Order is being processed, next order:\n")
orders.append({'sugar': sugar, 'milk': milk })
print('The orders has been processed with these data:')
for i in range(num_orders):
order = orders[i]
print (' - Person', i + 1, 'wants tea', ('with %i' % int(order['sugar']) if
order['sugar'] else 'without'), 'sugar and ', order['milk'], 'milk')
print('')
restart = input('Would you like to Re-Order? Y/N')
if restart in ('n', 'N'):
print('')
print ('Okay, Thank You, Enjoy Your Tea')Solution
It's not always about shortening code, but in most cases about having your code easy to maintain. For example, if this code is to go in production, I would change it as follows:
I added few user input validators and separated key points of the program into methods. This did not make it shorter, but it did make it more maintainable and easier to change (which is inevitable in a real life software cycle).
I would also add tests, and
EDIT: The only style correction - which is tiny - is to not put space in
"""A script for ordering a tea party."""
YES = ('y', 'yes')
MILK_SIZES = ('small', 'medium', 'large')
while True:
print("Making a cup of tea.")
num_orders = ask_number_of_orders()
orders = []
for person_num in range(num_orders):
print("Person %d, would you like:" % person_num + 1)
sugar = ask_for_sugar()
milk = ask_for_milk()
orders.append((sugar, milk))
print("Your order is being processed.", end="")
if person_num + 1 < num_orders:
print(" Next order:")
print("The orders have been processed with the following data:")
for person_num, (sugar, milk) in enumerate(orders):
order_status = construct_order_status(person_num + 1, sugar, milk)
print(order_status)
print("")
restart = input("Would you like to re-order? Y/N.")
if restart.lower() not in YES:
print("")
print("Ok, thank you, enjoy your day!")
break
def ask_for_number_of_orders():
"""Get number of orders from the user."""
while True:
try:
num_orders = int(input("How many for tea?"))
if num_order < 1:
raise ValueError
print("There are %d people for tea." % num_orders)
return num_orders
except ValueError:
print("Please enter non-negative integer, let's try again.")
def ask_for_sugar():
"""Prompt user for sugar, if yes - how much.
Returns number of sugar cubes (int) or None.
"""
while True:
sugar = input("Would you like sugar? Y/N.")
if sugar.lower() not in YES:
print("Okay, no sugar.")
return
while True:
try:
sugar = int(input("How many sugars?"))
if sugar < 1:
raise ValueError
return sugar
except ValueError:
print("Please enter non-negative integer, let's try again.")
def ask_for_milk():
"""Prompts user for the amount of milk."""
while True:
milk = input("How much milk would you like? Small/medium/large.")
if milk.lower() in MILK_SIZES:
return milk.lower()
else:
print("Sorry, did not catch that. Small, medium, or large?")
def construct_order_status(person_num, sugar, milk):
"""Constructs order status string.
Args:
person_num: Number of the person.
sugar: Number of sugar cubes or None.
milk: Size of the milk: small, medium, or large.
Returns a string representing order status.
"""
order_status = " - Person %d wants tea " % person_num
if sugar is None:
order_status += "without sugar"
else:
order_status += "with %d pieces of sugar" % sugar
order_status += " and %s milk." % milk
return order_statusI added few user input validators and separated key points of the program into methods. This did not make it shorter, but it did make it more maintainable and easier to change (which is inevitable in a real life software cycle).
I would also add tests, and
__main__, but this is going out of the scope of the question. This is, again, just one way to look at the problem: from the real life software development cycle perspective.EDIT: The only style correction - which is tiny - is to not put space in
print (. In python3 it's a function, and according to PEP8 no leading spaces are permitted before the parentheses: http://legacy.python.org/dev/peps/pep-0008/#id18.Code Snippets
"""A script for ordering a tea party."""
YES = ('y', 'yes')
MILK_SIZES = ('small', 'medium', 'large')
while True:
print("Making a cup of tea.")
num_orders = ask_number_of_orders()
orders = []
for person_num in range(num_orders):
print("Person %d, would you like:" % person_num + 1)
sugar = ask_for_sugar()
milk = ask_for_milk()
orders.append((sugar, milk))
print("Your order is being processed.", end="")
if person_num + 1 < num_orders:
print(" Next order:")
print("The orders have been processed with the following data:")
for person_num, (sugar, milk) in enumerate(orders):
order_status = construct_order_status(person_num + 1, sugar, milk)
print(order_status)
print("")
restart = input("Would you like to re-order? Y/N.")
if restart.lower() not in YES:
print("")
print("Ok, thank you, enjoy your day!")
break
def ask_for_number_of_orders():
"""Get number of orders from the user."""
while True:
try:
num_orders = int(input("How many for tea?"))
if num_order < 1:
raise ValueError
print("There are %d people for tea." % num_orders)
return num_orders
except ValueError:
print("Please enter non-negative integer, let's try again.")
def ask_for_sugar():
"""Prompt user for sugar, if yes - how much.
Returns number of sugar cubes (int) or None.
"""
while True:
sugar = input("Would you like sugar? Y/N.")
if sugar.lower() not in YES:
print("Okay, no sugar.")
return
while True:
try:
sugar = int(input("How many sugars?"))
if sugar < 1:
raise ValueError
return sugar
except ValueError:
print("Please enter non-negative integer, let's try again.")
def ask_for_milk():
"""Prompts user for the amount of milk."""
while True:
milk = input("How much milk would you like? Small/medium/large.")
if milk.lower() in MILK_SIZES:
return milk.lower()
else:
print("Sorry, did not catch that. Small, medium, or large?")
def construct_order_status(person_num, sugar, milk):
"""Constructs order status string.
Args:
person_num: Number of the person.
sugar: Number of sugar cubes or None.
milk: Size of the milk: small, medium, or large.
Returns a string representing order status.
"""
order_status = " - Person %d wants tea " % person_num
if sugar is None:
order_status += "without sugar"
else:
order_status += "with %d pieces of sugar" % sugar
order_status += " and %s milk." % milk
return order_statusContext
StackExchange Code Review Q#44614, answer score: 12
Revisions (0)
No revisions yet.