PTA每日一题-Python-简单计算器

PTA每日一题-Python-简单计算器,第1张

输入一个表达式字符串,计算其结果

输入格式:

行1:输入字符串数目
下面分别输入要计算的表达式

输出格式:

输出计算结果,结果保留2位小数。


对于异常数据能输出相应异常信息。


实现

我的实现为仅针对两位 *** 作数计算,如果需要多位 *** 作数并且判断 *** 作符,可以参考 中/后缀表达式进行实现。


我的另一篇文章:C语言中缀表达式求值(综合)

#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
"""
@File    :   test_1.py    
@Contact :   [email protected]
@Author :    Jason
@Date :      4/1/2022 1:35 PM
@Description  Python version-3.10

"""


def op(params, ch):
    """

    @param params: number list
    @param ch: operation char
    @return: None.
    """
    try:
        result = eval(f"{params[0]}{ch}{params[1]}")
        print(f"{result:0.2f}")
    except NameError as e:
        print("NameError")
    except ZeroDivisionError as e:
        print("ZeroDivisionError")
    except SyntaxError as e:
        print("SyntaxError")


def fun(ls):
    """

    @param ls: string list
    @return: None
    """
    for s in ls:
        if '+' in s:
            s = s.split('+')
            op(s, '+')
        if '-' in s:
            s = s.split('-')
            op(s, '-')
        if '*' in s:
            s = s.split('*')
            op(s, '*')
        if '/' in s:
            s = s.split('/')
            op(s, '/')


def question():
    """
    only operation two number formula and function's relation is worse than meta function.
    @return:
    """
    ls = []
    n = int(input())
    while n > 0:
        ls.append(input())
        n -= 1
    fun(ls)


if __name__ == "__main__":
    question()


输出
3
1+2
3/2
a+1
3.00
1.50
NameError

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/langs/563876.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-03
下一篇 2022-04-03

发表评论

登录后才能评论

评论列表(0条)

保存