20191113 Experiment 2 "Python Programming" Experiment Report

20191113 2019-2020-2 "Python Programming" Experiment 2 Report

Course: "Python Programming"
Class: 1911
Name: Lin Zixin
Student ID: 20191113
Experimental Teacher: Wang Zhiqiang
Experiment Date: April 12, 2020
Compulsory / Elective: Public Elective Course

1. Experimental content

  • Design and complete a complete application-calculator. contain:
    • Simple arithmetic
    • Modulus operation
    • Find a simple trigonometric function
    • Find the nth power of a number
    • Find the factorial of a number
    • Solve quadratic equations in one variable (in the complex domain)
    • Statistical operations (including summation, average, range, variance, standard deviation)
  • Practice basic grammar, decision sentences, loops, logical operations, etc.

2. Experimental process and results

Clear purpose

Refer to the advanced calculator in your hand and determine the functions included in the calculator according to your ability level.

  • Simple arithmetic

    The mixing difficulty factor is too large, and the current proficiency in knowledge does not support my programming.

  • Modulus operation

  • Find a simple trigonometric function

  • Find the nth power of a number

  • Find the factorial of a number

  • Solve quadratic equations in one variable (in the complex domain)

  • Statistical operations (including summation, average, range, variance, standard deviation)

Design ideas

Choose to edit various logical operations into functions, and finally assemble the entire computer framework.

Since the programmed program is expected to be slightly intelligent and have a good user experience, a prompt will be given when entering incorrect data, and the user will be able to re-enter rather than start from scratch. The use of while syntax is inevitable.

At the same time, related functions will be selected after running the calculator, and if statements are also commonly used.

  • Simple trigonometric operation

    The daily input is often based on angles. The Python algorithm requires a radian system. You need to first convert the input angle to a radian system and then calculate it.

  • Solve quadratic equations in one variable

    Solving unary quadratic equations in the complex number field involves solving unary quadratic equations in the real number field, but due to the different representations, the two should be distinguished.

  • Statistical operations

    In statistical operations, summation is used as the basis for averaging, and variance is used as the basis for standard deviation. Can be properly sorted in order to simplify the calculation.

Coding, debugging, running process

Simple arithmetic

  • In the original version, each operation was written as a function and then called within the framework of the calculator, but this caused code redundancy and was not necessary.
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):    # 除法运算,使用前需判断除数是否为0
    return a/b
  • The enhanced version improves the shortcomings of the primary version, but it still cannot give users a better experience. If you enter the wrong function number, you need to start from the initial interface.
def ari():
    print("1.二元加法运算\n2.二元减法运算\n3.二元乘法运算\n4.二元除法运算\n")
	temp = int(input("请依照所要使用的功能输入相应的数字序号:"))
    if temp == 1 or temp == 2 or temp == 3:
        x = float(input("请输入第一个操作数:"))
        y = float(input("请输入第二个操作数:"))
        if temp == 1:
        	print(x + y)
        elif temp == 2:
        	print(x - y)
        else:
        	print(x * y)
	elif temp == 4:
        x = float(input("请输入被除数:"))
        y = float(input("请输入除数:"))
        while y == 0:
        	print("输入错误!除数不能为0!")
            y = float(input("请重新输入除数:"))
        print(x / y)  
  • In the final version, a while loop is added to solve the problem if the corresponding function number entered is incorrect.
def ari():
    '''四则运算'''
    print("1.二元加法运算\n2.二元减法运算\n3.二元乘法运算\n4.二元除法运算\n")
    temp = 233
    while temp != 1 and temp != 2 and temp != 3 and temp != 4:
        temp = int(input("请依照所要使用的功能输入相应的数字序号:"))
        if temp == 1 or temp == 2 or temp == 3:
            x = float(input("请输入第一个操作数:"))
            y = float(input("请输入第二个操作数:"))
            if temp == 1:
                print(x + y)
            elif temp == 2:
                print(x - y)
            else:
                print(x * y)
        elif temp == 4:
            x = float(input("请输入被除数:"))
            y = float(input("请输入除数:"))
            while y == 0:
                print("输入错误!除数不能为0!")
                y = float(input("请重新输入除数:"))
            print(x / y)
        else:
            print("相应功能数字序号输入有误!")
            print("1.二元加法运算\n2.二元减法运算\n3.二元乘法运算\n4.二元除法运算\n")
  • Run result display

Modulus operation

  • After learning the lessons of the four operations, and the simple operation, it is easy to compile.
def mol():
    '''取模运算'''
    x = int(input("请输入整数被除数:"))
    y = int(input("请输入整数除数:"))
    while y == 0:
        print("输入错误!除数不能为0!")
        y = int(input("请重新输入整数除数:"))
    print(x % y)
  • Run result display

Find a simple trigonometric function

  • Divide the six kinds of operations into two types. First, take sin and asin as examples, type out simple code, and perform operation and debugging.
import math
x = float(input("请以角度制输入角度:"))
x = x/180 * math.pi
print(math.sin(x))
x = float(input("请输入相应数值:"))
print('%.2f' % math.degrees(math.asin(x)))
  • Assemble with the relevant codes of sin and asin as templates, and finally fill in similar simple arithmetic operations.
def act():
    '''求简单三角函数'''
    print("\n1.求正弦\n2.求余弦\n3.求正切\n4.求反正弦\n5.求反余弦\n6.求反正切")
    temp = 233
    while temp != '1' and temp != '2' and temp != '3' and temp != '4' and temp != '5' and temp != '6':
        temp = input("请依照所要使用的功能输入相应的数字序号:")
        if temp == '1' or temp == '2' or temp == '3':
            x = float(input("请以角度制输入角度:"))
            x = x / 180 * math.pi
            if temp == '1':
                print('%.2f' %math.sin(x))
            elif temp == '2':
                print('%.2f' %math.cos(x))
            elif temp == '3':
                print('%.2f' %math.tan(x))
        elif temp == '4' or temp == '5' or temp == '6':
            x = float(input("请输入相应数值,答案将以角度制呈现:"))
            if temp == '4':
                if -1 <= x and x <= 1:
                    print('%.2f' % math.degrees(math.asin(x)))
                else:
                    print("无解!")
            elif temp == '5':
                x = float(input("请输入相应数值(-1≤x≤1):"))
                if -1 <= x and x <= 1:
                    print('%.2f' % math.degrees(math.acos(x)))
                else:
                    print("无解!")
            elif temp == '6':
                x = float(input("请输入相应数值:"))
                print('%.2f' % math.degrees(math.atan(x)))
        else:
            print("相应功能数字序号输入有误!")
  • Run result display

Find the nth power of a number

  • The code is as simple as the modulus operation, and no obstacles are encountered in the encoding process.
def nqo():
    '''求一个数的n次方'''
    a = float(input("请输入底数:"))
    while a == 0:
        print("输入错误!底数不能为0!")
        a = int(input("请重新输入底数:"))
    n = float(input("请输入指数:"))
    print(math.pow(a,n))
  • Run result display

Find the factorial of a number

  • I didn't know that there was a relevant factorial function at the beginning. I coded it as follows.
def fac(n):     # 阶乘运算
    t = 1
    for i in range(1,n+1):
        t = t * i
    return t
  • It is found that the functions in the math library are many and practical, and the factorial operation is re-encoded.
def fac():
    '''求一个数的阶乘 '''
    n = int(input("请输入一个整数:"))
    print(math.factorial(n))
  • Run result display

Solve quadratic equations in one variable

  • Solving the quadratic equation of one variable outputs different values ​​due to different situations. The return value statement is used here. It was originally intended to use the output statement in the calculation framework, but unexpectedly found that the return value can be output directly. Therefore, format the return result in the return value row.
def qua():
    '''解一元二次方程'''
    print('*' * 7 + "解一元二次方程 ax^2 + bx + c = 0" + '*' * 7)
    a = float(input("请输入a:"))
    b = float(input("请输入b:"))
    c = float(input("请输入c:"))
    d = b*b - 4*a*c
    if d>=0:
        x1 = (-b+math.sqrt(d)) / (2*a)
        x2 = (-b-math.sqrt(d)) / (2*a)
        if d==0:
            return "有唯一的解:X = "+str(x1)
        else:
            return "X1 = "+str(x1)+'\t'+"X2 = "+str(x2)
    else:
        x1 = str(-b/(2*a)) + '+' + str(math.sqrt(-d)/(2*a)) + 'i'
        x2 = str(-b/(2*a)) + '-' + str(math.sqrt(-d)/(2*a)) + 'i'
        return "X1 = "+x1+'\t'+"X2 = "+x2
  • Run result display

Statistical operations

  • To store data, a list is used, and to calculate data, a for loop is used.
x = int(input("输入数据个数:"))
y = []
print("请输入数据:")
for i in range(x):
    temp = [float(input())]
    y += temp
  • Code the code according to the previously analyzed ideas, and combine the relevant prompt statements and loop structure that need to be coded.
def sta():
    '''统计运算'''
    x = int(input("输入数据个数:"))
    y = []
    print("请输入数据:")
    for i in range(x):
        temp = [float(input())]
        y += temp
    print("\n1.求和\n2.求平均值\n3.求极差\n4.求方差\n5.求标准差")
    temp = 233
    while temp != '1' and temp != '2' and temp != '3' and temp != '4' and temp != '5':
        temp = input("请依照所要使用的功能输入相应的数字序号:")
        s = 0
        for i in range(x):
            s = s + y[i]
        var = 0
        for i in range(x):
            var = var + (s / x - y[i]) ** 2
        var = var / x
        if temp == '1':
            print(s)
        elif temp == '2':
            print(s / x)
        elif temp == '3':
            print(max(y) - min(y))
        elif temp == '4':
            print(var)
        elif temp == '5':
            print(math.sqrt(var))
        else:
            print("相应功能数字序号输入有误!")

  • Run result display

Calculator frame coding

  • Assemble the above functions and add related prompt statements. To loop, add a while statement, and use "-1" as the program end mark.
#计算机功能框架
print('*'*5+"欢迎使用计算器!"+'*'*5)
print("本计算器提供的功能有:")
print("1.简单二元四则运算")
print("2.取模运算")
print("3.求简单三角函数")
print("4.求一个数的n次方")
print("5.求一个数的阶乘")
print("6.解一元二次方程")
print("7.统计运算")
print("-1.退出程序")
t = 233

while t!='-1':
    t = input("\n请依照所要使用的功能输入相应的数字序号:")
    if t=='1':
        ari()
    elif t=='2':
        mol()
    elif t=='3':
        act()
    elif t=='4':
        nqo()
    elif t=='5':
        fac()
    elif t=='6':
        print(qua())
    elif t=='7':
        sta()
    elif t=='-1':
        exit(0)
    else:
        print("相应功能数字序号输入有误!")

    print("\n是否再次计算?")
    print("本计算器提供的功能有:")
    print("1.二元四则运算")
    print("2.取模运算")
    print("3.求简单三角函数")
    print("4.求一个数的n次方")
    print("5.求一个数的阶乘")
    print("6.解一元二次方程")
    print("7.统计运算")
    print("-1.退出程序")
  • Run result display
    • cycle
    • termination

Complete code display-code cloud address

3. Problems encountered during the experiment and the resolution process

  • Question 1: I am not familiar with the usage of math.degrees , which leads to wrong use.

    Solution to Problem 1: Check the relevant information and learn the usage of this function: convert from radian system to angle system. To change the angle system to the radian system, x = x / 180 * math.pi

  • Question 2: When writing simple trigonometric function code, the format of the answer displayed is not beautiful enough; at the same time, some answers of the anti-trigonometric function class are incorrect.

    Solution for Problem 2: Format the answer, and add the size limit of the input value to the input prompt statement. At the same time, if the input value is not within the provided range, output "No solution!".

  • Question 3: If the calculator loop structure wants to terminate, it will always output information such as "Do you want to run again ..." that you do not want to output.

  • Solution for Problem 3: Join in the structural framework

        elif t=='-1':
            exit(0)
    

Others (sentiment, thinking, etc.)

  • Coding code is a particularly effective method of learning. The application makes all the knowledge that is dead on paper fresh and makes learning more sense.
  • The design of each program requires continuous testing and improvement. Even if it is just a small calculator program, there are many things to consider and need to be involved.
  • Before each programming, a specific description and design of the purpose and ideas should be carried out, so as to ensure the smooth and relatively efficient programming.

References

Guess you like

Origin www.cnblogs.com/Lzix/p/12683945.html