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
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" .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.