Python Forum
Very basic calculator question - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Very basic calculator question (/thread-35750.html)



Very basic calculator question - BoudewijnFunke - Dec-09-2021

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


RE: Very basic calculator question - deanhystad - Dec-09-2021

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 "/"?


RE: Very basic calculator question - menator01 - Dec-09-2021

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



RE: Very basic calculator question - deanhystad - Dec-10-2021

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.


RE: Very basic calculator question - BoudewijnFunke - Dec-10-2021

Thank you everybody!