A beginner python programming learner here.
I'm making a very simple two number calculator in python. Although it runs perfectly, I can't fix the issue with floating numbers ending with ".0". I want to remove this ending. I tried a few things but they didn't work. What condition do I need to add inside the code? Could you please take a look at it below:
def calculator():
num1 = float(input('First number: '))
operator = input('+, -, / or * ? ')
num2 = float(input('Second Number: '))
if operator == '+':
return print(num1, '+', num2, '=', num1 + num2)
elif operator == '-':
return print(num1, '-', num2, '=', num1 - num2)
elif operator == '/':
return print(num1, '/', num2, '=', num1 / num2)
elif operator == '*':
return print(num1, '*', num2, '=', num1 * num2)
calculator()
Thank you in advance!
I exactly did what @water-winter suggested but whenever I execute the program and enter numbers and operator I get this error: if result.is_integer():
AttributeError: 'int' object has no attribute 'is_integer'
Update: Looks like that only "/" operator works perfectly. The other 3 operators give the same error above. :/
New Update: Finally I managed to make the calculator programming flawlessly!
def calculator():
num1 = float(input("First number: "))
operator = input("Choose: +, -, /, or *")
num2 = float(input("Second number: "))
num1 = int(num1) if num1.is_integer() else num1
num2 = int(num2) if num2.is_integer() else num2
add = (num1 + num2)
subtract = (num1 - num2)
divide = (num1 / num2)
multiply = (num1 * num2)
if operator == "+" and add % 1 == 0:
print(num1, "+", num2, "is equal to:", int(add))
elif operator == "+" and not add % 1 == 0:
print(num1, "+", num2, "is equal to:", add)
elif operator == "-" and subtract % 1 == 0:
print(num1, "-", num2, "is equal to:", int(subtract))
elif operator == "-" and not subtract % 1 == 0:
print(num1, "-", num2, "is equal to:", subtract)
elif operator == "/" and divide % 1 == 0:
print(num1, "/", num2, "is equal to:", int(divide))
elif operator == "/" and not divide % 1 == 0:
print(num1, "/", num2, "is equal to:", divide)
elif operator == "*" and multiply % 1 == 0:
print(num1, "*", num2, "is equal to:", int(multiply))
elif operator == "*" and not multiply % 1 == 0:
print(num1, "*", num2, "is equal to:", multiply)
calculator()
Thank you guys, for the help and suggestions. They helped a lot! :)