[英]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 那应该删除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."
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.”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.