You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python简易计算器核心代码写法规范咨询与代码能力提升建议求助

Hey there! Great job putting together this basic calculator—it looks clean and works as intended. Let's tackle your questions one by one.

1. Is return operator.get(operator_sign)(val1,val2) a规范/optimal approach?

First things first: this is absolutely Pythonic and规范! Using a dictionary to map operator symbols to corresponding functions is a common, elegant way to replicate switch-case logic in Python (since Python doesn't have a native switch statement). It's readable, concise, and easy to extend—if you wanted to add a new operation like exponentiation later, you just add a key-value pair to the operator dictionary and a new function.

That said, here are a few small tweaks you could consider to make it even more robust:

  • Handle invalid operators: Right now, if a user enters an operator that's not in your dictionary (like %), operator.get() will return None, and calling None(val1, val2) will throw an error. You can add a fallback to handle this gracefully:
    def operation(val1, val2, operator_sign):
        # Use a lambda to return an error message if the operator is invalid
        func = operator.get(operator_sign, lambda x, y: f"Error: '{operator_sign}' is not a valid operator")
        return func(val1, val2)
    
    Or you could check for the operator's presence first and raise a user-friendly error:
    def operation(val1, val2, operator_sign):
        if operator_sign not in operator:
            raise ValueError(f"Invalid operator: '{operator_sign}'. Choose from +, -, *, /")
        return operator[operator_sign](val1, val2)
    
  • Simplify (if you want): Since your operation function is just a thin wrapper around the dictionary lookup, you could even remove it entirely and call the function directly:
    if operator_sign in operator:
        print(operator[operator_sign](val1, val2))
    else:
        print("Invalid operator!")
    
    This is a matter of preference—keeping the operation function is fine if you want to encapsulate the logic for reusability later.
  • Use built-in operators (optional): For learning purposes, writing your own add, sub, etc., functions is great! But once you're comfortable, you can use the built-in functions from the operator module to save some code:
    import operator  # Note: renamed your dictionary to avoid conflict
    op_map = {
        "+": operator.add,
        "-": operator.sub,
        "*": operator.mul,
        "/": operator.truediv,
    }
    
    Just make sure to rename your dictionary so it doesn't clash with the imported module name.
2. How to improve your coding skills and become a more efficient developer?

Here are some practical, actionable tips tailored to someone learning Python:

  • Code consistently, even small amounts: Practice makes perfect. Start with tiny projects (like expanding your calculator to support multiple operations in a row, or a to-do list app) and gradually take on more complex ones. Don't worry about writing "perfect" code at first—just write code that works, then refine it later.
  • Read other people's code: Browse popular Python projects on GitHub (like requests, Flask, or pandas) and look at how experienced developers structure their code, name variables/functions, and handle edge cases. Pay attention to comments, docstrings, and how they organize their modules.
  • Learn Pythonic patterns: Python has a lot of idioms that make code concise and readable (like list comprehensions, generator expressions, context managers with with statements, and using enumerate() instead of range(len(...))). Spend time learning these—they'll make your code more efficient and easier to maintain.
  • Master debugging and testing: When your code breaks, don't just guess—use print statements or a debugger (like pdb or the debugger in VS Code) to step through your code and see what's happening. Also, learn to write simple unit tests (using unittest or pytest) to verify that your functions work as expected. This will save you time in the long run.
  • Refactor your old code: Every few weeks, go back to code you wrote earlier and ask: "Can I make this better?" Maybe you can extract repeated code into a function, simplify a complex loop, or make variable names more descriptive. Refactoring is a great way to learn and improve.
  • Join developer communities: Participate in forums like Stack Overflow (ask questions when you're stuck, and try answering others' questions if you can), or join Python-focused Discord/Reddit communities. Talking to other developers will expose you to new ideas and approaches.
  • Deepen your fundamentals: Spend time learning core concepts like data structures (lists, dictionaries, sets, tuples) and algorithms (sorting, searching). Understanding when to use which data structure will make your code much more efficient. You don't need to become an algorithm expert, but having a solid foundation helps.

内容的提问来源于stack exchange,提问作者Kunal Khaire

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 19:57:33