NoaG96
NoaG96

Reputation: 5

How to return int if whole number, while ignoring floats and strings

I want to take an input, which can be float or string, and if it's a whole number, return int(input), otherwise just return input.

So far i tried using excep ValueError but this didnt sem to work.

def whole_number(num): #takes float or str
    try:
        x = num%1
        if x == 0:
            return int(num)
        else:
            return num
    except ValueError:
        return num

print(whole_number(1.1)) #should return 1.1
print(whole_number(9.0)) #should return 9
print(whole_number("word")) #should return "word"

but keep getting the error "TypeError: not all arguments converted during string formatting"

any suggestions? thanks

Upvotes: 0

Views: 85

Answers (1)

Austin
Austin

Reputation: 26039

You can use float.is_integer() to check for whole numbers:

def whole_number(num): # takes float or str
    return int(num) if isinstance(num, float) and num.is_integer() else num

Sample usage:

>>> whole_number(1.1)
1.1
>>> whole_number(9.0)
9
>>> whole_number("word")
word

What's wrong?

num = 'word'
print(num%1)

..is the part your code fails. Using mod operation on string, Python considers it as an attempt to format string with'%' throwing "TypeError: not all arguments converted during string formatting".

Upvotes: 6

Related Questions