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

Without actually code-golfing, there are still a few shortenings possible:

return float(input("Give %s number " % n))

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])
• Since the function body is a single expression, you could make it a lambda and eliminate the return. Sep 13 '16 at 19:31
• @200_success Thanks, edited. I'm not a code-golfer, but this is so much fun, I might actually try it :) Sep 13 '16 at 19:33
• Could you explain how this works in more detail please? print(int(ans) if not ans % 1 else ans) Sep 13 '16 at 19:50
• @LSmith ans % 1 returns either 0 or not. 0 is considered False in python, so not ans % 1 is True for whole numbers (where the mode gives 0). This is used in a ternary expression which are of the format expression1 if condition else expression2 in python. Sep 13 '16 at 19:52