Search code examples
pythonfunctionreturn-value

Why does my function self.deleteTime == None?


So as you can see in the code it should return a random number between 2 and 10 but in return None why??

                self.deleteTime = self.buttonGrow.is_pressed(mousePos, mousePressed)
                print(self.deleteTime)

class Button():
    def __init__(self, x, y, height, width, image, content, fontsize, actionID):
        self.font = pygame.font.Font('assets/font/font.otf', fontsize)
        self.content = content

        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.id = actionID
        self.screen = pygame.display.get_surface()
        self.fg = (82, 82, 82)

        # Load the image and set the button's image surface dimensions
        self.background_image = pygame.image.load(image)
        self.background_image = pygame.transform.scale(self.background_image, (self.width, self.height))
        self.rect = self.background_image.get_rect()

        self.rect.x = self.x
        self.rect.y = self.y

    def set_position(self, x, y):
        self.rect.x = x
        self.rect.y = y

    def draw(self):
        # Draw the button's background image
        self.screen.blit(self.background_image, self.rect)

        # Render the text and center it on the button
        text_render = self.font.render(self.content, True, self.fg)
        text_rect = text_render.get_rect(center=(self.rect.centerx, self.rect.centery))
        self.screen.blit(text_render, text_rect)

    def is_pressed(self, pos, pressed):
        if self.rect.collidepoint(pos):
            if pressed[0] and self.id == 1:
                self.newTime = random.randint(2, 10)
                print(self.newTime)
                return self.newTime

I was expecting the result to be a random number between 2 to 10 but it always returns None.


Solution

  • it can return None as default return type of method if none of your if statement executed then function returns nothin(None)

    if self.rect.collidepoint(pos) - false self.id != 1 or pressed[0] - false

    def is_pressed(self, pos, pressed):
        if self.rect.collidepoint(pos):
            if pressed[0] and self.id == 1:
                self.newTime = random.randint(2, 10)
                print(self.newTime)
                return self.newTime