TheHappyBee
TheHappyBee

Reputation: 303

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.

Upvotes: 1

Views: 112

Answers (4)

The Punisher
The Punisher

Reputation: 562

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:.

Upvotes: 1

Chaibedraa Ibrahim
Chaibedraa Ibrahim

Reputation: 101

It's should be like:

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

Upvotes: 0

shervin
shervin

Reputation: 1

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

if type(n) == float:
   return int(n)

Upvotes: 0

wjandrea
wjandrea

Reputation: 33107

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

Upvotes: 4

Related Questions