Larry Li
Larry Li

Reputation: 133

'>' not supported between instances of 'float' and 'NoneType'

I run the following code to define some basic objects:

import logging

class State:
    """A class representing a US state."""
        
    def __init__(self, name, postalCode, population):
        self.name = name
        self.postalCode = postalCode
        self.population = population
        
    def __str__(self):
        """Readable version of the State object"""
        return 'Name: ' + self.name + ", Population (in MM): " + str(self.population) + ", PostalCode: " + self.postalCode
    
    def increase_population(self, numPeople):
        """Increases the population of the state."""
        self.population += numPeople
        print("Population of",self.name,"increased to",self.population,"million.")
        
    def decrease_population(self, numPeople):
        """Decreases the population of the state."""
        try:
            if (numPeople > self.population):
                raise ValueError("decrease_population(self, numPeople): Invalid value for population reduction")
            else:
                # decrease the population by the value in variable numPeople
                self.population -= numPeople

                # Print new population
                print("Population of",self.name,"decreased to",self.population,"million.")
        except Exception as e:
            logging.exception(e)            

# Test Cases             
# Create an instance of State 'il' corresponding to Illinois, with a postal code of IL and a population of 12.8 million
il = State("Illinois","IL",12.8)

# use the given method to increase the population of il by 1 million
il.population = State.increase_population(il, 1)

# use the given method to decrease the population of il by 1.5 million
il.population = State.decrease_population(il, 1.5)

However I received a TypeError: '>' not supported between instances of 'float' and 'NoneType' The error is on line

            if (numPeople > self.population):

I tried to find a solution on SO but did not find an answer that works.

Upvotes: 0

Views: 1182

Answers (1)

John Byro
John Byro

Reputation: 734

It looks like you are mixing instance methods i.e self and static/class methods.

change your code to

il = State("Illinois", "IL", 12.8)

# use the given method to increase the population of il by 1 million
il.increase_population(1)

# use the given method to decrease the population of il by 1.5 million
il.decrease_population(1.5)

The instance method increase_population return None which makes

il.population = State.increase_population(il, 1)

to None Also increase_population(il, 1) is instance method , which can be called like il.increase_population(1) while you have passed instance name into it and calling like static_method

Same explanation with method decrease_population

Upvotes: 1

Related Questions