Whenever I run my code an error comes which states "TypeError: can only concatenate str (not "int") to str" this comes in the output = output text.yellow number
line. I understand thati can't add an integer with a string and for that I have also changed its type just before the line but it doesn't seem to work and I cant understand what the error is and how to solve it, hep would be really appreciated
My code is as below:
Info:
The text.yellow
is a class attribute which just changes the text to yellow color.
available_numbers and choosen_numbers is a list
def print_board():
number = 1
output = ""
while number < 91:
if number in available_numbers:
str(number)
output = output text.yellow number
int(number)
elif number in choosen_numbers:
str(number)
output = output text.green number
int(number)
number = 1
print(output)
CodePudding user response:
You should store str(number)
and int(number)
into the number
variable if you want to actually change number
.
But anyway, you should use f-string or format in order to concat int and strings, for example:
output = f"{output} {text.yellow} {number}"
just in case you still want to format it using
, you should do something like:
output = output text.yellow str(number)
make sure that text.yellow
is also a str
CodePudding user response:
The variable number is still an integer. Try this instead: output = output text.green str(number)
or store the string version in a variable like this string_number = str(number)
and use that variable for concatenation
CodePudding user response:
Try this:
def print_board():
number = 1
output = ""
while number < 91:
if number in available_numbers:
output = output text.yellow str(number)
elif number in choosen_numbers:
output = output text.green str(number)
number = 1
print(output)
CodePudding user response:
Precisely you can convert integer to string but unfortunately, you cannot save it anywhere. Do this
number=str(number)
or
this
output = output text.yellow str(number)
instead of this
str(number)
CodePudding user response:
You don't need to change the type every time when you need to change it. You can change the type at the moment when you need it and don't have to change it back))