how to make a profit calculator in python?

Question:

I can’t identify what the problem is with this code , and it gives me

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" 

when I call it

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 + " "
Asked By: Oti Oritsejafor

||

Answers:

You get an exception because Python expects to concatenate two strings. Instead you’re concatenating a string and an integer. Use the following syntax instead to cast the integer to a string before concatenating it:

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

EDIT: Replaced ` with the recommended casting function as mentioned by stark.

Answered By: xaviert

Just change your return line to:

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

Answered By: Simon

Use string formatting:

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

This makes your code better readable.

You can also use names for placeholders:

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

This is useful if you have many values. Furthermore, you have full control over the number of decimal and more details.

Answered By: Mike Müller
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.