如何将用户给出的变量转换为数字

时间:2015-03-31 01:05:07

标签: python string integer converter

以下代码

steak = 40.00
pepsi = 3.45
order1 = input("What would you like to have?")
order2 = input("What would you like to have?")
total = order1 + order2

如何将order1order2转换为数字,以便根据用户选择的内容添加?

2 个答案:

答案 0 :(得分:1)

听起来你想要加上用户选择购买的商品的价格。

products = {'steak':40.00, 'pepsi':3.45}
order1 = input("What would you like to have? ")
order2 = input("What would you like to have? ")
total = products.get(order1) + products.get(order2)
print(total)

这会打印43.45给定steakpepsi的订单。您可以根据需要进行进一步的计算(税,小费,变更等)。

答案 1 :(得分:0)

有很多方法可以做到这一点,但这可能是最简单的方法:

x = raw_input("What would you like to eat? ")
if x == "Steak":
    price1 = 40
else:
    print "Sorry we only have steak!"

y = raw_input("What would you like to drink? ")
if y == "Pepsi":
    price2 = 3.45
else:
    print "Sorry but we only have Pepsi!"

total = price1 + price2

print total