【问题标题】:How to stop a traceback call after making a deliberate mistake?故意犯错后如何停止回溯调用?
【发布时间】:2020-08-02 18:40:36
【问题描述】:

我正在制作一个只执行一定数量的操作的计算器,如果输入了其他任何内容,它会打印一条提醒消息。 但是在该过程中,在打印'a'之后会发生名称错误。 我哪里错了?

if Operation == '+':
    c = a + b

elif Operation == '-':
    c = a - b

elif Operation == '*':
    c = a * b

elif Operation == '/':
    c = a / b
else:
    print('Read the Instructions again, dimmwit')


print('Your answer is', c)

print('Thanks! Have a great time!')

请就我应该如何改进我的代码提出一些建议。

【问题讨论】:

    标签: python if-statement calculator nameerror


    【解决方案1】:

    你真的应该发布你得到的特定 NameError 和回溯。 (还有你的完整代码。)

    无论如何,问题是您没有将c 初始化为任何东西,因此当控制权脱离“侮辱用户”else 时,尝试打印c 不会发生。

    在所有情况下都给c一些值,然后检查你是否真的做了一个操作:

    c = None
    if Operation == "+":
        c = a + b
    elif Operation == "-":
        c = a - b
    elif Operation == "*":
        c = a * b
    elif Operation == "/":
        c = a / b
    else:
        print("Read the Instructions again, dimmwit")
    
    if c is not None:
        print("Your answer is", c)
        print("Thanks! Have a great time!")
    

    更好的是,在它自己的函数中进行计算,然后在其他地方输出给用户:

    def compute(operation, a, b):
        if operation == "+":
            return a + b
        elif operation == "-":
            return a - b
        elif operation == "*":
            return a * b
        elif operation == "/":
            return a / b
        return None
    
    
    c = compute(operation, a, b)
    
    if c is not None:
        print("Your answer is", c)
        print("Thanks! Have a great time!")
    else:
        print("Please read the instructions again.")
    

    【讨论】:

    • 帮助很大!请为像我这样需要提高技能的新手推荐一些类似这样的小项目!
    【解决方案2】:

    因为这个:

    else:
        print('Read the Instructions again, dimmwit')
    

    有可能到时候

    print('Your answer is', c)
    

    到达,如果采用else 路由,则没有定义c

    如果你把它变成一个函数,比如:

    def print_result(operation, a, b):
        if operation == '+':
            c = a + b
    
        elif operation == '-':
            c = a - b
    
        elif operation == '*':
            c = a * b
    
        elif operation == '/':
            c = a / b
    
        else:
            print('Read the Instructions again, dimmwit')
            return
    
        print('Your answer is', c)
        print('Thanks! Have a great time!')
    

    然后您可以使用return 尽早停止,而不是尝试打印从未计算过的答案c

    【讨论】:

    • 但是先生,代码正在执行,因此'Entry for a = 654 Entry for b = 456 你想应用哪个操作?9 a = 654 b = 456' 如果我故意犯了错误并且当没有错误时,代码会在该点停止。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 2021-07-17
    相关资源
    最近更新 更多