繁体   English   中英

如何缩短if / elif python代码?

[英]How can I shorten this if/elif python code?

我有自动售货机的代码,我觉得可以缩短它,有什么想法吗?

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

谢谢

那应该删除if/elif子句

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

不是最好的,但是发布的最短。

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

您可以使用字典来缩短此时间,

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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