【问题标题】:Printing strings of variables and using them in mathematical equations打印变量字符串并在数学方程中使用它们
【发布时间】:2015-10-14 03:04:07
【问题描述】:

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

谢谢:)

【问题讨论】:

  • 与问题无关,但我建议使用 dict 而不是您的大量 if elif ... 语句。这样你就可以拥有类似toppingsCosts = {'1' : 1, '2' : 1.75, '3' : 2.50 ....} 的东西并设置你只需要做的成本:numberOfToppingsCost = toppingsCosts[numberOfToppings]。那样看起来更干净一些。
  • 感谢您的提示。不幸的是,它似乎干扰了设置披萨大小的成本。我确实喜欢组织,但我仍然喜欢 Python。我会记住,列表是可用的。 :)

标签: python string variables math printing


【解决方案1】:

您也可以使用字符串.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))

【讨论】:

  • 感谢您的快速回复!它修复了它,但不幸的是(在某些情况下)总成本结果是一个重复的小数。使用 round() 有什么建议吗?
  • round(finalCost, 2)?
  • 我知道的就这么多了。只是好奇我把它放在代码中的什么地方。
  • 你可以把它放在打印语句print('The total cost is $ {}'.format(round(finalCost,2))),或者放在赋值中:finalCost = round((subtotal) * 1.13, 2)
  • 刚刚添加进去。完美运行。感谢您的所有帮助。
【解决方案2】:

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

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

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

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

【讨论】:

  • 也谢谢您!我不知道我怎么没有注意到这一点。易于修复;有用。 :)
猜你喜欢
  • 2015-06-10
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 2016-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多