Sitemap
Kelvin Chicas

Kelvin Chicas

programmer and graphic designer

A Basic calculator with Python

2 min readNov 2, 2022

What do we need to have a basic calculator in python?
multiply, add, subtract and divide. now how do we do this?

Press enter or click to view image in full size

let’s see a brief analysis of what we need to do to translate our idea into python language:

1) we need the user to enter 2 numbers and be able to capture them in variables and then operate them

2) then, using a decision structure, we will capture and evaluate the option requested from the user, that is, what mathematical operation the user wants to do

3) finally, we will show the result to the user and together with it we will show the options menu to start the operation again

4) As a special case we will take into account that division by zero does not exist, so we to consider that our second number is greater than zero in case the user selects divide

hands to the code!!!

# — — — — — — — — — — start of the code— — —— — — — — — — — — — — —

#we ask the user to enter two numbers and we save it in variables

n1 = float(input(“Enter your first number: “) )

n2 = float(input(“Enter your second number: “) )

#using the while structure and an option variable we will ask the user to select what he wants to do

#then we will save the selected option in a variable

opcion = 0

while True:

print(“””

Tell me, what you want to do?

1) Add the two numbers

2) Restar los dos números

3) Multiply the two numbers

4) Divide the two numbers

5) Change the chosen numbers

6) Exit Calculator

“””)

Get Kelvin Chicas’s stories in your inbox

Join Medium for free to get updates from this writer.

opcion = int(input(“Choose an option: “) )

#using the variable that contains the selected option, using if we will show the different results

if opcion == 1:

print(“ “)

print(“Result: ”,n1,”+”,n2,” = ”,n1+n2)

elif opcion == 2:

print(“ “)

print(“Result: ”,n1,”-”,n2,” = ”,n1-n2)

elif opcion == 3:

print(“ “)

print(“Result: ”,n1,”*”,n2,” = ”,n1*n2)

elif opcion == 4:

if n2>0:

print(“ “)

print(“Result: ”,n1,”/”,n2,” = ”,n1/n2)

else:

print(“Division error by 0”)

elif opcion == 5:

n1 = float(input(“Enter your first number: “) )

n2 = float(input(“Enter your second number: “) )

elif opcion == 6:

break

else:

print(“Option Error”)

# — — — — — — — — — — end of the code — — — — — — — — — — — — — — —

Now just need to save it as a .py file
and run it in command console

--

--

Kelvin Chicas
Kelvin Chicas

Written by Kelvin Chicas

0 followers

programmer and graphic designer