I was wondering if there is any way to make this code smaller/condensed. It is for a school project which says it has to be as small as it can be and I am not sure whether it can go any smaller.
num1 = float(input("Give first number "))#Get first number
num2 = float(input("Give second number ")) #Get second number
ans = num1 + num2 #Work out answer
if ans % 1 == 0: #If its a whole number
print (int(ans)) #Convert to int so its for example 14 instead of 14.0
else: #If not a whole number
print (ans) #Print the answer
1 Answer 1
Without actually code-golfing, there are still a few shortenings possible:
def ask(n):
return float(input("Give %s number " % n))
ans = ask("first") + ask("second")
print(int(ans) if not ans % 1 else ans)
This uses a function for asking for the numbers, does not store the intermediate values, uses a ternary expression for printing and the fact that zero evaluates to False
.
If you actually want it as small as possible (in bytes), this is a start, but can probably be golfed down a lot further (e.g. by encoding the strings):
a=lambda n:float(input("Give %s number "%n))
r=a("first")+a("second")
print((int(r),r)[r%1>0])
Have a look at the tips for golfing in python.
If you also want to forego the interface:
r=sum(float(input())for _ in"_"*2)
print((int(r),r)[r%1>0])
-
1\$\begingroup\$ Since the function body is a single expression, you could make it a
lambda
and eliminate thereturn
. \$\endgroup\$200_success– 200_success2016年09月13日 19:31:16 +00:00Commented Sep 13, 2016 at 19:31 -
\$\begingroup\$ @200_success Thanks, edited. I'm not a code-golfer, but this is so much fun, I might actually try it :) \$\endgroup\$Graipher– Graipher2016年09月13日 19:33:27 +00:00Commented Sep 13, 2016 at 19:33
-
\$\begingroup\$ Could you explain how this works in more detail please? print(int(ans) if not ans % 1 else ans) \$\endgroup\$L Smith– L Smith2016年09月13日 19:50:13 +00:00Commented Sep 13, 2016 at 19:50
-
1\$\begingroup\$ @LSmith
ans % 1
returns either0
or not.0
is considered False in python, sonot ans % 1
isTrue
for whole numbers (where the mode gives 0). This is used in a ternary expression which are of the formatexpression1 if condition else expression2
in python. \$\endgroup\$Graipher– Graipher2016年09月13日 19:52:39 +00:00Commented Sep 13, 2016 at 19:52