Home > Enterprise >  Why does the num.is_integer() function returns false
Why does the num.is_integer() function returns false

Time:07-29

class Item:
    pay_rate = 0.8 # The pay after   discount
    all = []
    def __init__(self, name: str, price: float, quantity=0):
        #Run validations to the recieved arguments
        assert price >= 0, f"Price {price} is not greater than or equal tozero!"
        assert quantity >= 0, f"Quantity {quantity} is not greater than or equal to zero!"

        # Assign to self object
        self.name = name
        self.price = price
        self.quantity = quantity

        #Actions to execute

        Item.all.append(self)


    def calculate_total_price(self):
        return self.price * self.quantity

    def apply_discount(self):
        self.price = self.price * self.pay_rate

    @classmethod
    def instantiate_from_csv(cls):
        with open('items.csv', 'r') as f:
            reader = csv.DictReader(f)
            items = list(reader)
        for item in items:
        Item(
                name=item.get('name'),
                price=float(item.get('price')),
                quantity=int(item.get('quantity')),
            )
    @staticmethod
    def is_integer(num):
        #We will count out the floats that are .0
        if isinstance(num, float):
            #Count out the floats that are point zero
            return num.is_integer()
        elif isinstance(num, int):
            return True
        else:
            return False

    def __repr__(self):
        return f"Item('{self.name}', {self.price}, {self.quantity})"

Im currently learning python and trying to understand the OOP Concept.I understood it all except the following lines

def is_integer(num):
    #We will count out the floats that are .0
    if isinstance(num, float):
        #Count out the floats that are point zero
        return num.is_integer()
    elif isinstance(num, int):
        return True
    else:
        return False

Can someone explain me why num.is_integer() returns False? That function is defined for the purpose of removing .0 from floats like 100.0 or 50.0 (Tutorial says that)

It's my firs time encountering this type of return usage.I'm accustomed to return a*b or return 'Hi' type of stuff.

CodePudding user response:

If your is_integer() function is returning False it's because you're either passing a float that has a significant fractional part or some object that is neither int nor float.

You might find this change to that function useful:

def is_integer(n):
    if __debug__:
        print(type(n))
    return n.is_integer() if isinstance(n, float) else isinstance(n, int)

CodePudding user response:

Firstly, there is nothing unusual about this type of return. To use your examples:

  1. return 'Hi' - returns the string 'Hi' back
  2. return a * b - say a=3, b=5, it calculates a*b and returns the result, 15
  3. return num.is_integer() - this will check if the number is an integer or not and returns the result, True or False

One note on is_integer(), it will say both 50 and 50.0 are integers even though strictly speaking, 50 is a int datatype and 50.0 is a float datatype in Python. If you go through the below code with this knowledge then it seems it does the same thing except that you would call it with Item.is_integer(50).

def is_integer(num):
    #We will count out the floats that are .0
    if isinstance(num, float):
        #Count out the floats that are point zero
        return num.is_integer()
    elif isinstance(num, int):
        return True
    else:
        return False
  • Related