繁体   English   中英

打印变量字符串并将其用于数学方程式

[英]Printing strings of variables and using them in mathematical equations

我之前曾问过一个问题,这是关于同一主题的。 我简化了之前的代码(从我问的另一个问题),但是我总是对字符串,整数和浮点数感到困惑。 我试图在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)的新手,我并不经常使用它。

谢谢 :)

您也可以使用字符串.format方法。 这样,您无需将float / int / etc strstr

代替:

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))

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

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

缺少“ +”。 应该是这样的:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM