Python Command Line Calculator Program
Last Update : 11 Oct, 2022This is a Python project example tutorial. In this example, You will learn to create a simple command-line calculator program using Python Programming Language.
This calculator can add, subtract, multiply or divide two numbers using user inputs.
To understand this code. You should know the Python programming topics such as Python Functions, User-defined Functions, Function Arguments, Python Loops, Python Conditions, etc.
Example : Python Command-Line Calculator
# Python Simple Command Line Calculator
#This is calculation function
def calculation(cal, num1, num2):
myList = []
if cal == '1':
myList.append('+')
myList.append(num1 + num2)
elif cal == '2':
myList.append('-')
myList.append(num1 - num2)
elif cal == '3':
myList.append('*')
myList.append(num1 * num2)
elif cal == '4':
myList.append('/')
myList.append(num1 / num2)
return myList
print("#############################")
print(" PYTHON CALCULATOR")
print("#############################")
print("")
print("Select Operation")
print("1 - Add")
print("2 - Subtract")
print("3 - Multiply")
print("4 - Divide")
print("")
print("#############################")
while True:
# Take the user input
print("")
operation = input("Enter Operation(1/2/3/4): ")
# Check if choice is one of the four Operation
if operation in ('1', '2', '3', '4'):
number1 = float(input("Enter first number: "))
number2 = float(input("Enter second number: "))
result = calculation(operation, number1, number2)
print(number1, result[0], number2, " = " , result[1])
# Check if user wants to do another calculation
# Break the loop if answer is 'n'
next_cal = input("Let's do next calculation? (y/n): ")
if next_cal == "n":
break
else:
print("")
print("Invalid user input")
Download source code - Python Command-Line Calculator
Program Output :
#############################
PYTHON CALCULATOR
#############################
Select Operation
1 - Add
2 - Subtract
3 - Multiply
4 - Divide
#############################
Enter Operation(1/2/3/4): 1
Enter first number: 200
Enter second number: 300
200.0 + 300.0 = 500.0
Let's do next calculation? (y/n): y
This program asks the User to select an operation from 1,2,3 or 4. If the user input other than 1,2,3 or 4, the program will display "Invalid User Input".
The User can input two numbers after entering a valid operation. Then, the program calls the calculation() function and displays the result on the screen.
Also, the program asks from User to do another calculation after displaying the result.