Skip to content
Advertisement

Why is it that when I return int(n) where n is a float it will still return a float?

So I’ve been trying to make a program to convert float into a integer and if the input is not a float (such as a string) just return the string:

def convert(n):
     if n == float:
          return int(n)
     else:
          return n

However when I give it a float such as 1.0 it will only return 1.0 and totally not convert it.

Does anyone know what is going on here? Any help will be accepted.

Advertisement

Answer

The problem is n == float. That’s not how you check an object’s type. See What’s the canonical way to check for type in Python? For example:

def convert(n):
     if isinstance(n, float):
          return int(n)
     else:
          return n
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement