+ 1
Is there any inbuilt function or any modules for this if else statement
num = 1.0 if num % 1 == 0: int(num) else: None print(num) Output:- 1 https://sololearn.com/compiler-playground/cu124eMkXjgT/?ref=app
9 odpowiedzi
+ 6
math.fmod()
will be recommended to perform modulo operations on float values.
If you’re using a negative operand, then you may see different results between math.fmod(x, y) and x % y.
+ 4
You may be looking for .is_integer() see
https://sololearn.com/compiler-playground/ckRLx39inAqO/?ref=app
+ 3
Thank you JaScript
+ 2
P A Arrchith Iyer ,
I like your program's output, and it didn't take long, even though the code comment said it might.
However, I agree with the general consensus that the problem you think you have that you're trying to solve with that complicated input validation is a non-problem, because a float is already the perfect type for those math routines.
I refactored that section like so, and it worked fine.
# Input Validation
while True:
try:
num = float(input())
except ValueError:
print("Input must be a number.")
else:
break
(Of course, on Sololearn, the user doesn't get a second chance at input, but the loop will work in an IDE.)
+ 1
At first I was thinking about ternary conditional expressions...
num = 1.23
num = int(num) if num%1==0 else None
print(num) # Nothing printed
But after inspecting your code in # Input Validation, else: None doesn't have any effect.
You code simply check if "num" is a number not a string. Even it is a number it won't convert a number with decimal point into an integer. It only converts to integer if the decimal digits are all zero.
+ 1
P A Arrchith Iyer
yes, I agree with Wong Hei Ming . I'm unclear what that check is for. Is it to convert whole number float to int?
1.0 to 1
2.0 to 2
What's the advantage in that?
also there is no need for the
else:
None
+ 1
Thank you Rain
0
Thank you Mirielle