首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python计算器

Python计算器
EN

Code Review用户
提问于 2016-08-27 02:30:42
回答 3查看 418关注 0票数 6

我希望您能对我的Python计算器、它可以改进的方式以及它目前缺乏的地方发表意见。

代码语言:javascript
复制
import operator

"""
Do the actual calculation
"""
def calculator(operation, operand_1, operand_2):
    ops = {"+": operator.add, "-": operator.sub, "/": operator.div, "*": operator.mul}
    return ops[operation](operand_1, operand_2)

"""
Initiate the user interface and input from user
"""
def main():
    print_line(19)
    print("WELCOME to CALC+-/*")
    print_line(19)
    while True:
        operation = raw_input("Operation type: ")
        operand_1 = int(raw_input("Operand 1: "))
        operand_2 = int(raw_input("Operand 2: "))
        calculation = calculator(operation, operand_1, operand_2)
        print("Result: " + str(calculation))
        if raw_input("Enter to continue, or 'q' to quit: "):
            break

"""
Utility function to print dashed lines
"""
def print_line(line_length):
    print("-"*line_length)

main()
EN

回答 3

Code Review用户

发布于 2016-08-27 04:50:12

函数的文档串应该位于函数内部的顶部。

例如:

代码语言:javascript
复制
"""
Utility function to print dashed lines
"""
def print_line(line_length):
    print("-"*line_length) # Also, space the operators out.

应:

代码语言:javascript
复制
def print_line(line_length):
    """Utility function to print dashed lines"""
    print("-" * line_length)

嗯,嗯:

代码语言:javascript
复制
print_line(19)
print("WELCOME to CALC+-/*")
print_line(19)

为什么是19?我可能会创建一个名为header的变量并获取它的长度:

代码语言:javascript
复制
header = "WELCOME to CALC+-/*"
print_line(len(header))
print(header)
print_line(len(header))

因此,当您忘记时,您不会感到困惑,为什么稍后会使用19

函数之间还应该有两条换行符。

这一条件是:

代码语言:javascript
复制
if raw_input("Enter to continue, or 'q' to quit: "):
    break

如果我键入任何内容,包括(但不限于) q,则允许我退出。

代码语言:javascript
复制
cont = raw_input("Enter to continue, or 'q' to quit: ")
while True:
    if cont == "":
        break
    elif cont == "q":
        return
    cont = raw_input("Invalid command, please try again: ")

您还有其他一些脆弱的东西,如果输入+<space>或任何带有空格的操作数,程序将崩溃。

replace空空间:

代码语言:javascript
复制
operation = raw_input("Operation type: ").replace(" ", "")

此外,按照惯例,你应该:

代码语言:javascript
复制
if __name__ == "__main__":
    main()

这个答案说明了一些原因。虽然我认为这个程序不太可能是由另一个程序导入的,但你最好是安全的,而不是抱歉的。

票数 6
EN

Code Review用户

发布于 2016-08-27 13:36:44

人们通常不会用波兰符号来思考,

而是按operand_1, operation, operand_2顺序思考。

您可能希望按该顺序请求输入(然后您可以按您希望的顺序调用calculator() ):

代码语言:javascript
复制
    operand_1 = int(raw_input("Operand 1: "))
    operation = raw_input("Operation type: ")
    operand_2 = int(raw_input("Operand 2: "))
票数 3
EN

Code Review用户

发布于 2016-08-27 14:38:44

评论

导入操作符“”进行实际计算“def计算器”(操作,operand_1,operand_2):ops = {"+":operator.add,"-":operator.sub,"/":operator.div,"*":operator.mul}返回ops操作

您导入整个模块,而实际上,您只需要它的四个功能。结果:你吃的RAM太多了。

尝试做dir(__import__('operator'))。你会很困惑,因为它有126个功能(除了内置模块),而你需要4个。

当不得不处理大量数据时,即使是RAM的最后一个字节也必须保存,所以少导入,少吃!少进口是一个很好的做法。

以下是这个问题的解决方案:

代码语言:javascript
复制
from operator import add, sub, div, mul

"""
Do the actual calculation
"""
def calculator(operation, operand_1, operand_2):
    ops = {"+": add, "-": sub, "/": div, "*": mul}
    return ops[operation](operand_1, operand_2)

“”进行实际计算“def计算器(操作,operand_1,operand_2):op= {"+":operator.add,"-":operator.sub,"/":operator.div,"*":operator.mul}返回ops操作“启动用户界面和用户输入”“def main():print_line(19) print(”print_line+-/*“欢迎来到CALC+-/*") print_line(19),而True: print_line=raw_input(”操作类型:") operand_1 = int(raw_input("Operand 1:“) operand_2 = int(raw_ )输入(“操作数2:”)计算=计算器(操作,( operand_1,operand_2)打印(“结果:”+str(计算))如果raw_input(“输入继续,或'q‘退出:"):”中断“”打印虚线的实用函数“”def print_line(line_length):print (“*line_length)

我可以看到,正如@Dair所相信的,这些不是docstring;它们是注释,因为主函数在它上面也有一个。请改用单行注释(#comment):

代码语言:javascript
复制
#Do the actual calculation
def calculator(operation, operand_1, operand_2):
    ops = {"+": operator.add, "-": operator.sub, "/": operator.div, "*": operator.mul}
    return ops[operation](operand_1, operand_2)

#Initiate the user interface and input from user
def main():
    print_line(19)
    print("WELCOME to CALC+-/*")
    print_line(19)
    while True:
        operation = raw_input("Operation type: ")
        operand_1 = int(raw_input("Operand 1: "))
        operand_2 = int(raw_input("Operand 2: "))
        calculation = calculator(operation, operand_1, operand_2)
        print("Result: " + str(calculation))
        if raw_input("Enter to continue, or 'q' to quit: "):
            break

#Utility function to print dashed lines
def print_line(line_length):
    print("-"*line_length)

print("-"\*line\_length)

在这里,你似乎错过了空间。以下是解决办法:

代码语言:javascript
复制
    print("-" * line_length)

印刷品(“欢迎来到CALC+-/*")

print("Result: " + str(calculation))

打印(“-”*line_length)

这里不是python-3.x,所以print是语句,不是函数!

引用文字和整个表达式(如(a) )是不正常的,它毫无用处地减缓了代码的速度,特别是使用了大量数据(即[(i) for i in xrange(2562700000)]),因此这里有一个修正:

代码语言:javascript
复制
print "WELCOME to CALC+-/*"
代码语言:javascript
复制
    print "Result: " + str(calculation)
代码语言:javascript
复制
print "-"*line_length

main()

您似乎没有正确地调用主函数。下面是您应该如何调用它,因为,否则,程序可能会导入并运行:

代码语言:javascript
复制
if __name__ == "__main__":
    main()

有些变量名称非常大,另一些则太短/不够清楚。

if raw\_input("Enter to continue, or 'q' to quit: "): break

除了在这里退出程序之外,您将允许任何输入,而不仅仅是q。解决办法是:

代码语言:javascript
复制
        if raw_input("Enter to continue, or 'q' to quit: ") == "q":
            break

我还建议支持Qq,如下所示:

代码语言:javascript
复制
        if raw_input("Enter to continue, or 'q' to quit: ").lower() == "q":
            break

print("Result: " + str(calculation))

这是字符串格式!

代码语言:javascript
复制
        print("Result: %d" % calculation)

print\_line(19) print("WELCOME to CALC+-/\*") print\_line(19)

等等,什么!?len内置可以帮助您在这里!

代码语言:javascript
复制
    header = "WELCOME to CALC+-/*"
    print_line(len(header))
    print(header)
    print_line(len(header))

结果

代码语言:javascript
复制
from operator import add, sub, div, mul

#Do the actual calculation
def calc(op, a, b):
    ops = {"+": add, "-": sub, "/": div, "*": mul}
    return ops[op](a, b)

#Initiate the user interface and input from user
def main():
    header = "WELCOME to CALC+-/*"
    print_dashed_line(len(header))
    print header
    print_dashed_line(len(header))
    while True:
        op = raw_input("Operation type: ")
        a = int(raw_input("Operand 1: "))
        b = int(raw_input("Operand 2: "))
        r = calc(op, a, b)
        print "Result: %d" % r
        if raw_input("Enter to continue, or 'q' to quit: ").lower() == "q":
            break

#Utility function to print dashed lines
def print_dashed_line(length):
    print "-" * length

if __name__ == "__main__":
    main()
票数 2
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/139749

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档