Holla Tech - Learn

Creating a Calculator
 

This lesson is about an example Python project: a simple calculator. 
Each part explains a different section of the program.
The first section is the overall menu. This keeps on accepting user input until the user enters “quit”, so a while loop is used. 

while True:
   print(“Options:”)
   print(“Enter ‘add’ to add two numbers”)
   print(“Enter ‘subtract’ to subtract two numbers”)
   print(“Enter ‘multiply’ to multiply two numbers”)
   print(“Enter ‘divide’ to divide two numbers”)
   print(“Enter ‘quit’ to end the program”)
   user_input = input(“: “)

   if user_input == “quit”:
      break
   elif user_input == “add”:
     
   elif user_input == “subtract”:
     
   elif user_input == “multiply”:
     
   elif user_input == “divide”:
     
   else:
      print(“Unknown input”

 

NOTE!
The code above is the starting point for our program. It accepts user input, and compares it to the options in the if/elif statements. The break statement is used to stop the while loop, in case the user inputs “quit”.

Creating a Calculator
 

The next part of the program is getting the numbers the user wants to do something with.
The code below shows this for the addition section of the calculator. Similar code would have to be written for the other sections.

elif user_input == “add”:
  num1 = float(input(“Enter a number: “))
  num2 = float(input(“Enter another number: “)) 

 

Now, when the user inputs “add”, the program prompts to enter two numbers, and stores them in the corresponding variables.

NOTE!
As it is, this code crashes if the user enters a non-numeric input when prompted to enter a number. We will look at fixing problems like this in a later module.

Creating a Calculator
 

The final part of the program processes user input and displays it.
The code for the addition part is shown here.

elif user_input == “add”:
  num1 = float(input(“Enter a number: “))
  num2 = float(input(“Enter another number: “))
  result = str(num1 + num2)
  print(“The answer is “ + result

 

We now have a working program that prompts for user input, and then calculates and prints the sum of the input.

NOTE!
Similar code would have to be written for the other branches (for subtraction, multiplication and division). The output line could be put outside the if statements to omit repetition of code.

BACK NEXT

CLICK ON THE BUTTON BELOW TO GO TO THE PYTHON MAIN COURSE PAGE. 

PYTHON MAIN COURSE PAGE

 


©️ License: All Rights Reserved 


CONTACT HOLLA TECH – LEARN SUPPORT