+

How do I make a calculator in Python?

We will use math operators, conditionals, functions and user input to build our calculator in Python.

Your system must have Python 3 installed on your local computer and have a programming environment configured.

User input

We will accept user input. We will use the Python input () function for this purpose. In this program, we will allow the user to enter two numbers, so let`s run the program to ask for two numbers.



 num_1 = input (`Enter your first number:`) num_2 = input (`Enter your second number:`) 

Output: < / p>

 Enter your first number: 10 Enter your second number: 5 

We must save the program before running it. You should be able to enter text in the terminal window in response to each prompt. 

Defining and Using Operators

Now let`s add operators such as addition, multiplication, division and subtraction to our calculator program.



 num_1 = int (input (`Enter your first number:`)) num_2 = int (input (` Enter your second number: `)) # Addition print ( ` {} + {} = `.format (num_1, num_2)) print (num_1 + num_2) # Subtraction print (` {} - {} = `.format (num_1 , num_2)) print (num_1 - num_2) # Multiplication print (`{} * {} =` .format (num_1, num_2)) print (num_1 * num_2) # Division print (`{} / {} =` .format (num_1, num_2)) print (num_1 / num_2) # The format () will help out output look descent and formatted. 

Output:

 Enter your first number: 15 Enter your second number: 10 15 + 10 = 25 15 - 10 = 05 15 * 10 = 150 15/10 = 1.5 

If you look at the above output, we can notice that as soon as the user enters num_1 as 15 and num_2 as 10 , all calculator operations are performed.

If we want to restrict the program to only one operation at a time, we have to use conditional statements and make the whole program of operations based on the user`s choice.

So we`ll start by adding some information at the top of the program along with the choices that need to be made so that the user knows what to choose.

 choice = input (`` `Please select the type of operation you want to perform: + for addition - for subtraction * for multiplication / for division ` ``) num_1 = int (input (`Enter your first number:`)) num_2 = int (input (`Enter your second number:`)) if choice == `+`: print (`{} + {} = `.format (num_1, num_2)) print (num_1 + num_2) elif choice ==` -`: print (`{} - {} =` .format (num_1, num_2)) print (num_1 - num_2) elif choice = = `*`: print (`{} * {} =` .format (num_1, num_2)) print (num_1 * num_2) elif choice == `/`: print (`{} / {} =` .format ( num_1, num_2)) print (num_1 / num_2) else: print (`Ente ra valid operator, please run the program again.`) 

Output:

 Please select the type of operation you want to perform: + for addition - for subtraction * for multiplication / for divis ion * Please enter the first number: 10 Please enter the second number: 40 10 * 40 = 400 



Get Solution for free from DataCamp guru