2

I'm new to this forum and new to python after c++.

I have a problem with a python calculator. When I run it and I do it with + for example : 10 + 5 gives 105, but I wanted to get 15.

Other operations don't even work (I get an error).

print("\nCalculator In Python")
print("\nChose The Operation :")
print("\na)+\n\nb)-\n\nc)/\n\nd)*")
answer = input("\n\n: ")
result = int

if answer == 'a':
    a = input("\n\nFirst Number : ")
    b = input("\n\nSecond Number : ")
    print(a, "+", b, "=", a+b)
elif answer == 'b':
    a = input("\n\nFirst Number : ")
    b = input("\n\nSecond Number : ")
    print(a, "-", b, "=", a-b)
elif answer == 'c':
    a = input("\n\nFirst Number : ")
    b = input("\n\nSecond Number : ")
    print(a, "/", b, "=", a/b)
elif answer == 'd':
    a = input("\n\nFirst Number : ")
    b = input("\n\nSecond Number : ")
    print(a, "*", b, "=", a*a)
user
  • 5,370
  • 8
  • 47
  • 75

3 Answers3

3

a+b is actually '10'+'5', which is '105'. This is happening because input() gives a string. So you need to convert it to a number first.

float(input())

Additionally, to ensure the user gives only valid numbers, you can use:

while True:
    a = input('\nGive a:')

    try:
        a = float(a)
        break
    except ValueError:
        print('Try again.')
user
  • 5,370
  • 8
  • 47
  • 75
0

The 'input' functions return a string that contains "10" and "5". Conducting a + operator on two strings concatenates them (i.e. "10" + "5" = "105").

If you convert the input to an float or integer you'll get the result you're looking for:

>>> a = "5" + "5"
>>> a
'55'
>>> 
>>> b = float("5") + float("5")
>>> b
10.0
MattV
  • 1,353
  • 18
  • 42
0

Python is setting your input to strings. You could check this with the "type(a)" function.

You would need to convert the input to either a float or integer.

integer = int(a)
FloatingPoint = float(a)