0

I have this if code for a vending machine and I feel like it could be shortened, any ideas?

Potato_size = raw_input(“Would you like a small, medium or large potato?”)
if Potato_size == “Small”:
    print “The price is £1.50 without toppings, continue?”
elif Potato_size == “Medium”:
    print “The price is £2.00 without toppings, continue?”
elif Potato_size == “Large”:
    print “The price is £2.50 without toppings, continue?”
else:
    print “Please answer Small, Medium or Large.”

Thanks

1
  • 8
    Better use proper quotes Commented May 20, 2015 at 16:26

3 Answers 3

6

That should remove the if/elif clauses

Potato_size = raw_input("Would you like a small, medium or large potato?")

Sizes={"Small":"£1.50","Medium":"£2.00","Large":"£2.50"}
try:
   print "The price is {} without toppings, continue?".format(Sizes[str(Potato_size)])
except NameError:
    print "Please answer Small, Medium or Large."
Sign up to request clarification or add additional context in comments.

3 Comments

Yes! This is THE way to go
You really should have except NameError: instead of the blanket except
or use Sizes.get(str(Potato_size,'This is not on sale'))
0

Not the best but it's the shortest posted yet.

sizes={"SMALL":"£1.50","MEDIUM":"£2.00","LARGE":"£2.50"}
price_str = {k: "The price is {} without toppings, continue?".format(v)
                 for k, v in sizes.iteritems()}

potato_size = raw_input("Would you like a small, medium or large potato?  ")
print price_str.get(potato_size.upper(), "Please answer Small, Medium or Large.\n")

Comments

-1

You can use a dict to shorten this,

potato_size ={
    "small": “The price is £1.50 without toppings, continue?”
    "medium":“The price is £2.00 without toppings, continue?”
    "large" :“The price is £2.50 without toppings, continue?”
}
user_input =  raw_input(“Would you like a small, medium or large potato?”)
if user_input in potato_size :
    print potato_size[user_input]
else:
    print “Please answer Small, Medium or Large.”

1 Comment

Hard-coding the whole statement to print in the dictionary is not a flexible solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.