A Science Calculator Based on Python

832102122 林陶然 2023-10-08 19:35:11

I.Introduction

This blog introduces a calcultator with a visual interface, which is completed with python.

The Link to My Classhttps://bbs.csdn.net/forums/ssynkqtd-04
The Link of Requirement of This Assignmenthttps://bbs.csdn.net/topics/617332156
The Aim of This AssignmentTo create a science calculator with visual interface
MU STU ID and FZU STU ID21124710(MU) / 832102122(FZU)
Link to github: https://github.com/Arthurhim/EE308/tree/main/Assignment1_Calculator

The calcutator has gone through iterations and has two versions, including:

V1.0: Simple Calculator

This version realises the basic fuctions required by a calculator, including addition, substraction, multiplication,
division and clear fuction (which inculdes clearing the lable to show the result as well as deleting only the last
digit).

img

V2.0: Science Calculator

On the basis of the first version, this version adds more functions to its interface, among which are:

1. Triangular functions(sin cos and tan, both in degree and radian modes)
2. Logarithmic fuctions(log and ln)
3. exponential function
4. other special symbols & functions(π and e, squareroot and factorial)
5. inverse functions of 1. and 2.

img

——non-inverse version

img

——inverse version

II.Project process

PSP form

Personal Software Process StagesEstimated Time(minutes)Actual Time(minutes)
Planning2030
• Estimate1520
Development1010
• Analysis1520
• Design Spec4040
• Design Review1010
• Coding Standard1520
• Design2020
• Coding300350
• Code Review1520
• Test1515
Reporting2015
• Test Report1010
• Size Measurement1010
• Postmortem & Process Improvement Plan3030
Sum545620

Design ideas

-Prototype

A calculator basically includes two parts: a user interface and a logic process unit. The former allows user to interact with it,
and the latter calculates and return the result to screen, so as to finish a logic cycle of it.

Based on these thoughts, the first prototype is created. It has a result label to show calculating procedure and results, and
buttons for user to type numbers and operators on the label as well as get result from it.

-Improvement

As the first prototype(presented as calculator V1.0) is finished, more functions can be added in. This includes trangular
functions, exponential and logarithmic functions, factorial function and some special symbols. To make it easier to use,
buttons "rad" and "deg" are added in so that user can use the trangular functions in the mode he want(radius or degree).
Finally, inverse function is also added to the calculator. The last two fuctions(rad & deg fuction, inverse fuction) are designed
to support "memory": For example, if user chose degree mode and inv mode before he close the calculator, it will rememer
these choices and remain itself in these modes the next time it is opened.

Error throw-out

Consider that sometime user failed to enter the complete content before he presses the "=" function to get the result, to let user
realize this, once it happens, a "error" information is designed to appear on the result label.

Flow chart -- how the calculator works:

img

III.Code

V1.0 Simple Calculator

import tkinter as tk

root = tk.Tk()
root.title('Calculator v1.0')
root.geometry('269x260+700+400')

root.attributes("-alpha", 0.9)
root["background"] = "#ffffff"

font_result = ('楷体', 21)
font_key = ('楷体', 15)

# 初始化变量
result_num = tk.StringVar()
result_num.set('0')
calculate_done = False
#

interface initialization and global variables declaring

#
button_clear = tk.Button(root, text="CE", width=5, font=font_key, relief=tk.FLAT, bg='#b1b2b2')
button_back = tk.Button(root, text="←", width=5, font=font_key, relief=tk.FLAT, bg='#b1b2b2')
button_division = tk.Button(root, text="÷", width=5, font=font_key, relief=tk.FLAT, bg='#b1b2b2')
button_multiplication = tk.Button(root, text="×", width=5, font=font_key, relief=tk.FLAT, bg='#b1b2b2')

button_clear.grid(row=2, column=1, padx=3, pady=2)
button_back.grid(row=2, column=2, padx=3, pady=2)
button_division.grid(row=2, column=3, padx=3, pady=2)
button_multiplication.grid(row=2, column=4, padx=3, pady=2)
# 按钮第一行

#
button_seven = tk.Button(root, text="7", width=5, font=font_key, relief=tk.FLAT, bg='#eacda1')
button_eight = tk.Button(root, text="8", width=5, font=font_key, relief=tk.FLAT, bg='#eacda1')
button_nine = tk.Button(root, text="9", width=5, font=font_key, relief=tk.FLAT, bg='#eacda1')
button_subtraction = tk.Button(root, text="-", width=5, font=font_key, relief=tk.FLAT, bg='#b1b2b2')

button_seven.grid(row=3, column=1, padx=3, pady=2)
button_eight.grid(row=3, column=2, padx=3, pady=2)
button_nine.grid(row=3, column=3, padx=3, pady=2)
button_subtraction.grid(row=3, column=4, padx=3, pady=2)
# 按钮第二行

#
button_four = tk.Button(root, text="4", width=5, font=font_key, relief=tk.FLAT, bg='#eacda1')
button_five = tk.Button(root, text="5", width=5, font=font_key, relief=tk.FLAT, bg='#eacda1')
button_six = tk.Button(root, text="6", width=5, font=font_key, relief=tk.FLAT, bg='#eacda1')
button_addition = tk.Button(root, text="+", width=5, font=font_key, relief=tk.FLAT, bg='#b1b2b2')

button_four.grid(row=4, column=1, padx=3, pady=2)
button_five.grid(row=4, column=2, padx=3, pady=2)
button_six.grid(row=4, column=3, padx=3, pady=2)
button_addition.grid(row=4, column=4, padx=3, pady=2)
# 按钮第三行

#
button_one = tk.Button(root, text="1", width=5, font=font_key, relief=tk.FLAT, bg='#eacda1')
button_two = tk.Button(root, text="2", width=5, font=font_key, relief=tk.FLAT, bg='#eacda1')
button_three = tk.Button(root, text="3", width=5, font=font_key, relief=tk.FLAT, bg='#eacda1')

button_one.grid(row=5, column=1, padx=3, pady=2)
button_two.grid(row=5, column=2, padx=3, pady=2)
button_three.grid(row=5, column=3, padx=3, pady=2)
# 按钮第四行

#
button_zero = tk.Button(root, text="0", width=12, font=font_key, relief=tk.FLAT, bg='#eacda1')
button_dot = tk.Button(root, text=".", width=5, font=font_key, relief=tk.FLAT, bg='#eacda1')
button_equivalence = tk.Button(root, text="=", width=5, height=3, font=font_key, relief=tk.FLAT, bg='#b1b2b2')

button_zero.grid(row=6, column=1, padx=3, pady=2, columnspan=2)
button_dot.grid(row=6, column=3, padx=3, pady=2)
button_equivalence.grid(row=5, column=4, padx=3, pady=2, rowspan=2)

# "0" "."  "="

button initialization

def click_button(x):
    global calculate_done
    if result_num.get() == '0':
        result_num.set(x)
        calculate_done = False
    elif calculate_done:
        if not x.isdigit():
            result_num.set(result_num.get() + x)
        else:
            result_num.set(x)
        calculate_done = False
    else:
        result_num.set(result_num.get()+x)


def calculation():
    opt_str = result_num.get()
    result = eval(opt_str)
    result_num.set(str(result))
    global calculate_done
    calculate_done = True


def clear():
    result_num.set('0')


def back():
    global calculate_done

    result_num.set(result_num.get()[:-1])
    calculate_done = False


button_one.config(command=lambda: click_button('1'))
button_two.config(command=lambda: click_button('2'))
button_three.config(command=lambda: click_button('3'))
button_four.config(command=lambda: click_button('4'))
button_five.config(command=lambda: click_button('5'))
button_six.config(command=lambda: click_button('6'))
button_seven.config(command=lambda: click_button('7'))
button_eight.config(command=lambda: click_button('8'))
button_nine.config(command=lambda: click_button('9'))
button_zero.config(command=lambda: click_button('0'))

button_addition.config(command=lambda: click_button('+'))
button_subtraction.config(command=lambda: click_button('-'))
button_multiplication.config(command=lambda: click_button('*'))
button_division.config(command=lambda: click_button('/'))


button_clear.config(command=clear)
button_equivalence.config(command=calculation)
button_back.config(command=back)
button_dot.config(command=lambda: click_button('.'))

root.mainloop()

logic unit

V2.0 Science Calculator

import re
import tkinter as tk
import math

root = tk.Tk()
root.title('Calculator v2.0')
root.geometry('380x336+700+400')

root.attributes("-alpha", 0.9)
root["background"] = "#ffffff"

font_result = ('楷体', 21)
font_key = ('楷体', 15)

# 初始化变量
result_num = tk.StringVar()
result_num.set('0')
calculate_done = False
#

interface initialization

tk.Label(root,
         textvariable=result_num, font=font_result, height=2,
         width=26, justify=tk.LEFT, anchor=tk.SE
         ).grid(row=1, column=1, columnspan=5)
#
button_sin = tk.Button(root, text="sin", width=6, font=font_key, relief=tk.FLAT, bg='#eacda1')
button_cos = tk.Button(root, text="cos", width=6, font=font_key, relief=tk.FLAT, bg='#eacda1')
button_tan = tk.Button(root, text="tan", width=6, font=font_key, relief=tk.FLAT, bg='#eacda1')
button_rad = tk.Button(root, text="rad", width=6, font=font_key, relief=tk.FLAT, bg='#eacda1')
button_deg = tk.Button(root, text="deg", width=6, font=font_key, relief=tk.FLAT, bg='#eacda1')


button_sin.grid(row=2, column=1, padx=3, pady=2)
button_cos.grid(row=2, column=2, padx=3, pady=2)
button_tan.grid(row=2, column=3, padx=3, pady=2)
button_rad.grid(row=2, column=4, padx=3, pady=2)
button_deg.grid(row=2, column=5, padx=3, pady=2)

# 按钮第一行

#
button_log = tk.Button(root, text="log", width=6, font=font_key, relief=tk.FLAT, bg='#eacda1')
button_ln = tk.Button(root, text="ln", width=6, font=font_key, relief=tk.FLAT, bg='#eacda1')
button_left_bracket = tk.Button(root, text="(", width=6, font=font_key, relief=tk.FLAT, bg='#eacda1')
button_right_bracket = tk.Button(root, text=")", width=6, font=font_key, relief=tk.FLAT, bg='#eacda1')
button_inv = tk.Button(root, text="inv", width=6, font=font_key, relief=tk.FLAT, bg='#eacda1')


button_log.grid(row=3, column=1, padx=3, pady=2)
button_ln.grid(row=3, column=2, padx=3, pady=2)
button_left_bracket.grid(row=3, column=3, padx=3, pady=2)
button_right_bracket.grid(row=3, column=4, padx=3, pady=2)
button_inv.grid(row=3, column=5, padx=3, pady=2)

# 按钮第二行

#
button_factorial = tk.Button(root, text="!", width=6, font=font_key, relief=tk.FLAT, bg='#eacda1')
button_clear = tk.Button(root, text="C", width=6, font=font_key, relief=tk.FLAT, bg='#b1b2b2')
button_percent = tk.Button(root, text="%", width=6, font=font_key, relief=tk.FLAT, bg='#b1b2b2')
button_back = tk.Button(root, text="←", width=6, font=font_key, relief=tk.FLAT, bg='#b1b2b2')
button_division = tk.Button(root, text="÷", width=6, font=font_key, relief=tk.FLAT, bg='#b1b2b2')


button_factorial.grid(row=4, column=1, padx=3, pady=2)
button_clear.grid(row=4, column=2, padx=3, pady=2)
button_percent.grid(row=4, column=3, padx=3, pady=2)
button_back.grid(row=4, column=4, padx=3, pady=2)
button_division.grid(row=4, column=5, padx=3, pady=2)

# 按钮第三行

#
button_power = tk.Button(root, text="^", width=6, font=font_key, relief=tk.FLAT, bg='#eacda1')
button_seven = tk.Button(root, text="7", width=6, font=font_key, relief=tk.FLAT, bg='#eacda1')
button_eight = tk.Button(root, text="8", width=6, font=font_key, relief=tk.FLAT, bg='#eacda1')
button_nine = tk.Button(root, text="9", width=6, font=font_key, relief=tk.FLAT, bg='#eacda1')
button_multiplication = tk.Button(root, text="×", width=6, font=font_key, relief=tk.FLAT, bg='#b1b2b2')


button_power.grid(row=5, column=1, padx=3, pady=2)
button_seven.grid(row=5, column=2, padx=3, pady=2)
button_eight.grid(row=5, column=3, padx=3, pady=2)
button_nine.grid(row=5, column=4, padx=3, pady=2)
button_multiplication.grid(row=5, column=5, padx=3, pady=2)

# 按钮第四行

#
button_square_root = tk.Button(root, text="√ ̄", width=6, font=font_key, relief=tk.FLAT, bg='#eacda1')
button_four = tk.Button(root, text="4", width=6, font=font_key, relief=tk.FLAT, bg='#eacda1')
button_five = tk.Button(root, text="5", width=6, font=font_key, relief=tk.FLAT, bg='#eacda1')
button_six = tk.Button(root, text="6", width=6, font=font_key, relief=tk.FLAT, bg='#eacda1')
button_subtraction = tk.Button(root, text="-", width=6, font=font_key, relief=tk.FLAT, bg='#b1b2b2')


button_square_root.grid(row=6, column=1, padx=3, pady=2)
button_four.grid(row=6, column=2, padx=3, pady=2)
button_five.grid(row=6, column=3, padx=3, pady=2)
button_six.grid(row=6, column=4, padx=3, pady=2)
button_subtraction.grid(row=6, column=5, padx=3, pady=2)
# 按钮第五行

#
button_pi = tk.Button(root, text="π", width=6, font=font_key, relief=tk.FLAT, bg='#eacda1')
button_one = tk.Button(root, text="1", width=6, font=font_key, relief=tk.FLAT, bg='#eacda1')
button_two = tk.Button(root, text="2", width=6, font=font_key, relief=tk.FLAT, bg='#eacda1')
button_three = tk.Button(root, text="3", width=6, font=font_key, relief=tk.FLAT, bg='#eacda1')
button_addition = tk.Button(root, text="+", width=6, font=font_key, relief=tk.FLAT, bg='#b1b2b2')


button_pi.grid(row=7, column=1, padx=3, pady=2)
button_one.grid(row=7, column=2, padx=3, pady=2)
button_two.grid(row=7, column=3, padx=3, pady=2)
button_three.grid(row=7, column=4, padx=3, pady=2)
button_addition.grid(row=7, column=5, padx=3, pady=2)
# 按钮第六行

#
button_e = tk.Button(root, text="e", width=6, font=font_key, relief=tk.FLAT, bg='#eacda1')
button_D_zero = tk.Button(root, text="00", width=6, font=font_key, relief=tk.FLAT, bg='#eacda1')
button_zero = tk.Button(root, text="0", width=6, font=font_key, relief=tk.FLAT, bg='#eacda1')
button_dot = tk.Button(root, text=".", width=6, font=font_key, relief=tk.FLAT, bg='#eacda1')
button_equivalence = tk.Button(root, text="=", width=6, font=font_key, relief=tk.FLAT, bg='#faa755')


button_e.grid(row=8, column=1, padx=3, pady=2)
button_D_zero.grid(row=8, column=2, padx=3, pady=2)
button_zero.grid(row=8, column=3, padx=3, pady=2)
button_dot.grid(row=8, column=4, padx=3, pady=2)
button_equivalence.grid(row=8, column=5, padx=3, pady=2)

button initialization

with open('rad_deg.txt', 'a+') as File:
    File.seek(0)
    content = File.read()
    if content == "":
        content = "deg"
    if content == "deg":
        button_deg.config(fg="red")
    if content == "rad":
        button_rad.config(fg="red")
    File.close()

with open('inv_config.txt', 'a+') as File:
    File.seek(0)
    mode = File.read()
    if mode == "":
        mode = "1"
    if mode == "-1":
        button_inv.config(fg="red")
        button_sin.config(text="sin⁻¹")
        button_cos.config(text="cos⁻¹")
        button_tan.config(text="tan⁻¹")
        button_ln.config(text="e^")
        button_log.config(text="10^")
        button_square_root.config(text="x²")
    File.close()


def click_button(x):
    global calculate_done
    if result_num.get() == '0':
        result_num.set(x)
        calculate_done = False
    elif calculate_done:
        if x == '+' or x == "-" or x == "*" or x == "/":
            result_num.set(result_num.get() + x)
        else:
            result_num.set(x)
        calculate_done = False
    else:
        result_num.set(result_num.get()+x)


def calculation():
    opt_str = result_num.get()

    if content == "rad":
        # 正函数
        opt_str = opt_str.replace("sin(", "math.sin(")
        opt_str = opt_str.replace("cos(", "math.cos(")
        opt_str = opt_str.replace("tan(", "math.tan(")
        # 反函数
        opt_str = opt_str.replace("sin⁻¹(", "math.asin(")
        opt_str = opt_str.replace("cos⁻¹(", "math.acos(")
        opt_str = opt_str.replace("tan⁻¹(", "math.atan(")
    elif content == "deg":
        # 正函数
        opt_str = opt_str.replace("sin(", "math.sin(math.pi * (1/180) * ")
        opt_str = opt_str.replace("cos(", "math.cos(math.pi * (1/180) * ")
        opt_str = opt_str.replace("tan(", "math.tan(math.pi * (1/180) * ")
        # 反函数
        opt_str = opt_str.replace("sin⁻¹(", "math.asin(math.pi * (1/180) * ")
        opt_str = opt_str.replace("cos⁻¹(", "math.acos(math.pi * (1/180) * ")
        opt_str = opt_str.replace("tan⁻¹(", "math.atan(math.pi * (1/180) * ")

    opt_str = opt_str.replace("log(", "math.log10(")
    opt_str = opt_str.replace("ln(", "math.log(")

    opt_str = opt_str.replace("×", "*")
    opt_str = opt_str.replace("÷", "/")
    opt_str = opt_str.replace("^", "**")
    opt_str = opt_str.replace("%", "*0.01")

    opt_str = opt_str.replace("π", "math.pi")
    opt_str = opt_str.replace("e", "math.e")

    opt_str = factorial(opt_str)
    opt_str = square_root(opt_str)
    # print(opt_str)  # debug

    try:
        result = eval(opt_str)
        result_num.set(str(round(result, 14)))  # 去掉最后一位,以纠正浮点型误差
    except Exception as e:
        result_num.set("error")

    global calculate_done  # 标记计算完毕(若下一次计算开始,则清屏)
    calculate_done = True


def change_tri_mode(s):
    global content
    with open('rad_deg.txt', 'a+')as file:
        file.seek(0)
        file.truncate(0)
        if s == "rad":
            content = "rad"
            file.write("rad")
            button_rad.config(fg="red")
            button_deg.config(fg="black")
        elif s == "deg":
            content = "deg"
            file.write("deg")
            button_rad.config(fg="black")
            button_deg.config(fg="red")
        file.close()


def change_inv_mode():
    global mode
    with open('inv_config.txt', 'a+')as file:
        file.seek(0)
        file.truncate(0)
        if mode == "1":
            mode = "-1"
            file.write("-1")
            button_inv.config(fg="red")
            button_sin.config(text="sin⁻¹", command=lambda: click_button('sin⁻¹('))
            button_cos.config(text="cos⁻¹", command=lambda: click_button('cos⁻¹('))
            button_tan.config(text="tan⁻¹", command=lambda: click_button('tan⁻¹('))
            button_ln.config(text="e^", command=lambda: click_button('e^'))
            button_log.config(text="10^", command=lambda: click_button('10^'))
            button_square_root.config(text="x²", command=lambda: click_button('^2'))
        elif mode == "-1":
            mode = "1"
            file.write("1")
            button_inv.config(fg="black")
            button_sin.config(text="sin", command=lambda: click_button('sin('))
            button_cos.config(text="cos", command=lambda: click_button('cos('))
            button_tan.config(text="tan", command=lambda: click_button('tan('))
            button_ln.config(text="ln", command=lambda: click_button('ln('))
            button_log.config(text="log", command=lambda: click_button('log('))
            button_square_root.config(text="√ ̄", command=lambda: click_button('√'))
        file.close()


def factorial(s):
    count_fac = s.count("!")
    if count_fac == 0:
        return s

    pattern = r'\b\d+!?\b'
    matches = re.findall(pattern, s)
    for match in matches:
        num = int(match)
        num = math.factorial(num)
        s = s.replace(match+"!", str(num), 1)
    return s


def square_root(s):
    count_squ = s.count("√")
    if count_squ == 0:
        return s

    pattern = r'\b\√?+\d\b'
    matches = re.findall(pattern, s)
    for match in matches:
        num = int(match)
        num = math.sqrt(num)
        s = s.replace("√" + match, str(num), 1)
    return s


def clear():
    result_num.set('0')


def back():
    global calculate_done

    result_num.set(result_num.get()[:-1])
    calculate_done = False


button_one.config(command=lambda: click_button('1'))
button_two.config(command=lambda: click_button('2'))
button_three.config(command=lambda: click_button('3'))
button_four.config(command=lambda: click_button('4'))
button_five.config(command=lambda: click_button('5'))
button_six.config(command=lambda: click_button('6'))
button_seven.config(command=lambda: click_button('7'))
button_eight.config(command=lambda: click_button('8'))
button_nine.config(command=lambda: click_button('9'))
button_zero.config(command=lambda: click_button('0'))
button_D_zero.config(command=lambda: click_button('00'))
button_pi.config(command=lambda: click_button('π'))
button_e.config(command=lambda: click_button('e'))

button_addition.config(command=lambda: click_button('+'))
button_subtraction.config(command=lambda: click_button('-'))
button_multiplication.config(command=lambda: click_button('×'))
button_division.config(command=lambda: click_button('÷'))
button_power.config(command=lambda: click_button('^'))
button_square_root.config(command=lambda: click_button('√'))
button_factorial.config(command=lambda: click_button('!'))

button_sin.config(command=lambda: click_button('sin('))
button_cos.config(command=lambda: click_button('cos('))
button_tan.config(command=lambda: click_button('tan('))
button_rad.config(command=lambda: change_tri_mode("rad"))
button_deg.config(command=lambda: change_tri_mode("deg"))

button_log.config(command=lambda: click_button('log('))
button_ln.config(command=lambda: click_button('ln('))

if mode == "-1":
    button_sin.config(command=lambda: click_button('sin⁻¹('))
    button_cos.config(command=lambda: click_button('cos⁻¹('))
    button_tan.config(command=lambda: click_button('tan⁻¹('))
    button_log.config(command=lambda: click_button('10^'))
    button_ln.config(command=lambda: click_button('e^'))
    button_square_root.config(command=lambda: click_button('^2'))

button_left_bracket.config(command=lambda: click_button('('))
button_right_bracket.config(command=lambda: click_button(')'))
button_dot.config(command=lambda: click_button('.'))
button_percent.config(command=lambda: click_button('%'))


button_inv.config(command=change_inv_mode)
button_clear.config(command=clear)
button_equivalence.config(command=calculation)
button_back.config(command=back)

root.mainloop()

logic unit

IV.Result display

V1.0 Simple Calculator:

img

V2.0 Science Calculator:

img

Triangular functions

img

log and ln

img

Exponential and square root functions

img

Other functions

V.Summary

In this Assignment I learnt how to make use of a previous learned programming language(python is chosen for this project)
to develop a software. Also during this preocess, I've took the procedure to develop a software with the steps given in class:
designing, coding, improving and debugging.

...全文
961 回复 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复
1 Computers and Programs 1 1.1 The Universal Machine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.2 Program Power . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 1.3 What is Computer Science? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 1.4 Hardware Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 1.5 Programming Languages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.6 The Magic of Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.7 Inside a Python Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 1.8 Chaos and Computers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 1.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 2 Writing Simple Programs 13 2.1 The Software Development Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 2.2 Example Program: Temperature Converter . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 2.3 Elements of Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 2.3.1 Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 2.3.2 Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 2.4 Output Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 2.5 Assignment Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 2.5.1 Simple Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 2.5.2 Assigning Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 2.5.3 Simultaneous Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 2.6 Definite Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 2.7 Example Program: Future Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 2.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 3 Computing with Numbers 25 3.1 Numeric Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 3.2 Using the Math Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 3.3 Accumulating Results: Factorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 3.4 The Limits of Int . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 3.5 Handling Large Numbers: Long Ints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 3.6 Type Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 3.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 4 Computing with Strings 39 4.1 The String Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 4.2 Simple String Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 4.3 Strings and Secret Codes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 4.3.1 String Representation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 4.3.2 Programming an Encoder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 4.3.3 Programming a Decoder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 4.3.4 Other String Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 i ii CONTENTS 4.3.5 From Encoding to Encryption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 4.4 Output as String Manipulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 4.4.1 Converting Numbers to Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 4.4.2 String Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 4.4.3 Better Change Counter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 4.5 File Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 4.5.1 Multi-Line Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 4.5.2 File Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 4.5.3 Example Program: Batch Usernames . . . . . . . . . . . . . . . . . . . . . . . . . 55 4.5.4 Coming Attraction: Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 4.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 5 Objects and Graphics 61 5.1 The Object of Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 5.2 Graphics Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 5.3 Using Graphical Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 5.4 Graphing Future Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 5.5 Choosing Coordinates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 5.6 Interactive Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 5.6.1 Getting Mouse Clicks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 5.6.2 Handling Textual Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76 5.7 Graphics Module Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 5.7.1 GraphWin Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 5.7.2 Graphics Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 5.7.3 Entry Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 5.7.4 Displaying Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 5.7.5 Generating Colors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 5.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82 6 Defining Functions 85 6.1 The Function of Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 6.2 Functions, Informally . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 6.3 Future Value with a Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 6.4 Functions and Parameters: The Gory Details . . . . . . . . . . . . . . . . . . . . . . . . . . 90 6.5 Functions that Return Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 6.6 Functions and Program Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 6.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 7 Control Structures, Part 1 101 7.1 Simple Decisions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 7.1.1 Example: TemperatureWarnings . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 7.1.2 Forming Simple Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 7.1.3 Example: Conditional Program Execution . . . . . . . . . . . . . . . . . . . . . . . 104 7.2 Two-Way Decisions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 7.3 Multi-Way Decisions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 7.4 Exception Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 7.5 Study in Design: Max of Three . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 7.5.1 Strategy 1: Compare Each to All . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 7.5.2 Strategy 2: Decision Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 7.5.3 Strategy 3: Sequential Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . 114 7.5.4 Strategy 4: Use Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 7.5.5 Some Lessons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 7.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 CONTENTS iii 8 Control Structures, Part 2 119 8.1 For Loops: A Quick Review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 8.2 Indefinite Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 8.3 Common Loop Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 8.3.1 Interactive Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 8.3.2 Sentinel Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 8.3.3 File Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 8.3.4 Nested Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126 8.4 Computing with Booleans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 8.4.1 Boolean Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 8.4.2 Boolean Algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 8.5 Other Common Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 8.5.1 Post-Test Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 8.5.2 Loop and a Half . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 8.5.3 Boolean Expressions as Decisions . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 8.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134 9 Simulation and Design 137 9.1 Simulating Racquetball . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 9.1.1 A Simulation Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 9.1.2 Program Specification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138 9.2 Random Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138 9.3 Top-Down Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140 9.3.1 Top-Level Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140 9.3.2 Separation of Concerns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 9.3.3 Second-Level Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142 9.3.4 Designing simNGames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 9.3.5 Third-Level Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144 9.3.6 Finishing Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146 9.3.7 Summary of the Design Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148 9.4 Bottom-Up Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148 9.4.1 Unit Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148 9.4.2 Simulation Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 9.5 Other Design Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150 9.5.1 Prototyping and Spiral Development . . . . . . . . . . . . . . . . . . . . . . . . . . 150 9.5.2 The Art of Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151 9.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152 10 Defining Classes 155 10.1 Quick Review of Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155 10.2 Example Program: Cannonball . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156 10.2.1 Program Specification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156 10.2.2 Designing the Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156 10.2.3 Modularizing the Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 10.3 Defining New Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 10.3.1 Example: Multi-Sided Dice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160 10.3.2 Example: The Projectile Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162 10.4 Objects and Encapsulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164 10.4.1 Encapsulating Useful Abstractions . . . . . . . . . . . . . . . . . . . . . . . . . . . 164 10.4.2 Putting Classes in Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164 10.5 Widget Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166 10.5.1 Example Program: Dice Roller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166 10.5.2 Building Buttons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166 10.5.3 Building Dice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169 iv CONTENTS 10.5.4 The Main Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172 10.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173 11 Data Collections 177 11.1 Example Problem: Simple Statistics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177 11.2 Applying Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178 11.2.1 Lists are Sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178 11.2.2 Lists vs. Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179 11.2.3 List Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180 11.3 Statistics with Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181 11.4 Combining Lists and Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184 11.5 Case Study: Python Calculator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188 11.5.1 A Calculator as an Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188 11.5.2 Constructing the Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188 11.5.3 Processing Buttons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190 11.6 Non-Sequential Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193 11.6.1 Dictionary Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193 11.6.2 Dictionary Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194 11.6.3 Example Program: Word Frequency . . . . . . . . . . . . . . . . . . . . . . . . . . 194 11.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198 12 Object-Oriented Design 201 12.1 The Process of OOD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201 12.2 Case Study: Racquetball Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 12.2.1 Candidate Objects and Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203 12.2.2 Implementing SimStats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203 12.2.3 Implementing RBallGame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205 12.2.4 Implementing Player . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207 12.2.5 The Complete Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207 12.3 Case Study: Dice Poker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210 12.3.1 Program Specification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210 12.3.2 Identifying Candidate Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210 12.3.3 Implementing the Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211 12.3.4 A Text-Based UI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214 12.3.5 Developing a GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216 12.4 OO Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 12.4.1 Encapsulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 12.4.2 Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222 12.4.3 Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222 12.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223 13 Algorithm Analysis and Design 225 13.1 Searching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225 13.1.1 A Simple Searching Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225 13.1.2 Strategy 1: Linear Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226 13.1.3 Strategy 2: Binary Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226 13.1.4 Comparing Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227 13.2 Recursive Problem-Solving . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228 13.2.1 Recursive Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229 13.2.2 Recursive Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230 13.2.3 Recursive Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230 13.3 Sorting Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231 13.3.1 Naive Sorting: Selection Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231 13.3.2 Divide and Conquer: Merge Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232 CONTENTS v 13.3.3 Comparing Sorts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234 13.4 Hard Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235 13.4.1 Towers of Hanoi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236 13.4.2 The Halting Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239 13.4.3 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241

176

社区成员

发帖
与我相关
我的任务
社区描述
梅努斯软件工程
软件工程 高校 福建省·福州市
社区管理员
  • LinQF39
  • Jcandc
  • chjinhuu
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧