Python: cannot concatenate str and int objects error

Python: cannot concatenate str and int objects error

use the str function in order to convert currency to a string

def shop():
      print Hello  + name + , what would you like? You have $ + str(currency)

Python takes a strict view towards types and doesnt convert between type implicitly like dynamic languages do. If you want your numbers to become strings, you must explicitly convert to string with the str function. This is part of the Zen of Python:

Explicit is better than implicit.

By requiring the programmer to explicitly convert between types there removes some surprises where numbers or strings get added. For example, it is not immediately obvious if 2 + 3 + foo should equal 23foo or 5foo

There are sometimes where you dont have to explicitly convert to a string, for example in print statements, numbers will automatically be converted to strings if they are the only thing in the statement. However, if you attempt to add the number to a string before hand passing it to the print statement, then you have to explicitly convert to a string.

If your case, you want to say

print Hello  + name + , what would you like? You have $ + str(currency)

Python: cannot concatenate str and int objects error

The + operator has its own behaviour for some variable types (or object class, to be more precise). This is called operator overloading. In the case of adding two integers, the result is the obvious:

a = 1
b = 5
print(a+b)
   Out[0]: 6

In the other side, when you try to add two strings, Python understands it as concatenation. So:

a = hi 
b = my friend
print(a+b)
    Out[0]: hi my friend

In your case, you are trying to add a string and an integer. Python does not have any idea how to add these, or more precisely, the + operator is not defined when adding objects str and int. In order to fix your code, you need to cast the variable currency to string:

def shop():
  print Hello  + name + , what would you like? You have $ + str(currency)

Leave a Reply

Your email address will not be published. Required fields are marked *