Reputation: 19
This is my Python code and I would like to know why the error
TypeError: can only concatenate str (not "int") to str
is happening, and how to fix it:
import random
print("Welcome to the Text adventures Game\nIn this Game you will go on an amazing adventure.")
print("Following are the rules:\n1.You can type the directions you want to go in.\n2. There will be certain items that you will encounter. You can type grab to take it or leave to leave it\n3.In the starting, we will randomly give you 3 values. It is your choice to assign them to your qualites.\nYour Qualities are:\n1.Intelligence\n3.Attack\n4.Defence\n These Qualities will help you further in the game")
print("With these, You are all set to play the game.")
Name=input(str("Please Enter Your Name: "))
a=input("Hi "+Name+", Ready To Play The Game?: ")
Intelligence=0
Attack=0
Defence=0
if a=="yes"or a=="y":
value1=random.randint(0,100)
choice1=input("Your Value is: \n"+value1+ "\nYou would like to make it your Intelligence,Attack Or Defence level? ")
Upvotes: 0
Views: 1089
Reputation: 5329
You want to concatenate a string with an integer and it is not possible. You should cast your integer to string, like this: str(value1)
.
BUT, more efficient to use the .format()
method of the string. This method automatically cast the integer type to str.
In your case:
choice1=input("Your Value is: \n{}\nYou would like to make it your Intelligence,Attack Or Defence level? ".format(value1))
Or if you use Python 3.6+
, the formatted string is also available. The starting f
character indicates the formatted strings.
In your case:
choice1=input(f"Your Value is: \n{value1}\nYou would like to make it your Intelligence,Attack Or Defence level? ")
You can find several Python string formatting on this page: https://realpython.com/python-string-formatting/
Upvotes: 0
Reputation: 19
This happens because the value stored in the variable is an integer and you are concatenating it in between string.
to do so:----
use str() method :
The str() function returns the string version of the given object.
It internally calls the __str__()
method of an object.
If it cannot find the __str__()
method, it instead calls repr(obj).
Return value from repr() The repr() function returns a printable representational string of the given object.
so typecasting value1 integer variable with str().
str(value1)
Happy coding :)
Upvotes: 0
Reputation: 1413
You are trying to add int
to string
try this
if a=="yes"or a=="y":
value1=random.randint(0,100)
choice1=input("Your Value is: \n"+str(value1)+ "\nYou would like to make it your Intelligence,Attack Or Defence level? ")
Upvotes: 3