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

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))

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)
  • 1
    \$\begingroup\$ Since the function body is a single expression, you could make it a lambda and eliminate the return. \$\endgroup\$ Sep 13 '16 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
    Sep 13 '16 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
    Sep 13 '16 at 19:50
  • 1
    \$\begingroup\$ @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. \$\endgroup\$
    – Graipher
    Sep 13 '16 at 19:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.