如何在python中创建一个利润计算器?

时间:2015-12-06 13:47:33

标签: python

我无法确定此代码的问题,它给了我

Traceback (most recent call last):
File "python", line 7, in <module>
File "python", line 5, in profit_calculator
TypeError: cannot concatenate 'str' and 'int' objects" 

我称之为

buy1= raw_input("You bought item 1 for: ")
buy2 =raw_input("You bought item 2 for: ")
buy3 =raw_input("You bought item 3 for: ")
sold1=raw_input("You sold item 1 for: ")
sold2=raw_input("You sold item 2 for: ")
sold3=raw_input("You sold item 3 for: ")



def profit_calculator():
    profit1 = int(sold1) - int(buy1)
    profit2 = int(sold2) - int(buy2)
    profit3 = int(sold3) - int(buy3)
    return "Your profits are " + profit1 + " " + profit2 + " " + profit3 + " "

3 个答案:

答案 0 :(得分:0)

你得到一个例外,因为Python期望连接两个字符串。相反,你要连接一个字符串和一个整数。在连接之前,请使用以下语法将整数转换为字符串:

{{1}}

编辑:用stark提到的推荐的施法功能替换`。

答案 1 :(得分:0)

只需将您的退货行更改为:

return "Your profits are " + str(profit1) + " " + str(profit2) + " " + str(profit3) + " "

答案 2 :(得分:0)

使用string formatting

"Your profits are {} {} {}".format(profit1, profit2, profit3)

这使您的代码更易于阅读。

您还可以为占位符使用名称:

 "Your profits are {p1} {p2} {p3}".format(p1=profit1, p2=profit2, p2=profit3)

如果您有许多值,这将非常有用。此外,您可以完全控制小数和更多细节。