简体   繁体   中英

How can I shorten this if/elif python code?

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

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."

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")

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.”

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM