0

I am trying to make a calculator program in Python as a bit of a challenge. I am a beginner to python and I am probably making some really obvious mistake. In my calculator I ask the user to define the values and to select the operation they want to use. With the addition operation the calculator gives a strange output. For an example I am telling the calculator to add '7 + 7'. Instead of giving me the correct answer of 14, it gives me 77. Here is my code so far. Hope somebody can help. Cheers

#Sets the values for calculator to use
val1 = input ("Enter the first value: ")
val2 = input ("Enter the second value: ")

#Asks what operation to use
print ("1. Add")
print ("2. Subtract")
print ("3. Divide")
print ("4. Multiply")
op = input ("What operation should I use:")

#Addition
if op == '1':
    print(val1, " + ", val2, " = ", (val1 + val2))
1
  • 1
    typecast to int Commented Apr 26, 2019 at 22:18

2 Answers 2

2

The user input is of string type. That's why 7 + 7 becomes 77. You need to convert them to integer using int() (or float using float()) type to perform arithmetic

val1 = int(input ("Enter the first value: "))
val2 = int(input ("Enter the second value: "))

As pointed out by @Bailey Parker, in case the user input isn't a number, you can consider using try/except as mentioned here

Sign up to request clarification or add additional context in comments.

3 Comments

This worked, thanks for the help. Will accept answer after the cooldown
Note that int and float may raise a ValueError if the thing input isn't a number (ex. int('foo')). You probably want to do this in a try/except wrapped in a while.
@BaileyParker: Thanks for the pointer. I added your suggestion
0

When the + operator's two operands are strings, it will concatenate them together, creating a longer string. You'll need to turn your strings into integers to do math with them.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.