TypeError: object of type 'int' has no len() - Python/Pygame
11,510
Solution 1
If you just want the value of self.cookie_count
, you can just use
self.draw_text('Cookies: {}'.format(self.cookie_count)
The len()
function returns the number of items in an object such as an array and does not work on an int
object.
Solution 2
You can try removing the len()
function as your self.cookie_count
is already an int.
So your answer should be:
self.draw_text('Cookies: {}'.format(self.cookie_count))
Related videos on Youtube
Author by
Josh Parkinsons
Updated on June 04, 2022Comments
-
Josh Parkinsons almost 2 years
I am creating a cookie clicker game, where there is a surface that displays how many cookies I have.
Here is my code for drawing text.
def draw_text(self, text, font_name, size, color, x, y, align="nw"): font = pg.font.Font(font_name, size) text_surface = font.render(text, True, color) text_rect = text_surface.get_rect() self.screen.blit(text_surface, text_rect)
Then in the new function of my game loop (for when a new game starts), I created a variable:
def new(self): self.cookie_count = 0
And then finally, I have my drawing function.
def draw(self): self.draw_text('Cookies: {}'.format(len(self.cookie_count)), self.cookie_font, 105, SKYBLUE, 325, HEIGHT * 3/4, align="nw") pg.display.update()
Yet, when I run the program, I get:
TypeError: object of type 'int' has no len()
I am new to creating a "score counter" you could call it. But why does
self.draw_text('Cookies: {}'.format(len(self.cookie_count))
give me an error? How come the length of self.cookie_count is not printed?
-
TheDetective almost 7 yearsI'm not quite sure what you're trying to do with
len
, but it doesn't work onint
.len
returns how long a string is. -
Alexander almost 7 years
.format(self.cookie_count)
-
-
xgord almost 7 yearsYou should put the relevant information from that link in your answer, as links can become deprecated over time.
-
juanpa.arrivillaga almost 7 years
len
is not a "string or list function", it works for anything that implements__len__
, and that is most built-in container types. -
rlbond almost 7 yearsnote that your
log10
algorithm only works on positive integers. -
robinCTS almost 7 yearsCongratulations on your first answer. A couple of good tips for you: 1) Use backticks (`) to quote functions, variables and other code snippets inline. 2) Use four spaces at the start of a line to create a code block. These tips and other useful information can be found by clicking on the help icon at the top right hand corner of the answer box.
-
robinCTS almost 7 yearsJust a helpful tip for you - if you use backticks (`) around inline code snippets it makes your answer clearer.
-
robinCTS almost 7 yearsUsing backticks (`) around inline code snippets helps to make answers clearer.
-
TBlock almost 7 years@robinCTS Thanks! Totally forgot.