Artwork by @allison_horst
đ Debugging scenarios and solutions
Quick debugging tips
- Read the error message and look at the line that it refers to.
- Sometimes the issue is at the line just above the line that was listed in the error.
- If enabled, pay close attention to the syntax highlighting in your editor, which can point at where the error might be happening.
- Use
print()
statements to display the type and value of your variable. - Go back to the instructions and carefully re-read them.
- Use Python Tutor to visualize your code.
- Use the Rubber Duck Debugging to walk yourself through the logic of your code.
- If you are having trouble with your output not matching what is expected, use an online text comparison tool, e.g. https://text-compare.com or https://contenttool.io/text-difference-checker.
Table of contents
- Quick debugging tips
- EOF (end-of-file) Errors
EOL while scanning string literal
- Indentation Errors
KeyError: ...
with a dictionary- Name Errors
- Positional Arguments Errors
- Syntax Errors
- Type Errors
- Undesirable Results
- Common autograder error messages on Gradescope
- Template
EOF (end-of-file) Errors
EOFError: EOF when reading a line
- Cause:
- Python is expecting an input but there is no input to provide.
- Alternatively, there might be a missing closing parenthesis (see
SyntaxError: unexpected EOF while parsing
). - If the error is produced when using a loop, check that you do not have an infinite loop. Look closely at the loopâs conditions and verify that the loop stops, especially, in the edge cases.
- In almost all cases,
input()
should be included inside the main program, not inside the functions.
- The program instructions might be providing 1 input value, but you have an extra
input()
in your code.num_items = int(input()) item = input()
but the input is just a single number, thereâs no
item
to provide viainput()
. - An infinite loop example -
num_items
doesnât get updated within the loop, so the condition stays alwaysTrue
(unlessnum_items == 0
and the loop is not executed):num_items = int(input()) items = [] while num_items: item = input("Enter an item: ") items.append(item)
SyntaxError: unexpected EOF while parsing
- Cause: Missing a closing parenthesis
)
. - Example erroneous code:
print('Hello, World'
- Corrected line of code:
print("Hello, World")
EOL while scanning string literal
- Cause: Missing a closing quotation mark or a mismatched quotation mark (incorrectly placed quotation can also cause it).
- Example erroneous code:
print('Hello, World) # missing a quotation mark
or
print('Hello, World") # mismatched quotation marks
Indentation Errors
IndentationError: unexpected indent
- Example erroneous code:
print("Hello world!") print("What a nice day!")
- Cause: The code is either indented even though it is not necessary or is missing an indentation. The line number in the error points at where the mismatch happened.
- Correct code:
print("Hello world!") print("What a nice day!")
IndentationError: expected an indented block
- Example erroneous code:
def print_hello(): """Print a simple greeting.""" print("Hello!")
- Cause: This error occurs if the previous line ended with a colon
:
and did not have a properly indented line of code underneath it. It is likely that the issue occured at the line directly above the line reported in the error. - Correct code (notice the indentation after the line that ends with a colon):
def print_hello(): """Print a simple greeting.""" print("Hello!")
KeyError: ...
with a dictionary
This error occurs when working with dictionaries. The line above the error shows which line caused the incorrect retrieval.
- Example erroneous code:
month_names = {
"1": "January",
"2": "February",
}
print("First month is", month_names[1]) # KeyError: 1
Alternatively, you wouldnât get an error but would get an undesired output that displays None
if using .get()
:
print("First month is", month_names.get(1)) # results in "First month is None"
- Cause: This error occurrs when trying to retrieve a value using a key that doesnât exist in the dictionary. Possible causes:
- the dictionary does not store the correct key-value pairs (did you add all necessary items? what about the edge cases?)
- the key is stored / retrieved as an incorrect type (see the example)
- Correct code (alternative options):
...
print("First month is", month_names["1"])
print("First month is", month_names.get("1"))
print("First month is", month_names[str(1)])
Name Errors
NameError: name '...' is not defined
Python would replace the ellipsis ...
with the name of the variable that itâs unable to find.
- Cause: Generally, this error happens when a function name or a variable name
- is misspelled
- has not been properly defined first
For example:
NameError: name 'Print' is not defined
- Example erroneous code:
Print('Hello, World')
- Cause: In this case, the function name is âmisspelledâ - an accidentally capitalized name of the function makes Python look for a variable called
Print
.
This error can also be caused if there is a single word (or comma-separated words) inside the print()
that needed to be displayed as the literal text but does not include quotation marks around it (similar to the SyntaxError: invalid syntax
).
- Example erroneous code:
print(Hello) print(Hello, World)
generates the same error (
NameError: name 'Hello' is not defined
), since Python is now looking for a variable calledHello
- it doesnât know that we just forgot to put quotation marks around the text.
NameError
with a dictionary
NameError: name 'A' is not defined
- Example erroneous code:
dict1 = {"A":1, "B":2, "C":3} print(dict1[A])
Cause: Missing quotation marks (
" "
) when indexing a key from the dictionary.- Correct code:
dict1 = {"A":1, "B":2, "C":3} print(dict1["A"])
Positional Arguments Errors
Letâs first look at the case where too many arguments were provided in the function call. In that case, the error would be something like: print_name takes 0 positional arguments but 1 was given
.
- Example erroneous code:
def print_name():
print("Sam")
if __name__ == '__main__':
print_name("Sam")
Cause: The function
print_name()
does not take any parameters but when calling the function one parameter is being passed. This error signifies that there is a mismatch between the number of parameteres in the function defintion and the number of arguments in the function call.Correct code:
def print_name():
print("Sam")
if __name__ == '__main__':
print_name()
This also works the other way around if you are missing arguments in the function call. For example, the function below results in an error: get_largest() missing 1 required positional argument: 'y'
.
- Example erroneous code:
def get_largest(x, y):
return max(x, y)
if __name__ == '__main__':
x = int(input())
y = int(input())
print(get_largest((x, y)))
- Cause: The function
get_largest()
takes in two parameters but when calling the function only one is passed in (i.e., a tuple with two elements). This error likewise signifies that there is a mismatch between the number of parameteres in the function defintion and the number of arguments in the function call. - Correct code:
def get_largest(x, y):
return max(x, y)
if __name__ == '__main__':
x = int(input())
y = int(input())
print(get_largest(x, y))
Syntax Errors
SyntaxError: invalid syntax
This is a general error that occurs when the syntax is not correct and a âPython sentenceâ is broken. If enabled, pay close attention to the syntax highlighting, which can point at where the error might be happening.
Below are sample Python syntax rules:
- A function call must start and end with a parenthesis; the number of open and closed parentheses must match.
- The literal text has to be enclosed within the quotation marks.
- Variables must first be defined (created) before being used.
- Cause: Missing opening quotation mark or opening parenthesis or quotations around the text.
- Example erroneous code:
print(Hello World') print'Hello World print(Hello World) # see also NameError
SyntaxError: unmatched ')'
- Cause: an extra closing parenthesis
)
that does not have a matching opening paren(
. - Example erroneous code:
print('Hello, World'))
Type Errors
TypeError: argument of type 'int' is not iterable
- Example erroneous code:
total = 42
sum(total)
- Cause: The error usually occurs when a built-in Python function that is intended for a sequence/collection is applied to an integer instead.
- Correct code:
total = [42]
sum(total)
TypeError: argument of type 'NoneType' is not iterable
- Example erroneous code:
val = None
if "a" in val:
print("Found it!")
- Cause: The error usually occurs when the
in
operator in trying to index aNone
value instead of the sequence/collection.- Check the type/value of the object that is used after the
in
operator - if that object is a result of the functionâs return value, verify that the function is returning the correct object or that yourif
branches are set up correctly to not try to index aNone
. - Do not store the result of
print()
and attempt to index it. Just like the methods that modify lists directly (since lists are mutable),print()
does not return anything other thanNone
.
- Check the type/value of the object that is used after the
- Correct code:
val = None if val != None: if "a" in val: print("Found it!")
or
val = "aeou" # correct object provided if "a" in val: print("Found it!")
TypeError: can only concatenate str (not "int") to str
- Example erroneous code:
num = 6 print("I would like " + num + " tacos please.")
- Cause: You can only concatenate a string with a string, not a numeric type. Check the types of the variables that you are using in the concatenation.
- Correct code and alternatives:
num = 6 print("I would like " + str(num) + " tacos please.") # proper string concatenation print("I would like", num, "tacos please.") # using print defaults print(f"I would like {num} tacos please.") # using f-strings
ValueError: invalid literal for int() with base 10
- Example erroneous code:
current_year = '1792.99' current_year = int(current_year) print(current_year)
Cause: Float, represented as a string, cannot be directly converted into an integer. If you do want to pass a string representation of a float to an int, you need to convert to a float first, then to an integer.
- Correct code:
current_year = '1792.99' current_year = float(current_year) current_year = int(current_year) print(current_year)
TypeError: object of type '...' has no len()
Examples include the errors
TypeError: object of type 'int' has no len()
TypeError: object of type 'float' has no len()
- Example erroneous code:
len(42)
Cause: The error usually occurs when you think that you are asking for a length of a collection (e.g., a list, string, dictionary) but in reality the argument is an integer. Examine the value that is being provided as an argument into the
len()
function.Correct code:
len([42])
TypeError: ... takes exactly one argument (... given)
Some examples of this error:
TypeError: len() takes exactly one argument (2 given)
- Example erroneous code:
len(42, 33)
- Cause: The error usually occurs when
- a built-in Python function is being applied to an incorrect object.
- the function is not given the required number of arguments.
- Correct code:
len([42, 33])
TypeError: unsupported operand type(s) for +: 'int' and 'list'
- Example erroneous code:
nested_list = [[5, 10, 6], [7, 8, 9]]
total_sum = sum(nested_list)
Cause: The error can occur when trying to sum up a nested list, instead of its individual elements.
Correct code:
nested_list = [[5, 10, 6], [7, 8, 9]]
total_sum = 0
for item in nested_list:
item_sum = sum(item)
total_sum += item_sum
Undesirable Results
Output printing None
None
is printed even though you donât want it to be there- Example erroneous code:
def print_hello():
print("hello")
if __name__ == '__main__':
print(print_hello())
- Cause: The function
print_hello()
does not return anything (it has noreturn
statement) so when you callprint(print_hello())
you are printing its return value which isNone
. - Correct code:
def print_hello():
print("hello")
if __name__ == '__main__':
print_hello()
Logic Errors
- Sometimes, we get a logic error, when the output does not match what we expect.
- Example erroneous code:
def get_largest(x,y): if x > y: return y else: return x
Cause: Although the syntax of this function is correct and the function will produce no errors, the result will be incorrect. This is simply due to a logical error - an incorrect value is being returned (or, the
if
condition needs to be changed).- Correct code:
def get_largest(x,y): if x > y: return x else: return y
Function address is printed <function function_name at 0x....>
- Function Address gets printed -
<function function_name at 0x....>
- Example erroneous code:
def area(radius):
return 3.14 * radius**2
if __name__ == '__main__':
radius = float(input())
print(f"Circle has area {area} inches squared.")
- Cause: Instead of the function call, which requires the parentheses (and the arguments, if necessary), only the name of the function is used.
- Correct code:
... print(f"Circle has area {area(radius)} inches squared.")
Common autograder error messages on Gradescope
Your submission timed out. It took longer than 600 seconds to run.
- Cause: you have an infinite
while
loop in your code. - Check: Carefully look at the condition in the
while
and ask when/if it will ever become False. Check when/where you are updating variables in the condition - the loop will keep going until the condition becomes False, so if the variable is not updated within the loop, you get an infinite loop.
Test Failed: Check the name of your .py file: it is incorrect.
- Cause: you did not name your file according to the instructions.
- We do not re-upload studentsâ files: if you would want to manually do something for all 280+ students in the class, please do not ask us to do it.
Test Failed: Syntax error when importing ...
- Cause: Something in your file is causing a syntax error (could be as simple as incorrect indentation; see the SyntaxError examples listed above).
- Check: Run your code and examine the line that is causing an error.
Template
Error: ...
This is a template for the error entries.
- Example erroneous code:
...
Cause: âŚ
Correct code:
...
Acknowledgements
Developed by Yekaterina Kharitonova with assistance from students and course mentors.
Special thanks to Liu Kurafeeva for creating the initial formatting of this page.