我有这个,如果自动售货机的代码,我觉得它可以缩短,任何想法?
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.”
由于
答案 0 :(得分:6)
那应删除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."
答案 1 :(得分:0)
不是最好的,但它发布的时间最短。
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")
答案 2 :(得分:-1)
你可以用dict来缩短它,
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.”