patternpythonMinor
Python adding machine
Viewed 0 times
machinepythonadding
Problem
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 answerSolution
Without actually code-golfing, there are still a few shortenings possible:
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
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):
Have a look at the tips for golfing in python.
If you also want to forego the interface:
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])Code Snippets
def ask(n):
return float(input("Give %s number " % n))
ans = ask("first") + ask("second")
print(int(ans) if not ans % 1 else ans)a=lambda n:float(input("Give %s number "%n))
r=a("first")+a("second")
print((int(r),r)[r%1>0])r=sum(float(input())for _ in"_"*2)
print((int(r),r)[r%1>0])Context
StackExchange Code Review Q#141261, answer score: 4
Revisions (0)
No revisions yet.