🌱 Junior Python Level — Complete Error List & Solutions

Junior Python Error List & Troubleshooting

All 18 essential Junior Python exceptions explained with exact root causes, production fixes, side-by-side Broken vs. Fixed code, and a live Python 3.13 execution sandbox.

🚨 Complete Python Error List, Root Causes & Production Solutions

🌱 Junior Python Core Syntax & Runtime Error Encyclopedia

Every Junior-Level (18) Python exception explained with its exact root reason, step-by-step fix, side-by-side ❌ Broken vs. ✅ Fixed Code, and 1-click Live Python Execution.

🔍
Showing Level Errors
📋 Quick-Reference Summary Table: Junior Python Errors (18)
Level Exception / Error Root Reason (Why It Happens) Production Solution (How to Fix)
JuniorSyntaxError: invalid syntax / unterminated stringRaised during the parsing stage before any line executes. Common causes include missing a colon (:) after if/for/def/class headers, unclosed parentheses/brackets, unclosed quotes, or using assignment (=) instead of equality (==) inside an if condition.Inspect the line number and caret (^) in the traceback AND the line immediately above it (unclosed parentheses often report on the next line). Add the missing colon, closing quote/bracket, or change = to ==.
JuniorIndentationError / TabError: unexpected indentPython uses whitespace indentation to define code blocks instead of curly braces {}. IndentationError occurs when a block is missing indentation after a colon, indents don't align in the same block, or tabs and spaces are mixed (TabError).Follow PEP 8 strictly: use exactly 4 spaces per indentation level and configure your IDE to convert Tabs to Spaces automatically.
JuniorNameError: name '...' is not definedOccurs when Python tries to read a variable, function, or module name that has not been assigned yet in the current scope, is misspelled (e.g., 'ture' instead of 'True'), or was only defined inside an if-branch that did not run.Initialize variables with a default value before conditional branches, verify exact case-sensitive spelling, and import required modules before using them.
JuniorTypeError: unsupported operand type(s) / not callableOccurs when an operation is applied to incompatible types (such as concatenating a str and an int: 'Score: ' + 95), passing the wrong number of arguments to a function, or shadowing a built-in function name (like naming a variable list = [1,2] or str = 'abc') and later calling list().Use f-strings for string formatting, convert input strings with int()/float() before math operations, and never name variables after built-ins (list, dict, str, sum, max, min).
JuniorValueError: invalid literal for int() / not enough values to unpackRaised when a function receives an argument of the correct type (e.g., str) but with an inappropriate value (e.g., int('42.5') or int('abc')), or when tuple unpacking has a mismatched item count (a, b = [1, 2, 3]).Validate user strings or wrap parsing in a try...except ValueError block. For flexible unpacking, use starred expressions (first, *rest = items).
JuniorIndexError: list index out of rangeAttempting to access a list, tuple, or string index that is >= len(seq) or < -len(seq). Often caused by off-by-one range loops (range(len(items) + 1)) or indexing an empty list (items[0]).Check if a sequence is non-empty (if items:) before indexing, iterate directly over elements (for item in items:), or use slicing (items[:1]) which never raises IndexError.
JuniorKeyError: 'missing_key'Raised when accessing a dictionary key via square brackets dict[key] that does not exist in the dictionary.Use dict.get(key, default) for safe lookups with a fallback value, check 'if key in my_dict:', or use collections.defaultdict when accumulating values.
JuniorAttributeError: 'NoneType' object has no attribute '...'Occurs when calling a method or accessing an attribute on an object that doesn't define it. The #1 cause for Junior developers is assigning the result of an in-place list method like my_list = my_list.sort() or my_list = my_list.append(x), which returns None!Call in-place mutating methods (.append(), .sort(), .extend(), .reverse()) on their own line without reassigning the variable, or use sorted(my_list) which returns a new list.
JuniorZeroDivisionError: division by zeroDividing any number by 0 using /, //, or % (modulo). Frequently happens when computing averages on an empty list where len(items) == 0.Always guard denominators before dividing (return 0.0 if not items else sum(items) / len(items)).
JuniorModuleNotFoundError / ImportErrorPython cannot locate the module in sys.path. Usually caused by installing a package globally while running the script in a different virtual environment (.venv), misspelling the package import name, or naming your own script file the same as a standard library module (e.g., naming your file random.py or json.py).Activate your virtual environment and install via 'python -m pip install <pkg>', and never name local .py files after standard library modules.
JuniorFileNotFoundError: [Errno 2] No such file or directoryOpening a file for reading ('r') when the path does not exist, or relying on a relative path that breaks when the script is launched from a different working directory.Use pathlib.Path(__file__).resolve().parent to anchor relative paths to the script's directory, check path.exists(), or handle FileNotFoundError cleanly.
JuniorTypeError: 'tuple' or 'str' object does not support item assignmentStrings (str) and tuples (tuple) are immutable in Python—their individual characters or elements cannot be modified in place after creation.For strings, create a new string using slicing, .replace(), or ''.join(). For collections that need item mutation, convert the tuple to a list.
JuniorTypeError: unhashable type: 'list' / 'dict' / 'set'Dictionary keys and set elements must be hashable (immutable). Mutable containers like list, dict, and set do not have a stable __hash__ value and cannot be used as dictionary keys or put inside a set.Convert mutable lists to immutable tuples (tuple(my_list)) or sets to frozenset() before using them as dictionary keys or set members.
JuniorRecursionError: maximum recursion depth exceededA recursive function calls itself infinitely because it is missing a base termination case, or the recursive step does not move closer to the base case (exceeding sys.getrecursionlimit(), default 1000 frames).Always define an explicit base case (e.g., if n <= 1: return 1) at the top of the function, or rewrite deep recursion as an iterative loop.
JuniorStopIteration (Manual next() Exhaustion)Calling built-in next(iterator) on an iterator or generator that has no more items left to yield raises StopIteration (for loops catch this automatically, but manual next() calls do not).Pass a default fallback value as the second argument to next(iterator, default) so it returns the fallback instead of raising StopIteration.
JuniorUnicodeDecodeError: 'utf-8' codec can't decode byteReading a file or byte stream encoded in Latin-1 / Windows-1252 (cp1252) using UTF-8, or omitting encoding='utf-8' on Windows where the default locale encoding differs.Always specify explicit encoding='utf-8' when opening text files, or use errors='replace' / encoding='latin-1' when ingesting legacy non-UTF-8 files.
JuniorAssertionErrorRaised when an assert statement evaluates to False. Note: never use assert for production input validation or security checks because running Python with the -O (optimize) flag strips all assert statements from bytecode!Use assert in unit tests (pytest) and internal development checks; in production code, raise explicit ValueError or TypeError instead.
JuniorTypeError: missing 1 required positional argument: 'self'Defining an instance method inside a class without 'self' as its first parameter, or calling an instance method directly on the class (MyClass.method()) without instantiating an object first (MyClass().method()).Always include 'self' as the first parameter of instance methods (or decorate with @staticmethod / @classmethod if no instance is needed) and instantiate the class with parentheses.