Python Forum

Full Version: Very basic calculator question
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Dear people, i have recently started learning Python (about a week ago) and i am trying to write a calculator.
At first i made a simple one, to do adding up. But then i wanted to give the user the option to choose between + - or /.
I get to the point where everything adds up to be 10+10 example, instead of 20.

this is my code:

[attachment=1456]

this is what i get when i run it:

[attachment=1457]

How do i make it go from 10+10 to 20?
I've already tried changing str to int or float, but it gave an error.

Thank you!

Boudewijn
Please post your code, not screenshots.

Your code concatenates strings. If you type in +, 1, 2 then sum is going to be "1+2". Sounds like you want to to do is add the numerical values to produce the sum 3.

Changing first and second to floats is a good start, but what are you going to do for choice? How can you code add two numbers when choice is "+", subtract second from first when choice is "-", compute the product when choice is "*" and the quotient when choice is "/"?
Have a look at eval

One way could be

operators = ['+', '-', '*', '/']
choose = input(f'Choose Operator: {operators} ')
num1 = float(input('num1 >> '))
num2 = float(input('num2 >> '))
total = f'{num1}{choose}{num2}'
print(eval(total))
Output:
Choose Operator: ['+', '-', '*', '/'] + num1 >> 5 num2 >> 3 5.0+3.0 = 8.0
Eval is lazy, dangerous and evil. Well maybe not evil, but definately lazy and dangerous. Figure out how your program can take appropriate actions based on the choice input.
Thank you everybody!