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

Course: "Python Programming"
Class: 1924
Name: Chen Hanwen
Student ID: 20192426
Experimental Teacher: Wang Zhiqiang
Experiment Date: April 16, 2020
Compulsory / Elective: Public Elective Course

1. Experimental content

  • Design and complete a complete application program, complete operations such as addition, subtraction, multiplication and division, and more functions.
  • Examine the knowledge points of basic grammar, judgment statements, loop statements, logical operations, etc.

2. Experimental process and results

experiment procedure:

First edition:

  1. First of all, I think that the calculator can directly calculate the result of the expression, and can continue to operate on the obtained result, so it is divided into two cases:

    • Perform new calculations

    • Continue to operate on the results obtained.

  2. Next, I use a while loop to allow the calculator to perform multiple calculations. In fact, the difference between the above two situations is not very big. When one situation is completed, the other situation is close to completion. So, I finished the first case .

Here I define the judgesymbol () function to determine whether the operation symbol input by the user is +-* /%

def judgesymbol(a):
    if a in ["+", "-", "*", "/", "%", "**"]:
        return 1
    else:
        print("\033[31m请重新输入运算符号!\033[0m")
        return 0

Define the judgezero () function to determine whether the divisor is 0

def judgezero(a):
    try:
        eval(a)
        return 1
    except ZeroDivisionError:
        print("\033[31m0不能作为除数!请重新输入!\033[0m")
        return 0

The main body of this part is as follows:

while True:	
   if i == 2:
      a = input("请输入第一个操作数:")
      s = input("请输入运算类型:")
      if judgesymbol(s) == 0:
          continue
      b = input("请输入第二个操作数:")
      sum = a+s+b
      if judgezero(sum) == 0:
          continue
      print(sum+"={:g}".format(eval(sum)))
      i = int(input("是否继续输入?(输入0结束,输入1对得出的结果继续操作,输入2进行新的运算)"))

Here I use the eval () function to calculate the expression, and use "{: g}". Format () to make the result not produce unnecessary zeros, and use i as the condition of the loop.

  1. Immediately after modifying the code of the first part, completed the second part. (The place where the change occurred is marked in the code)
    while True:
        if i == 1:
     3      sum1 = sum
     4      print("第一个操作数为", eval(sum1))
            a = input("请输入运算类型:")
            if judgesymbol(a) == 0:
                continue
            b = input("请输入第二个操作数:")
     9      sum1 = sum+a+b
            if judgezero(sum1) == 0:
                continue
    12      print("{}".format(eval(sum))+a+b+"={:g}".format(eval(sum1)))
    13      sum = sum1
    14      i = int(input("是否继续输入?(输入0结束,输入1对得出的结果继续操作,输入2进行新的运算)"))
    
  2. The final version of the code is as follows ( code cloud direct ):
# -*- encoding: utf-8 -*-
'''
文件:    Experiment2.py
时间:    2020/04/11 16:12:24
作者:    20192426 陈瀚文
'''

# 版本一


def judgesymbol(a):
  '''
  判断是否输入的符号是否为+-*/%中的一个
  '''
  if a in ["+", "-", "*", "/", "%", "**"]:
      return 1
  else:
      print("\033[31m请重新输入运算符号!\033[0m")
      return 0


def judgezero(a):
  '''
  功能:判断被除数是否为零,若不为零输出运算结果,否则重新输入
  '''
  try:
      eval(a)
      return 1
  except ZeroDivisionError:
      print("\033[31m0不能作为除数!请重新输入!\033[0m")
      return 0


i = 2
sum = ""
sum1 = ""
while True:
  if i == 0:
      break
  if i == 1:              # 对得出的结果继续操作
      sum1 = sum
      print("第一个操作数为", eval(sum1))
      a = input("请输入运算类型:")
      if judgesymbol(a) == 0:     # 判断符号是否合法
          continue
      b = input("请输入第二个操作数:")
      sum1 = sum+a+b
      if judgezero(sum1) == 0:    # 判断是否进行了除0运算
          continue
      print("{}".format(eval(sum))+a+b+"={:g}".format(eval(sum1)))
      sum = sum1
      i = int(input("是否继续输入?(输入0结束,输入1对得出的结果继续操作,输入2进行新的运算)"))
  if i == 2:          # 对两个数进行运算
      a = input("请输入第一个操作数:")
      s = input("请输入运算类型:")
      if judgesymbol(s) == 0:     # 判断符号是否合法
          continue
      b = input("请输入第二个操作数:")
      sum = a+s+b
      if judgezero(sum) == 0:     # 判断是否进行了除0运算
          continue
      print(sum+"={:g}".format(eval(sum)))
      i = int(input("是否继续输入?(输入0结束,输入1对得出的结果继续操作,输入2进行新的运算)"))

  1. The results are as follows:

Summary: After using version 1 of the program for a long time, I found that this program still has many shortcomings. For example, when inputting, the operands and expressions are entered separately. If the input is incorrect, you must re-enter it, which will cause users It wastes some time, making the efficiency of the program inefficient, making the program spend more time than the mental calculation time when calculating some expressions that are not computationally intensive, which causes inconvenience to the user, so I came up with the idea of ​​optimizing the program And completed the second edition.


Second Edition (Final Edition)

  1. For the first version of the code, I made the following thoughts:
    -If the user directly enters the entire expression, you can use the eval () function to directly find the value of the expression.
    -You can use regular expressions to split the operands and operators in the string entered by the user, and then you can discuss the situation based on the results of the split
    -In this way, it is easier to write the code to calculate the trigonometric function , You can add the function of calculating trigonometric functions to the calculator
  2. Based on the above thinking and the relevant code of the first edition, I imported the re module and the math module, and first completed the code of the four arithmetic parts, and defined the function splitarg () to separate the non-operator part from the operands and operators
    def splitarg(formula):
        '''
        功能:将数与运算符分离
        '''
        pattern = "[+\-*/%]"
        return re.split(pattern, formula)

Define the function splitmark () to separate operators from operands and operators

def splitmark(formula):
    '''
    功能:将运算符与数分离
    '''
    pattern = "[0-9]"
    mark = re.split(pattern, formula)
    return list(filter(None, mark))

Define the function judge () to determine whether the dividend is zero

def judge(formula):
    '''
    功能:判断被除数是否为零,若不为零输出运算结果,否则重新输入
    '''
    try:
        print("{}={:g}".format(formula, eval(formula)))
        return str(eval(formula))
    except ZeroDivisionError:
        print("\033[31m0不能作为除数!请重新输入!\033[0m")
  1. After this, I completed the functions of the four arithmetic parts with reference to the code of version one. The code is as follows:

    def simple(result):
        '''
        功能:四则运算+求余运算+乘方
        '''
        while True:
            formula = input()
            arg = splitarg(formula)         # 把表达式以运算符为界分割成列表
            arg = list(filter(None, arg))   # 将列表中的空字符串删掉
            mark = splitmark(formula)       # 把表达式中的运算符分离出来
            if formula == "q":              # 若输入为q,结束循环
                print("                       Bye~")
                return '0'
            elif formula == "c":            # 若输入为c,切换成计算三角函数模式
                return '2'
            elif len(arg) == 1 and mark != []:  # 若输入的表达式只有一个操作数,则默认上一次计算的结果为另一个操作数
                result = result+formula
                result = judge(result)
            else:                           # 正常输入表达式,正常计算
                result = judge(formula)
    
  2. Then the trigonometric function part was written. Since the trigonometric functions provided by the math module all use the radian system, the angle system must be converted to the radian system when the trigonometric function is calculated, and the result must be converted to the angle system when the inverse trigonometric function is calculated. Consider the two separately, the code is as follows:

    def trigonometric(result):
        '''
        功能:计算三角函数
        '''
        while True:
            formula = input("请输入表达式:")
            if formula == "q":              # 若输入为q,结束循环
                print("                       Bye~")
                return '0'
            elif formula == "c":            # 若输入为c,切换成计算三角函数模式
                return '1'
            else:
                arg = re.split("[()]", formula)     # 将三角函数表达式以括号为界分割,组成列表
                arg = list(filter(None, arg))       # 除去列表中的空字符串,若输入正确,此时列表的第一项为三角函数名,第二项为数据
                # 判断表达式所计算的是三角函数还是反三角函数
                if len(arg[0]) == 3:                # 三角函数情况
                    arg[1] = eval(arg[1])/180*pi
                    formula1 = eval(arg[0]+"("+str(arg[1])+")")
                    print("{}={:g}".format(formula, formula1))
                elif len(arg[0]) == 4:              # 反三角函数情况
                    formula1 = eval(arg[0]+"("+str(arg[1])+")")*180/pi
                    print("{}={:g}".format(formula, formula1))
    
  3. At this point, all the required functions have been written, and finally the main function part.

    print('''\033[36m---------------------开始计算---------------------\033[0m\n
    \033[33m--------------------输入q退出---------------------\033[0m\n
    ---------------请直接输入要计算的公式---------------
    
    支持运算类型:
        1.四则运算
        2.求余运算
        3.乘方(用“**”表示,例如2^3表示为2**3)
        4.三角函数计算(直接输入公式,例如:sin(x))
    ''')
    
    mode = input('''请选择模式,输入对应的数字序号:    
        1.普通计算(对应类型1-3)
        2.三角函数(对应类型4)
        0.退出
        ''')
    if mode == '0':
        print("                       Bye~")
    while (int(mode)):      # 当mode="0"时,程序退出
        if mode == '1':     # 当mode="1"时,执行四则运算函数
            print("请输入表达式:(输入q退出,输入c切换模式)")
            result = "0"
            mode = simple(result)
        elif mode == '2':   # 当mode="2"时,执行三角函数计算
            print("请输入表达式:(角度使用角度制,反三角函数请使用形如asin()的形式输出输入q退出,输入c切换模式)")
            result = "0"
            mode = trigonometric(result)
        else:               # 当输入其他值时,报错
            print("\033[31m请正确输入模式序号!\033[0m")
    
  4. The final second version of the code is as follows ( code cloud direct ):

# -*- encoding: utf-8 -*-
'''
文件:    Experiment2.py
时间:    2020/04/16 19:20:35
作者:    20192426 陈瀚文
'''

# 版本二

import re
from math import*


def splitarg(formula):
    '''
    功能:将数与运算符分离
    '''
    pattern = "[+\-*/%]"
    return re.split(pattern, formula)


def splitmark(formula):
    '''
    功能:将运算符与数分离
    '''
    pattern = "[0-9]"
    mark = re.split(pattern, formula)
    return list(filter(None, mark))


def judge(formula):
    '''
    功能:判断被除数是否为零,若不为零输出运算结果,否则重新输入
    '''
    try:
        print("{}={:g}".format(formula, eval(formula)))
        return str(eval(formula))
    except ZeroDivisionError:
        print("\033[31m0不能作为除数!请重新输入!\033[0m")


def simple(result):
    '''
    功能:四则运算+求余运算+乘方
    '''
    while True:
        formula = input()
        arg = splitarg(formula)         # 把表达式以运算符为界分割成列表
        arg = list(filter(None, arg))   # 将列表中的空字符串删掉
        mark = splitmark(formula)       # 把表达式中的运算符分离出来
        if formula == "q":              # 若输入为q,结束循环
            print("                       Bye~")
            return '0'
        elif formula == "c":            # 若输入为c,切换成计算三角函数模式
            return '2'
        elif len(arg) == 1 and mark != []:  # 若输入的表达式只有一个操作数,则默认上一次计算的结果为另一个操作数
            result = result+formula
            result = judge(result)
        else:                           # 正常输入表达式,正常计算
            result = judge(formula)


def trigonometric(result):
    '''
    功能:计算三角函数
    '''
    while True:
        formula = input("请输入表达式:")
        if formula == "q":              # 若输入为q,结束循环
            print("                       Bye~")
            return '0'
        elif formula == "c":            # 若输入为c,切换成计算三角函数模式
            return '1'
        else:
            arg = re.split("[()]", formula)     # 将三角函数表达式以括号为界分割,组成列表
            arg = list(filter(None, arg))       # 除去列表中的空字符串,若输入正确,此时列表的第一项为三角函数名,第二项为数据
            # 判断表达式所计算的是三角函数还是反三角函数
            if len(arg[0]) == 3:                # 三角函数情况
                arg[1] = eval(arg[1])/180*pi
                formula1 = eval(arg[0]+"("+str(arg[1])+")")
                print("{}={:g}".format(formula, formula1))
            elif len(arg[0]) == 4:              # 反三角函数情况
                formula1 = eval(arg[0]+"("+str(arg[1])+")")*180/pi
                print("{}={:g}".format(formula, formula1))


print('''\033[36m---------------------开始计算---------------------\033[0m\n
\033[33m--------------------输入q退出---------------------\033[0m\n
---------------请直接输入要计算的公式---------------

支持运算类型:
    1.四则运算
    2.求余运算
    3.乘方(用“**”表示,例如2^3表示为2**3)
    4.三角函数计算(直接输入公式,例如:sin(x))
''')

mode = input('''请选择模式,输入对应的数字序号:    
    1.普通计算(对应类型1-3)
    2.三角函数(对应类型4)
    0.退出
    ''')
if mode == '0':
    print("                       Bye~")
while (int(mode)):      # 当mode="0"时,程序退出
    if mode == '1':     # 当mode="1"时,执行四则运算函数
        print("请输入表达式:(输入q退出,输入c切换模式)")
        result = "0"
        mode = simple(result)
    elif mode == '2':   # 当mode="2"时,执行三角函数计算
        print("请输入表达式:(角度使用角度制,反三角函数请使用形如asin()的形式输出输入q退出,输入c切换模式)")
        result = "0"
        mode = trigonometric(result)
    else:               # 当输入其他值时,报错
        print("\033[31m请正确输入模式序号!\033[0m")

  1. The results are as follows

3. Problems encountered during the experiment and the resolution process

  • Question 1: After writing the version one code, I found that the input is too cumbersome and not very convenient

  • Solution for Problem 1: Write the code of version 2 on the basis of version 1, and add the function of calculating trigonometric functions

  • Question 2: When writing the function of calculating trigonometric functions, an error is reported because the difference between inverse trigonometric functions and trigonometric functions is not considered

  • Solution to Problem 2: Use if statement to calculate trigonometric and inverse trigonometric functions

  • Question 3: When the mode is adjusted, the following code will be executed every time, causing inconvenience

  mode = input('''请选择模式,输入对应的数字序号:    
  1.普通计算(对应类型1-3)
  2.三角函数(对应类型4)
  0.退出
  ''')
  • Problem 3 solution: The above code was moved outside the while loop to solve the problem

Others (sentiment, thinking, etc.)

  1. Experiments can be very effective in checking the learning situation . In this experiment, I found that I still have some knowledge that I still do n’t have a firm grasp. At the same time, I also found that when the amount of code reaches a certain level, bugs will not be easily found, and fixing bugs has become very important. Difficult, and the debugging function can let me know clearly which part of the code does not meet the expectations of the design, so as to fix the errors in the code.
  2. The process of writing code should be more thinking , trying to find a better solution, and improve the practicality of the program.

References

Guess you like

Origin www.cnblogs.com/chw123/p/12717113.html