2015-10-14 62 views
0

我以前曾问过一个问题,而这个问题是关于同一主题的。我简化了以前的代码(从我提出的其他问题),但我总是对字符串,整数和浮点数感到困惑。我试图在if和else语句中设置变量,然后在另一个变量中使用这些变量来打印出来,或者我可以简单地打印出数学本身。这是代码:打印变量字符串并在数学方程中使用它们

# This program asks for the size of pizza and how many toppings the customer would like and calculates the subtotal, tax and total cost of the pizza. 
print ('Would you like a large or extra large pizza?') 
sizeOfPizza = input() 
print() # Blank space to separate text out 
print ('How many toppings would you like? (1, 2, 3 or 4)') 
numberOfToppings = input() 
print() # Blank space to separate text out 
if sizeOfPizza == 'large': 
    sizeOfPizzaCost = 6 
else: 
    sizeOfPizzaCost = 10 
if numberOfToppings == '1': 
    numberOfToppingsCost = 1 
elif numberOfToppings == '2': 
    numberOfToppingsCost = 1.75 
elif numberOfToppings == '3': 
    numberOfToppingsCost = 2.50 
elif numberOfToppings == '4': 
    numberOfToppingsCost = 3.35 
subtotal = (sizeOfPizzaCost) + (numberOfToppingsCost) 
finalCost = (subtotal) * 1.13 
print("The subtotal is $ " + str(subtotal)) 
print('Tax is 13%') 
print('The total cost is $ ' str(finalCost)) 
input() 

我只是不明白如何与变量应用数学和打印他们,因为我不断收到一个语法错误,我是否添加(浮点(my_var)或类似(INT(my_var) 。如果不是变量和调用它们,我只是在print()函数内打印出数学会容易得多。

对不起,如果解决方案很简单。 (v3.5.0),我不经常使用它。

谢谢:)

+0

无关的问题,但我会建议使用'dict'来代替'if elif ...'语句的大列表。这样你就可以拥有像'toppingsCosts = {'1':1,'2':1.75,'3':2.50 ....}'的东西,并设置你需要做的成本:'numberOfToppingsCost = toppingsCosts [numberOfToppings]'。这样看起来更清洁一些。 – xgord

+0

感谢您的提示。不幸的是,它似乎干扰了设置披萨大小的成本。我非常喜欢组织,但我仍然很喜欢Python。我会记住,列表是可用的。 :) – Zacharias

回答

2

你也可以使用字符串.format方法。这样你就不需要将float/int/etc转换为str

相反的:

print("The subtotal is $ " + str(subtotal)) 
print('Tax is 13%') 
print('The total cost is $ ' + str(finalCost)) 

这样做:

print('The subtotal is $ {}'.format(subtotal)) 
print('Tax is 13%') 
print('The total cost is $ {}'.format(round(finalCost,2)) 

你可以连续使用这些结合在一起,所以这样的事情是可能的:

print(""" 
     The subtotal is $ {} which is based on a {} 
     pizza with a base price of {} and {} toppings x {}. 
     Adding 13% tax for a total of {}. 
     """.format(subtotal, sizeOfPizza, sizeOfPizzaCost, numberOfToppings, numberOfToppingsCost, finalCost)) 
+0

感谢您的快速回复!它修正了它,但不幸的是(在某些情况下)总成本变成重复小数。使用round()有什么建议? – Zacharias

+0

'round(finalCost,2)'? –

+0

我非常了解。只是好奇,我把它放在代码中。 – Zacharias

1

您的代码中有语法错误。您的行在这里:

print('The total cost is $ ' str(finalCost)) 

缺少'+'。应该是这样的:

print('The total cost is $ ' + str(finalCost)) 
+1

谢谢你!我不知道我没注意到。轻松修复;有用。 :) – Zacharias

相关问题