1

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.

TheHappyBee
  • 169
  • 1
  • 10

4 Answers4

4

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
wjandrea
  • 28,235
  • 9
  • 60
  • 81
1

Although almost all answers I see are correct, I would like to point out that your else statement would not be necessary if you return a result in the if one. What I mean is, your code could be shorter like this:

def convert(n):
    if isinstance(n, float):
        return int(n)
    return n

However, the important part as everyone mentioned is the fact that you were not correctly comparing types by doing if n == float:.

Sherlock Bourne
  • 490
  • 1
  • 5
  • 10
0

it's because your if statement is never true ! try this :

if type(n) == float:
   return int(n)
shervin
  • 1
  • 3
0

It's should be like:

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