1

I tried to code a simple calculator but as a beginner I don't know how to actually convert my input strings into float or int. I want the output to be integer when it is 2 but not 2.0 while the output to be 2.5 when its a float. But I coded this and entered 1 + 1 I still get 2.0

from ast import literal_eval

# User input a simple calculation
num1, operator, num2 = input('Please enter a simple math calculation ').split()
num1 = float(num1)
num2 = float(num2)

# Convert string into either int or float
def convertString1 (num1):
    val = literal_eval(num1)
    return isinstance(val, int) or (isinstance(val, float) and val.is_integer())
def convertString2 (num2):
    val = literal_eval(num2)
    return isinstance(val, int) or (isinstance(val, float) and val.is_integer())


# Condition to perform calculation and output
if operator ==  "+" :
    print("{} + {} = {}".format(num1, num2, num1+num2))
elif operator == "-" :
    print("{} - {} = {}".format(num1, num2, num1-num2))
elif operator == "*" :
    print("{} * {} = {}".format(num1, num2, num1*num2))
elif operator == "/" :
    print("{} / {} = {}".format(num1, num2, num1/num2))
else :
    print("Syntax error")
3
  • 3
    Because you are converting the values to float... num1 = float(num1) num2 = float(num2). Also functions don't call themselves, you have to do that Commented Aug 24, 2017 at 15:25
  • 1
    Why have you defined functions you don't use? Commented Aug 24, 2017 at 15:25
  • You could also use literal_eval to parse 1 as an int but 1.0 as a float. Commented Aug 24, 2017 at 15:30

2 Answers 2

2

It is better to add if statement. For example

if int(res) == res:
    res = int(res)
Sign up to request clarification or add additional context in comments.

Comments

0

The reason your numbers are displaying that way is because you're evaluating num1 and num2 as floats. If you wanted to test if you have an int, you could try something like if int(num1) == num1: to decide if you want to apply additional formatting. That leads into altering how it displays:

If all you're concerned with is how it displays, since you're already using format, try something like

"{:.0f}".format(a)

This will round the value, however, if you're sure that it's an int, then rounding it won't have any affect apart from visual.

Comments

Your Answer

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.