Here is an example of a simple calculator program that performs addition, subtraction, multiplication & division using Python.
The first step in this program is Defining functions:
#Calculator Program Python
#The below while loop is to avoid running the console again and again, so that the user can perform calculations as per his wish.
stop_calc = False
def add(a,b):
return a +b;
def sub(a,b):
return a-b;
def mul(a,b):
return a*b;
def div(a,b):
return a/b;
After defining the basic functions above, we will use the below code to run the Python calculator program.
#Below the while loop will run till the flag becomes true so that the user can use the calculator without having to run the calculator program and again & again
while stop_calc==False:
val1 = int(input("What is the first number? "))
val2 = int(input("What is the second number? "))
print("+\n-\n/\n*")
#In the below input we will get the values from the user on what operation he wants to perform and the appropriate function will be called from the above-defined ones
a = input("Please enter the operation you want to perform: ")
if a=="+":
answer = add(val1,val2)
if a=="-":
answer = sub(val1,val2)
if a=="*":
answer = mul(val1,val2)
if a=="/":
answer = div(val1,val2)
#The below print statement prints the final solution
print (f"{val1} {a} {val2} = {answer}")
b = input("Please choose yes or no")
if b=="no":
stop_calc= True
No comments:
Post a Comment