待翻譯:7 Python Mistakes Beginners Make (And What to Do Instead)
AI 服務暫時不可用,以下為來源摘要,待恢復後補全翻譯:It's about the mistakes that make a running program wrong. Below are seven of them. For each one you get the hidden cause, plus the first thing worth checking.
AI 服務暫時不可用,以下為來源正文,待恢復後補全翻譯。
--> 7 Python Mistakes Beginners Make (And What to Do Instead) - KDnuggets --> Join Newsletter Some Python bugs announce themselves with a traceback. The maddening ones don't. pip swears the package is installed, yet the import fails. A script that worked yesterday suddenly can't find a function that's clearly right there. Two lists get paired up and a record quietly vanishes, with no error and no warning. Here's the uncomfortable pattern behind most of these: Python did exactly what you asked. The gap is between what you asked and what you assumed, and that gap is where beginners lose entire afternoons. This isn't about syntax errors or the common Python gotchas like mutable default arguments that KDnuggets has covered before; it's about the mistakes that make a running program wrong. Below are seven of them. For each one you get the hidden cause, plus the first thing worth checking. Symptom Hidden Cause First Check 1. pip installs, import fails Two different Pythons print(sys.executable) 2. Import finds the wrong thing Your file shadows the module print(module.file) 3. Math on user input crashes input() returns str Convert with int() at the boundary 4. Program continues, output missing except Exception: pass Preserve the traceback 5. Loop skips items / RuntimeError Mutating while iterating Loop over a copy 6. Variable becomes None list.sort() returns None Use sorted() for a new list 7. zip() drops a record Stops at shortest iterable zip(..., strict=True) on 3.10+ Figure 1. The seven mistakes as a troubleshooting reference: symptom, hidden cause and the first check to run. Sources: Python documentation. Original matrix created for this article. 1. Installing the Package into a Different Python The classic opening scene of a beginner's bad day: pip install requests finishes happily, you run your script, and Python greets you with ModuleNotFoundError: No module named 'requests'. You install it again. Same error. At this point it genuinely feels like pip and Python are gaslighting you, but the truth is more boring: you have two different Pythons. Interpreters pile up on a machine over the years, and every virtual environment brings along its own interpreter plus its own package directory. The pip on your PATH can easily belong to one Python while your script runs under another. The fix is to stop letting them drift apart. Create and activate an environment, then route every install through the interpreter that will actually run the code: python -m venv .venv source .venv/bin/activate # Windows: .venv\Scripts\activate python -m pip install requests If the mystery shows up anyway, don't reinstall a fourth time. Print sys.executable inside the failing script, then compare it against whatever python -m pip --version says. Two different paths means reinstalling was never going to work. The packaging guide's pip-and-venv walkthrough takes maybe ten minutes and puts this whole class of problem to bed. 2. Your Filename Hijacks the Import Name a practice file json.py, write import json inside it, and watch Python lose its mind with errors about missing attributes or circular imports. You can pull off the same trick with random.py or csv.py, or with pandas.py if you'd rather break third-party code instead. What's happening: Python walks the module search path to resolve imports, and your script's own directory sits near the front of that line. So your json.py gets found before the standard library's version ever does. Every piece of code expecting the real module now receives your three-line practice file, and none of it copes well. Rename the file and the problem usually dies instantly. If it lingers, delete the stale pycache folder next to it. For any future confusion of this kind, one line settles the question of what Python actually loaded: print(module.file). 3. Trusting Input to Have the Type You Want age = input("How old are you? ") next_year = age + 1 # TypeError: can only concatenate str (not "int") to str input() hands you a string no matter what. The user typed 25? You got "25". The crash above is the friendly version of this mistake. The nastier version is a comparison like "9" > "10", which is perfectly legal string ordering and quietly returns True. Convert at the boundary, deliberately, and catch the one failure conversion can produce: try: age = int(input("How old are you? ")) except ValueError: print("Please enter a whole number.") That's the whole discipline: external values get an explicit type the moment they enter, and the specific ValueError gets handled where the user can do something about it. 4. Catching the Exception and Erasing the Evidence What's actually wrong with this? try: process(records) except Exception: pass Everything, though not for the reason beginners think. Catching exceptions is fine. Throwing away the only evidence of what failed is the actual crime. Say process() dies on record 4,000: this code shrugs, keeps going, and the damage doesn't surface until days later, when some report comes up short on rows and nobody can say why. The errors and exceptions tutorial points the way out: catch the specific exception you expect and know how to handle, and let everything else surface. If you genuinely need a broad catch at some outer boundary, log the exception and re-raise it, so the program gains context without losing the traceback. Silence is the one option that costs you the failure and the explanation at once. Once specific handling feels natural, some practical error-handling helpers can tidy up the repetition. 5. Changing a Collection While Walking Through It Suppose you're purging inactive users: for user in users: if not user.active: users.remove(user) # skips the neighbor of every removed item Removing an item shifts everything after it one position left, but the loop's internal index marches on, so the element right after each removal never gets examined. The list you're modifying is the same structure steering the loop, and the two jobs interfere. Dictionaries are stricter about it and raise a RuntimeError mid-iteration instead. Python's own tutorial suggests the two safe patterns: loop over a copy when you must mutate in place, or build a new collection, which is usually cleaner anyway: for user in users.copy(): # safe: iterating the copy if not user.active: users.remove(user) active_users = [u for u in users if u.active] # often better 6. Saving the Return Value of an In-Place Method One line, one very confusing afternoon: numbers = numbers.sort() # numbers is now None list.sort() sorts the list where it stands and returns None. That's deliberate, so you can't confuse it with an operation that makes a copy. But it means the assignment above throws your freshly sorted list away and stores nothing in its place. The error turns up later, somewhere else entirely, as 'NoneType' object is not iterable. Two idioms exist, and you have to actually pick one. Call numbers.sort() on its own line when you want the list changed. Write numbers = sorted(numbers) when you want a new one. Other side-effect methods like append() and reverse() deserve the same suspicion; if a method mutates, expect None back until the docs tell you different. 7. Assuming zip() Will Warn You About Missing Data Pair up names and scores with zip() and count what comes out: names = ["Amara", "Ben", "Chen", "Dana"] scores = [91, 84, 77] print(list(zip(names, scores))) # [('Amara', 91), ('Ben', 84), ('Chen', 77)] ...Dana is just gone By default zip() just stops when the shortest iterable runs out. There's no exception and no warning, only a record that fell off the end. If those were labels and predictions, you might ship that bug. When equal length is actually part of your data's contract, put it in the code: zip(names, scores, strict=True) raises a ValueError the moment the lengths disagree. One catch, though — the strict flag arrived in Python 3.10, so on anything older you're comparing the lengths yourself before pairing. Making the Failure Visible First Look back across all seven and a habit starts to form. None of these bugs came from Python misbehaving. They came from assumptions the program never agreed to, and those assumptions ran invisibly until something downstream finally snapped. So when a program acts irrational, hold off on rewriting it. Interrogate it first. Check which interpreter is actually running (sys.executable) and where each import really came from (module.file). Look at the type and value you're genuinely holding rather than the one you meant to have. And leave unexpected exceptions loud until you've decided, on purpose, what recovery should look like. That short interrogation settles a surprising number of beginner debugging sessions inside a few minutes, and it builds exactly the instincts a structured Python mini-course can stack real projects on top of. Python itself is remarkably consistent. Usually the fastest fix is working out which of your assumptions it never signed up for. Nahla Davies is a software developer and tech writer. Before devoting her work full time to technical writing, she managed—among other intriguing things—to serve as a lead programmer at an Inc. 5,000 experiential branding organization whose clients include Samsung, Time Warner, Netflix, and Sony. Our Top 5 Free Course Recommendations --> Latest Posts 7 Python Mistakes Beginners Make (And What to Do Instead) The Local AI Stack for Productive SLMs Quantization and Pruning Methods to Make Your LLM Leaner What We Can Learn From Google Engineers’ Indispensible Prompts Understanding the Impact of AI on Job Markets 10 Rules for Getting Better Results from AI Coding Agents Top Posts The Local AI Stack for Productive SLMs How to Leverage Local Small Language Models for Your Projects How to Build a Career in AI: 3 Distinct Pathways 10 Rules for Getting Better Results from AI Coding Agents 5 Real-World Use Cases for AI Agents Transforming Industries Building an End-to-End Data Science Portfolio Project Top 10 Open-Source Benchmarks for AI Coding Agents in 2026 Python Data Classes Beyond the Boilerplate Run Qwen3.8-27B as a Local AI Coding Agent in Just 3 Commands What We Can Learn From Google Engineers’ Indispensible Prompts Published on August 31, 2026 by No, thanks!