Why does my Python calculator dont work?


#1

Here’s my code :
num1 = input("enter number ")
operator = input("enter operator +,-,*,/ ")
num2 = input("enter another number ")

if (operator == “+”):
print (“your math:” , num1, “+”, num2)
print (“rusult:”, num1 + num2)

When i run the code, it works relativ normal, but the result that comes out is’nt true.
if i do 2 + 2 it says 22 and not 4, what did i do wrong?


#2

Hey dervl3nn4n,

You say that your code is producing a result which isn’t true, but from Python’s perspective it is doing what you’ve asked it to do.

Let’s say that, when we run your code, we’re seeing (and entering) the following in the terminal:

Enter number:  2
Enter operator: +
Enter another number: 2
Your math: 2+2
Result: 22

Obviously, we all know that 2 + 2 = 4 (unless we’re dealing with exceptionally large values of 2 :grin: ) so the question is why Python is telling you it’s 22?

22 is valid, and correct, output if we wanted your code to be concatenating two strings. This is what your Python code is doing.

If we know that Python is interpreting your + operator as “concatenate these strings”, what would we need to change to tell Python that you actually want to add two numbers?


#3

and how do i tell python now that i dont want to add two strings?
i started learning like 1 week ago and i really have no idea :smiley:
the last line (print (“result:”, num1 + num2)) doesn’t say that the numbers are string or did i understand something wrong?


#4

You are doing great dervl3nn4n. Only one week and already doing a calculator in Python? Congratulations!

The solution is simple, let me explain the error first. When you ask for an input, normally it is always a string, your are actually storing strings in num1 and num2, that is why when you use the + operator, it ‘adds’ (concatenate) these values.

So, what you need to do is convert these strings into numbers (integers or floats) to add them.
There is a built-in function to do that, int(). You can see the reference here.

Then, a possible solution would be:

#Python Calculator by dervl3nn4n
num1 = input("Enter number: ")
operator = input("Enter operator +,-,*,/: ")
num2 = input("Enter another number: ")

if (operator == '+'):
    print('Your math:' , num1, '+', num2)
    print('Result:', int(num1) + int(num2))

Try it out!


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.