+ All Categories
Home > Documents > Noadswood Science, 2014. To create a simple and advanced calculator Friday, August 07, 2015 Apollo...

Noadswood Science, 2014. To create a simple and advanced calculator Friday, August 07, 2015 Apollo...

Date post: 22-Dec-2015
Category:
Upload: logan-knight
View: 224 times
Download: 0 times
Share this document with a friend
Popular Tags:
34
Noadswood Science, 2014
Transcript
Page 1: Noadswood Science, 2014.  To create a simple and advanced calculator Friday, August 07, 2015 Apollo 11 CalculatorModern GUI Calculator.

Noadswood Science, 2014

Page 2: Noadswood Science, 2014.  To create a simple and advanced calculator Friday, August 07, 2015 Apollo 11 CalculatorModern GUI Calculator.

To create a simple and advanced calculator

Wednesday, April 19, 2023

Apollo 11 Calculator Modern GUI Calculator

Page 3: Noadswood Science, 2014.  To create a simple and advanced calculator Friday, August 07, 2015 Apollo 11 CalculatorModern GUI Calculator.

Apollo 11

The Apollo spacecraft were the cutting edge of science – their code was extremely concise and relied on some inputs (radar / trajectory / velocity) and then gave some simple math calculations…

Although cutting edge the processing power of the spacecraft was about the same as that of a modern pocket calculator!

Page 4: Noadswood Science, 2014.  To create a simple and advanced calculator Friday, August 07, 2015 Apollo 11 CalculatorModern GUI Calculator.

Calculator

This project will focus on creating a simple calculator, followed by a more advanced one…

The initial task is to create a calculator layout as efficiently as possible – there are many similar buttons in a calculator so it makes more sense to build them by looping through lists rather than individual buttons being written

The initial task is to build a calculator one button at a time…

Page 5: Noadswood Science, 2014.  To create a simple and advanced calculator Friday, August 07, 2015 Apollo 11 CalculatorModern GUI Calculator.

Calculator – 1 Button

Write the following program for a single button calculator (simply clicking the button outputs the number ”1” to the display)

#Calculator 1 Buttonfrom tkinter import *from decimal import *

#Main Programwindow = Tk()window.title("Calculator")

#Displaydisplay = Entry(window, width=45, bg="light green")display.grid()

#Buttonsdef click1(): display.insert(END, "1")Button(window, text="1", width=5, command=click1).grid(row=1,column=0)

#Run Main Loopwindow.mainloop()

Page 6: Noadswood Science, 2014.  To create a simple and advanced calculator Friday, August 07, 2015 Apollo 11 CalculatorModern GUI Calculator.

Calculator – 1 Button

Page 7: Noadswood Science, 2014.  To create a simple and advanced calculator Friday, August 07, 2015 Apollo 11 CalculatorModern GUI Calculator.

Calculator – 3 Buttons

Using the previous code add some more to make multiply buttons (i.e. a button for number 2 and 3…)

Page 8: Noadswood Science, 2014.  To create a simple and advanced calculator Friday, August 07, 2015 Apollo 11 CalculatorModern GUI Calculator.

Calculator – 3 Buttons

To add more buttons then more functions can be defined…

def click2(): display.insert(END, "2")Button(window, text="2", width=5,

command=click2).grid(row=2,column=0)def click3(): display.insert(END, "3")Button(window, text="3", width=5,

command=click3).grid(row=3,column=0)

The problem with this solution is that every button requires three lines of code

This also becomes a major problem if something needs to change, such as the button size. Every line of code which has information about button size would then need to change

Page 9: Noadswood Science, 2014.  To create a simple and advanced calculator Friday, August 07, 2015 Apollo 11 CalculatorModern GUI Calculator.

Solution

It makes sense to have one function which handles the button clicks – then if we want to change its layout it will apply this change to every button we have…

This can be created using a loop

Page 10: Noadswood Science, 2014.  To create a simple and advanced calculator Friday, August 07, 2015 Apollo 11 CalculatorModern GUI Calculator.

Calculator – Multiple Buttons Write the following program for a multiple button calculator

(counter variables have been used for the rows and columns and they are increased to build the number pad (the buttons don’t actually do anything yet, but this is a much cleaner code already))

# Calculator Multiple Buttonsfrom tkinter import *from decimal import *#Key Press Functiondef click(key): display.insert(END, key)#Main Programwindow = Tk()window.title("Calculator")#Top Row Framestop_row = Frame(window)top_row.grid(row=0, column=0, columnspan=2, sticky=N)#Editable Displaydisplay = Entry(top_row, width=45, bg="light green")display.grid()

Page 11: Noadswood Science, 2014.  To create a simple and advanced calculator Friday, August 07, 2015 Apollo 11 CalculatorModern GUI Calculator.

Calculator – Multiple Buttons#Number Pad Framenum_pad = Frame(window)num_pad.grid(row=1, column=0, sticky=W)num_pad_list = ['7', '8', '9','4', '5', '6','1', '2', '3','0', '.', '=' ]#Number Pad Buttonsr = 0c = 0for btn_text in num_pad_list:#Code below currently doesn't actually work! Button(num_pad, text=btn_text, width=5, command=click).grid(row=r,column=c) c = c+1 if c > 2: c = 0 r = r+1#Operator Frameoperator = Frame(window)operator.grid(row=1, column=1, sticky=E)

Page 12: Noadswood Science, 2014.  To create a simple and advanced calculator Friday, August 07, 2015 Apollo 11 CalculatorModern GUI Calculator.

Calculator – Multiple Buttonsoperator_list = ['*', '/', '+', '-','(', ')','C' ]#Operator Buttonsr = 0c = 0for btn_text in operator_list: Button(operator, text=btn_text, width=5, command=click).grid(row=r,column=c) c = c+1 if c > 1: c = 0 r = r+1#Run Main Loopwindow.mainloop()

Page 13: Noadswood Science, 2014.  To create a simple and advanced calculator Friday, August 07, 2015 Apollo 11 CalculatorModern GUI Calculator.

Frames

One way of controlling groups of elements is by spanning columns, however it is often better to put groups of widgets in another widget known as a frame…

Number pad frame

(num_pad)

Top row frame (top_row)

Operator frame

Page 14: Noadswood Science, 2014.  To create a simple and advanced calculator Friday, August 07, 2015 Apollo 11 CalculatorModern GUI Calculator.

Simple Calculator

Open the simple calculator already produced

Simple_Calculator.py

Lets understand what is working here and how…

Page 15: Noadswood Science, 2014.  To create a simple and advanced calculator Friday, August 07, 2015 Apollo 11 CalculatorModern GUI Calculator.

For Loops

A for loop handles lists, dictionaries and tuples – they go through the intended code as many times as required (once for each button we need (once for each value of btn_text))

The variable btn_text is used to hold the values of the num_pad_list

On the first time around the loop btn_text represents string ‘7’

On the next time around the btn_text will be ‘8’

Each time around the loop the column counter c is increased by 1 until it is greater than 2

Page 16: Noadswood Science, 2014.  To create a simple and advanced calculator Friday, August 07, 2015 Apollo 11 CalculatorModern GUI Calculator.

Arguments

The for loop has made sending an argument using the click() function difficult, but it remains necessary to know which button is being referred to when the mouse is clicked…

To solve this arguments need to be sent indirectly using default values

Page 17: Noadswood Science, 2014.  To create a simple and advanced calculator Friday, August 07, 2015 Apollo 11 CalculatorModern GUI Calculator.

Arguments – Number Pad The function cmd() sets the value held by btn_text as a default

value of x which allows the cmd() function to be called without supplying any arguments meaning it will work without brackets

When cmd() is called by pressing a particular button it in turn calls click() with its defualt btn_text value supplied so click() function now knows which button is being sent to it

#Number Pad Buttonsr = 1c = 0for btn_text in num_pad_list: def cmd(x=btn_text): click(x) Button(num_pad, text=btn_text, width=5, command=cmd).grid(row=r,column=c) c = c+1 if c > 2: c = 0 r = r+1

Page 18: Noadswood Science, 2014.  To create a simple and advanced calculator Friday, August 07, 2015 Apollo 11 CalculatorModern GUI Calculator.

Arguments – Operator Buttons The buttons send a call to the click() function via cmd()

It is good code design to separate out appearance from function (the calculator is constructed separately from the click() function (which is where the work occurs))

#Operator Buttonsr = 2c = 0for btn_text in operator_list: def cmd(x=btn_text): click(x) Button(operator, text=btn_text, width=5, command=cmd).grid(row=r,column=c) c = c+1 if c > 1: c = 0 r = r+1

Page 19: Noadswood Science, 2014.  To create a simple and advanced calculator Friday, August 07, 2015 Apollo 11 CalculatorModern GUI Calculator.

Click Function

The code after the else: statement inserts the value or symbol of the button at the end of display

The code which handles the clear key after the elif statement deletes everything in the display from the first character (0) through to the end

The maths occurs after result (which is stored in the variable result)

#Key Press Functiondef click(key):#Calculate via equals key if key == '=': try: result = str(eval(display.get()))[0:10] display.insert(END, " = " + result) except: display.insert(END, " --> Error!")#Clear screen via c key elif key == "C": display.delete(0, END) #Add other key-pressed values to end of current entry else: display.insert(END, key)

Page 20: Noadswood Science, 2014.  To create a simple and advanced calculator Friday, August 07, 2015 Apollo 11 CalculatorModern GUI Calculator.

Maths

A series of functions are applied at the same time, for example the eval() function is a float or integer data type but it needs to be changed into a string using the str() function

Nesting function calls within other function calls makes it a lot neater, however it can be difficult to read. Written over multiple lines it becomes a little clearer…

result = str(eval(display.get()))

result = display.get() > store the contents of entry in a variable

result = eval(result) > use the eval() function to calculateresult = str(result) > cast the result into a string

Page 21: Noadswood Science, 2014.  To create a simple and advanced calculator Friday, August 07, 2015 Apollo 11 CalculatorModern GUI Calculator.

Maths Problem

There is a major problem with computing and this arises when it tries to divide

Decimal (base 10) Binary

0 0

1 1

2 10

3 11

4 100

5 101

6 110

7 111

8 1000

9 1001

10 1010

Computers store the numbers on silicon chips which can have a negative charge or not (i.e. 1 or 0) meaning computers do maths in base two (binary)

Problems arise when computers to and represent 0.1 in base 10 as a binary number (0.00011001100110011001100…)

It must always be rounded at some point

Page 22: Noadswood Science, 2014.  To create a simple and advanced calculator Friday, August 07, 2015 Apollo 11 CalculatorModern GUI Calculator.

Maths Problem

Take the division of two base 10 numbers

10 / 3

In binary this becomes 1010/11 = 11.010101010101…

At some point rounding is required else it will go on forever

However, if this is converted back to base 10 we get the following

3.33333333333333348136306995

Python will need to round…

Page 23: Noadswood Science, 2014.  To create a simple and advanced calculator Friday, August 07, 2015 Apollo 11 CalculatorModern GUI Calculator.

Maths Solution – Slicing

If you look at the code written in the simple calculator you will notice it to be the following: -

result = str(eval(display.get()))[0:10]

The [0:10] refers to a technique known as slicing where the answer produced goes to an acceptable number of decimal places

Page 24: Noadswood Science, 2014.  To create a simple and advanced calculator Friday, August 07, 2015 Apollo 11 CalculatorModern GUI Calculator.

Advanced Calculator

Open the Advanced Calculator (notice the script Advanced Calculator Functions)

This calculator is the sample as the Simple Calculator, however it contains a set off buttons for some constants…

Page 25: Noadswood Science, 2014.  To create a simple and advanced calculator Friday, August 07, 2015 Apollo 11 CalculatorModern GUI Calculator.

Constants

Buttons for constants can be added for set values which do not change

#Constants Frameconstants = Frame(window)constants.grid(row=3, column=0, sticky=W)constants_list = ['pi', 'speed of light (m/s)', 'speed of sound (m/s)', 'ave dist to sun (km)' ]#Constants Buttonsr = 1c = 1for btn_text in constants_list: def cmd(x=btn_text): click(x) Button(constants, text=btn_text, width=22,

command=cmd).grid(row=r,column=c) r = r+1

Page 26: Noadswood Science, 2014.  To create a simple and advanced calculator Friday, August 07, 2015 Apollo 11 CalculatorModern GUI Calculator.

Functions

Buttons for functions can be added to apply a set function to the entered data

#Functions Framefunctions = Frame(window)functions.grid(row=3, column=1, sticky=E)functions_list = ['factorial (!)', '-> roman', '-> binary', 'binary -> 10' ]#Functions Buttonsr = 1c = 1for btn_text in functions_list: def cmd(x=btn_text): click(x) Button(functions, text=btn_text, width=13,

command=cmd).grid(row=r,column=c) r = r+1

Page 27: Noadswood Science, 2014.  To create a simple and advanced calculator Friday, August 07, 2015 Apollo 11 CalculatorModern GUI Calculator.

Attaching

The constants can now be attached to the buttons…

#Constants elif key == constants_list[0]: display.insert(END, "3.141592654") elif key == constants_list[1]: display.insert(END, "300000000") elif key == constants_list[2]: display.insert(END, "330") elif key == constants_list[3]: display.insert(END, "149597887.5")

Page 28: Noadswood Science, 2014.  To create a simple and advanced calculator Friday, August 07, 2015 Apollo 11 CalculatorModern GUI Calculator.

Attaching

Collecting information

if key == functions_list[0]: display.insert(END,

Advanced_Calculator_Functions.factorial(n)) elif key == functions_list[1]: display.insert(END,

Advanced_Calculator_Functions.to_roman(n)) elif key == functions_list[2]: display.insert(END,

Advanced_Calculator_Functions.to_binary(n)) else: display.insert(END,

Advanced_Calculator_Functions.from_binary(n))

Page 29: Noadswood Science, 2014.  To create a simple and advanced calculator Friday, August 07, 2015 Apollo 11 CalculatorModern GUI Calculator.

Module

The functions could quite easily be written into the code, however Python allows modules to be imported…

The functions have been saved as Advanced_Calculator_Functions.py

To import the module it is called using: -

import Advanced_Calculator_Functions

Page 30: Noadswood Science, 2014.  To create a simple and advanced calculator Friday, August 07, 2015 Apollo 11 CalculatorModern GUI Calculator.

*Maths

A variety of other functions can be added to the calculator if the ones used are not required…

x2 and √ are often used on calculators and can be added using the following ** operator

Squared…

def square(n): returns n**2

Square root…

def square_root(n): returns n**0.5

Page 31: Noadswood Science, 2014.  To create a simple and advanced calculator Friday, August 07, 2015 Apollo 11 CalculatorModern GUI Calculator.

*Maths – Factorial

Factorials multiply all the numbers from 1 to the chosen number

E.g. five factorial (5!) means 5x4x3x2x1 = 120

# Calculate the factorial of a numberdef factorial(n): try: n = int(n) except: return "--> Error!" # '0' is special: if n == 0: return 1 # back out if too large: if n > 40: return "--> Answer will not fit on screen!" #catch negative numbers: if n < 0: return "--> Error!" # apply factorial algorithm: ans=n # set initial value of answer before loop while n > 1: ans = ans*(n-1) n = n-1 return ans

Page 32: Noadswood Science, 2014.  To create a simple and advanced calculator Friday, August 07, 2015 Apollo 11 CalculatorModern GUI Calculator.

*Maths – Roman Numerals A tuple stores the set of numbers (1000, 900, 500 etc…)

and a dictionary stores which letter(s) they correspond to

# Convert number to roman numeralsdef to_roman(n): try: n = int(n) except: return "--> Error!" # opt out of numbers greater than 4999 if n > 4999: return "--> out of range" # create the tuple and the dictionary numberBreaks = (1000,900,500,400,100,90,50,40,10,9,5,4,1) letters = {1000 : "M", 900 : "CM", 500 : "D", 400 : "CD", 100 : "C", 90 : "XC", 50 : "L", 40 : "XL",10 : "X", 9 :

"IX", 5 : "V", 4 : "IV",1 : "I" } # start algorithm result = "" for value in numberBreaks: while n >= value: result = result+letters[value] n = n-value return result

Page 33: Noadswood Science, 2014.  To create a simple and advanced calculator Friday, August 07, 2015 Apollo 11 CalculatorModern GUI Calculator.

*Maths – Binary

Python has functions that can be used to convert from one base to another

# Convert base 10 numbers to binary functiondef to_binary(n): try: n = int(n) return bin(n)[2:] except: return "--> Error!"

Page 34: Noadswood Science, 2014.  To create a simple and advanced calculator Friday, August 07, 2015 Apollo 11 CalculatorModern GUI Calculator.

*Maths – Binary > Base 10 Python has functions that can be used to convert from one

base to another (so we have binary numbers back to base 10)

# Convert base 2 numbers to base 10 functiondef from_binary(n): try: return int(n, 2) except: return "--> Error!"


Recommended