打印变量字符串并在数学方程中使用它们

时间:2015-10-14 03:04:07

标签: python string variables math printing

我之前曾问过一个问题,这是关于同一主题的。我已经简化了我之前的代码(来自我提出的另一个问题),但我总是对字符串,整数和浮点数感到困惑。我正在尝试在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()

我只是不明白如何使用变量应用数学并打印它们,因为无论我添加(float(my_var)还是喜欢(int(my_var))我都会遇到语法错误。相反,它会更容易制作变量并调用它们,我只需在print()函数中打印出数学。

很抱歉,如果解决方案非常简单。我还是Python(v3.5.0)的新手,我不经常使用它。

谢谢:)

2 个答案:

答案 0 :(得分: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))

答案 1 :(得分:1)

您的代码中存在语法错误。你的话在这里:

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

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

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