4
\$\begingroup\$

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
200_success
146k22 gold badges190 silver badges479 bronze badges
asked Sep 13, 2016 at 19:05
\$\endgroup\$
0

1 Answer 1

4
\$\begingroup\$

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.