What is a calculator?
A calculator is something used for making mathematical calculations, in particular a small electronic device with a keyboard and a visual display.
How can I make one in python?
Glad you ask! I will guide you (reader) towards making a simple terminal calculator. Let’s start by writing down what should our calculator have:
- users input on what operation they want
- a addition if statement
- a subtraction if statement
- a multiplication if statement
- a division if statement
How to do all of this?
I will shortly explain how to do the things mentioned above.
Users input ( https://codinghelp.site/wiki/python/3-python-input-function/ )
Firstly, you want to print something like “Please select an operation (+, /, *, -)”. For this, we are going to use the input function, that same input function will be assigned to a variable named users_input. You also want to ask for the first and second number with the input function (cast them to number1 and number2 variables), set their datatype to float.
If statements ( https://codinghelp.site/wiki/python/5-python-if-statement/ )
We will not only use if statements here, we will also use elif + else! We are going to have singular if statement, three elif statements and an else statement. In the IF statement you should check if the user has selected the “+” sign, if they have, use the print function to tell the user what’s the sum of the 2 numbers, use the + operator. The output should be something like number1+number2=something. You will want to repeat all these steps for other signs as well. Lastly, the ELSE statement will indicate that they’ve specified a invalid option, you should raise a ValueError. Wrap all of this in a try/except clause, except for a ValueError.
In words how to do this (you have to just translate to python)
PRINT Please select an operation (+, /, *, -) USERS_INPUT = INPUT NUMBER1 = INPUT PLEASE ENTER THE FIRST NUMBER NUMBER2 = INPUT PLEASE ENTER THE SECOND NUMBER TRY IF USERS_INPUT IS EQUAL TO + PRINT NUMBER1 + NUMBER2 = NUMBER1+NUMBER2 IF USERS_INPUT IS EQUAL TO / PRINT NUMBER1 / NUMBER2 = NUMBER1/NUMBER2 IF USERS_INPUT IS EQUAL TO - PRINT NUMBER1 - NUMBER2 = NUMBER1-NUMBER2 IF USERS_INPUT IS EQUAL TO * PRINT NUMBER1 * NUMBER2 = NUMBER1*NUMBER2 ELSE RAISE VALUEERROR EXCEPT VALUEERROR PRINT BAD INPUT
Code for this exercise; https://pastebin.com/AhTCtVvb (please try to do it yourself 🙂 if you have any difficulties ask on our subreddit or the discord)