Python calculator tutorial

Posted by pneudralics on Fri, 04 Mar 2022 20:01:24 +0100

This article has two versions of the calculator. Below is the table of contents


Let's start with the box calculator

Framed calculator

For this calculator, we use the Tkinter library that comes with Python

# Import tkinter Library
import tkinter

We need to do some basic operations on the window

# Get a window
window = tkinter.Tk()
# Set title
window.title('Calculator')
# Set window size
window.geometry('200x200')

Then define an input method with a function

Input method

# Input method
def add(n):
    # Gets the value of the n1 text box
    n1 = inp.get()
    # Empty text box
    inp.delete(0,len(n1))
    # Insert the original plus the new input parameter n
    inp.insert(0,n1+str(n))

Then use the function to define a calculation method

computing method

# Execution calculation method
def calc():
    n1 = inp.get()  
    inp.delete(0,len(n1))
    # Use eval to execute the string of the text box once, and then insert it into the text box
    inp.insert(0,str(eval(n1)))

After completion, you need to clear the text box. We still use the function

Clear text box method

# Empty text box
def clear():
    n1 = inp.get()  
    inp.delete(0,len(n1))

After clearing the text box, a character will be left. We need to delete the last character and still use the function

Method of deleting the last character

# Delete last character
def back():
    n1 = inp.get()  
    inp.delete(len(n1)-1,len(n1))

Then we calculate the absolute value

Calculate absolute value

# Calculate absolute value
def ab():
    n1 = inp.get()  
    inp.delete(0,len(n1))
    inp.insert(0,str(eval(n1)*-1))

Set some text boxes as part of the button

Set text box

# Set a text box
inp = tkinter.Entry(window, width=25)
# Merge 5 columns in row 0 and 0
inp.grid(row=0,column=0,columnspan=5)

Make some more function buttons

Function button

# Delete button (window, width, text, execute command) grid(1 row, 0 column)
tkinter.Button(window,width=5, text="C", command=clear).grid(row=1,column=0)
tkinter.Button(window,width=5, text="←", command=back).grid(row=1,column=1)
tkinter.Button(window,width=5, text="+/-", command=ab).grid(row=1,column=2)

Remake operator button

operator

# Delete button (window, width, text, background color, text color, execute command and pass in parameters) grid(1 row, 4 columns)
tkinter.Button(window,width=5, text="+",bg="#f70",fg="#fff",command=lambda:add("+")).grid(row=1,column=4)
tkinter.Button(window,width=5, text="-", bg="#f70",fg="#fff",command=lambda:add("-")).grid(row=2,column=4)
tkinter.Button(window,width=5, text="×",bg="#f70",fg="#fff",command=lambda:add("*")).grid(row=3,column=4)
tkinter.Button(window,width=5, text="÷",bg="#f70",fg="#fff",command=lambda:add("/")).grid(row=4,column=4)
tkinter.Button(window,width=12,text="0", command=lambda:add("0")).grid(row=5,column=0,columnspan=2)
tkinter.Button(window,width=5,text="=", bg="#f70",fg="#fff",command=calc).grid(row=5,column=4)
tkinter.Button(window,width=5, text=".", command=lambda:add(".")).grid(row=5,column=2)

Finally, we found that there were no 123 456 789 buttons, so we created them with the for loop
Add code to

# Set a text box
inp = tkinter.Entry(window, width=25)
# Merge 5 columns in row 0 and 0
inp.grid(row=0,column=0,columnspan=5)

Below

9 buttons

# Set a text box
inp = tkinter.Entry(window, width=25)
# Merge 5 columns in row 0 and 0
inp.grid(row=0,column=0,columnspan=5)
# Create 123 456 789 buttons with the for loop
for i in range(0,3):
    for j in range(1,4):
      n = j+i*3
      btn=tkinter.Button(window, text=str(j+i*3),width=5, command=lambda n=n:add(n))
      btn.grid(row=i+2,column=j-1)

A calculator with a box is ready. See the end of the article for the complete code

Command line calculator

The code of this calculator is very short and can be learned quickly
First, get the first number and the second number

Get number

# Get the first number of operations through user input
num1 = int(input("Enter the first number: "))
# Get the second number of operations through user input
# The default is a string. You need to use int to convert characters into an array
num2 = int(input("Enter the second number: "))
# Prompt user for operator

We also have to add while True to ensure that the code is executed repeatedly, otherwise the calculator cannot calculate multiple times
Add while True before

while True:
	# Get the first number of operations through user input
	num1 = int(input("Enter the first number: "))
	# Get the second number of operations through user input
	# The default is a string. You need to use int to convert characters into an array
	num2 = int(input("Enter the second number: "))
	# Prompt user for operator

So it can be repeated
Then get the operation method

Operation method

print("Input operation: 1. Addition; 2. Subtraction; 3. Multiply; 4. Divide")
# Gets the operation symbol entered by the user
choice = input("Enter your choice(1/2/3/4):")

Then judge the addition

Judgment addition

# If 1
if choice == '1':
	print(num1,"+",num2,"=", num1+num2)

Subtraction, multiplication and division are similar to addition. You can try it yourself

division























division

If you don't, you can see mine

The rest

# If 2
	elif choice == '2':
		print(num1,"-",num2,"=", num1-num2) 
	elif choice == '3':
		print(num1,"×",num2,"=", num1*num2) 
	elif choice == '4':
		print(num1,"÷",num2,"=", num1/num2)

Then bridge them to the bottom of the addition

bridging

while True:
	# Get the first number of operations through user input
	num1 = int(input("Enter the first number: "))
	# Get the second number of operations through user input
	# The default is a string. You need to use int to convert characters into an array
	num2 = int(input("Enter the second number: "))
	# Prompt user for operator
	print("Input operation: 1. Addition; 2. Subtraction; 3. Multiplication; 4. Divide")
	# Gets the operation symbol entered by the user
	choice = input("Enter your choice(1/2/3/4):")
	# If 1
	if choice == '1':
		print(num1,"+",num2,"=", num1+num2)
	# If 2
	elif choice == '2':
		print(num1,"-",num2,"=", num1-num2) 
	elif choice == '3':
		print(num1,"×",num2,"=", num1*num2) 
	elif choice == '4':
		print(num1,"÷",num2,"=", num1/num2)

The algorithm part is good. We also need to add an else, otherwise the output will be wrong

else

# Everything else is illegal
else:
	print("illegal input")

Finally, we add else to the bottom of the upper part

Bridge 2

while True:
	# Gets the first number of operations through user input
	num1 = int(input("Enter the first number: "))
	# Get the second number of operations through user input
	# The default is a string. You need to use int to convert characters into an array
	num2 = int(input("Enter the second number: "))
	# Prompt user for operator
	print("Input operation: 1. Addition; 2. Subtraction; 3. Multiplication; 4. Divide")
	# Gets the operation symbol entered by the user
	choice = input("Enter your choice(1/2/3/4):")
	# If 1
	if choice == '1':
		print(num1,"+",num2,"=", num1+num2)
	# If 2
	elif choice == '2':
		print(num1,"-",num2,"=", num1-num2) 
	elif choice == '3':
		print(num1,"×",num2,"=", num1*num2) 
	elif choice == '4':
		print(num1,"÷",num2,"=", num1/num2)
	# Everything else is illegal
	else:
		print("illegal input")

Both calculators have been introduced, and the next is the complete code

Complete code

Framed calculator

# Import tkinter Library
import tkinter

# Get a window
window = tkinter.Tk()
# Set title
window.title('Calculator')
# Set window size
window.geometry('200x200')

# Input method
def add(n):
    # Gets the value of the n1 text box
    n1 = inp.get()
    # Empty text box
    inp.delete(0,len(n1))
    # Insert the original plus the new input parameter n
    inp.insert(0,n1+str(n))

# Execution calculation method
def calc():
    n1 = inp.get()  
    inp.delete(0,len(n1))
    # Use eval to execute the string of the text box once, and then insert it into the text box
    inp.insert(0,str(eval(n1)))

# Empty text box
def clear():
    n1 = inp.get()  
    inp.delete(0,len(n1))

# Delete last character
def back():
    n1 = inp.get()  
    inp.delete(len(n1)-1,len(n1))

# Calculate absolute value
def ab():
    n1 = inp.get()  
    inp.delete(0,len(n1))
    inp.insert(0,str(eval(n1)*-1))

# Set a text box
inp = tkinter.Entry(window, width=25)
# Merge 5 columns in row 0 and 0
inp.grid(row=0,column=0,columnspan=5)


# Create 123 456 789 buttons with a for loop
for i in range(0,3):
    for j in range(1,4):
      n = j+i*3
      btn=tkinter.Button(window, text=str(j+i*3),width=5, command=lambda n=n:add(n))
      btn.grid(row=i+2,column=j-1)
# Delete button (window, width, text, execute command) grid(1 row, 0 column)
tkinter.Button(window,width=5, text="C", command=clear).grid(row=1,column=0)
tkinter.Button(window,width=5, text="←", command=back).grid(row=1,column=1)
tkinter.Button(window,width=5, text="+/-", command=ab).grid(row=1,column=2)

# Delete button (window, width, text, background color, text color, execute command and pass in parameters) grid(1 row, 4 columns)
tkinter.Button(window,width=5, text="+",bg="#f70",fg="#fff",command=lambda:add("+")).grid(row=1,column=4)
tkinter.Button(window,width=5, text="-", bg="#f70",fg="#fff",command=lambda:add("-")).grid(row=2,column=4)
tkinter.Button(window,width=5, text="×",bg="#f70",fg="#fff",command=lambda:add("*")).grid(row=3,column=4)
tkinter.Button(window,width=5, text="÷",bg="#f70",fg="#fff",command=lambda:add("/")).grid(row=4,column=4)
tkinter.Button(window,width=12,text="0", command=lambda:add("0")).grid(row=5,column=0,columnspan=2)
tkinter.Button(window,width=5,text="=", bg="#f70",fg="#fff",command=calc).grid(row=5,column=4)
tkinter.Button(window,width=5, text=".", command=lambda:add(".")).grid(row=5,column=2)

# Enter message loop
window.mainloop()

Command line calculator

while True:
	# Get the first number of operations through user input
	num1 = int(input("Enter the first number: "))
	# Get the second number of operations through user input
	# The default is a string. You need to use int to convert characters into an array
	num2 = int(input("Enter the second number: "))
	# Prompt user for operator
	print("Input operation: 1. Addition; 2. Subtraction; 3. Multiplication; 4. Divide")
	# Gets the operation symbol entered by the user
	choice = input("Enter your choice(1/2/3/4):")
	# If 1
	if choice == '1':
		print(num1,"+",num2,"=", num1+num2)
	# If 2
	elif choice == '2':
		print(num1,"-",num2,"=", num1-num2) 
	elif choice == '3':
		print(num1,"×",num2,"=", num1*num2) 
	elif choice == '4':
		print(num1,"÷",num2,"=", num1/num2)
	# Everything else is illegal
	else:
		print("illegal input")

Topics: Python