Latest dealsDeals See all deals→
How to Debug Common Programming Assignment Errors

How to Debug Common Programming Assignment Errors: Step-by-Step Python, Java, and SQL Examples

Emma Claire Bennett
Emma Claire Bennett
35 min read

Most programming assignments are not lost while writing the code. They are lost at 11 p.m. the night before the deadline, in front of a red error message that seems to have nothing to do with the line it points at.

We have been helping students with programming coursework at AssignmentDude since 2017. The errors that cost the most time are rarely exotic. They are the same handful of mistakes, repeated across courses, and the research on student code says the same thing. A University of Kent study of 37 million Java compilations found single mistakes that showed up hundreds of thousands of times in one year.

This guide covers those errors in the three languages we see most in coursework: Python, Java, and SQL. For each one you get the broken code, the message it produces, what that message is telling you, and the fix. We ran every example before publishing, so the error text below is what you will see on your own screen.

Start with the six-step routine if you are stuck right now. Skip to your language if you already know which error you have.

What the research says about student errors

Errors that produce a message get fixed in about a minute. Errors that produce no message are where the hours go. Three large studies of student code point the same way.

Java: 37 million compilations

Altadmri and Brown (2015) tracked 18 known mistakes across 37 million compilations from more than 250,000 students using the BlueJ editor. Six of their rows tell the story.

MistakeTimes seen in one yearMedian time to fixDoes the compiler flag it?
Mismatched brackets, braces or quotes793,23217 secondsYes
Calling a method with the wrong argument types464,07558 secondsYes
Method can end without returning a value342,89137 secondsYes
= instead of == in a condition173,938111 secondsYes
Ignoring the value a method returns121,663Over 1,000 secondsNo
== instead of .equals() on strings121,172Over 1,000 secondsNo

The study capped its timer at 1,000 seconds, a little under 17 minutes. For the two mistakes the compiler says nothing about, more than half of students hit that cap or never fixed the bug in the session.

Python and Java: the same few messages, over and over

David Pritchard counted error messages in large sets of student Python and Java submissions. His top five for each language are the ones you are most likely to meet in a first or second programming course.

RankPython messageJava message
1SyntaxError: invalid syntaxcannot find symbol (variable)
2NameError: name is not defined';' expected
3EOFError: EOF when reading a linecannot find symbol (method)
4SyntaxError: unexpected EOF while parsingcannot find symbol (class)
5IndentationError: unindent does not matchincompatible types

A few messages account for a large share of the total, and the rest form a long tail. Learning to read ten messages well covers far more than ten errors' worth of your debugging time.

SQL: the query that runs is the risky one

Taipalus, Siponen and Vartiainen (2018) sorted more than 33,000 queries from 237 students in an introductory database course into four classes: syntax errors, semantic errors, logical errors, and needless complications.

The logical errors stand out. These queries run without complaint and answer a different question from the one asked. On single exercises, wrong operators appeared in up to 62.2% of queries and wrong joins in up to 58.0%. On one grouping exercise, about 59% of 158 students submitted a similar wrong query and moved on because the result looked fine.

That is why about half of the examples below are bugs with no error message at all.

A six-step debugging routine for any language

Use the same six steps every time, in the same order. Guessing and retyping feels faster and almost never is.

  1. Read the whole message, then the part that matters. In Python, the last line names the error and the lines above it show how the program got there. In Java, fix only the first compiler error and recompile, because later errors are often side effects of the first. For a Java exception, find the first at line that names one of your own files.
  2. Go to the line number, then look one line up. The message marks the spot where the language gave up, which is often after the real mistake. A missing bracket, quote or semicolon usually sits on the line before.
  3. Reproduce it with the smallest input you can. A list of three numbers is easier to reason about than the 500-row test file. If the bug disappears with small input, you have learned it depends on size or on one specific value.
  4. Say what you expected, in one sentence. For example: "After the loop, total should be 255." If you cannot finish that sentence, the problem is your understanding of the task, and no amount of code editing will fix it.
  5. Check the actual value at that point. Print it or stop there in a debugger. The gap between what you expected and what you see is the bug.
  6. Change one thing, then rerun every test. If the change did not help, undo it before trying the next idea. Stacking three half-fixes is how a small bug becomes a rewrite.

Python errors and how to fix them

Seven errors cover most Python assignment trouble: six with a traceback and one without. All output below comes from Python 3.13. Older versions print shorter messages, so update if your course allows it.

1. NameError: name is not defined

total_score = 0 for mark in [78, 85, 92]:    total_score += mark print(totel_score)Traceback (most recent call last):  File "grades.py", line 4, in <module>    print(totel_score)          ^^^^^^^^^^^ NameError: name 'totel_score' is not defined. Did you mean: 'total_score'?

What it means: Python reached a name it has never seen. The usual causes are a typo, using a variable before giving it a value, or creating it inside a function or an if branch that never ran.

Fix: The carets sit under the exact name. Correct the spelling here. When Python offers no suggestion, search the file for the line where you assign that variable and check that it runs first.

2. TypeError: can only concatenate str (not "int") to str

age = input("Enter your age: ") next_year = age + 1 print(next_year)Traceback (most recent call last):  File "age.py", line 2, in <module>    next_year = age + 1                ~~~~^~~ TypeError: can only concatenate str (not "int") to str

What it means: input() always returns text, even when the user types digits. Python will not add the text "19" to the number 1.

Fix: Convert at the moment you read the value, so every later line works with a number.

age = int(input("Enter your age: "))

3. SyntaxError and IndentationError

These stop the program before a single line runs. Three versions show up most.

A missing colon after if, for, while or def:

def grade(score):    if score >= 90        return "A"    return "B"  File "grade.py", line 2    if score >= 90                  ^ SyntaxError: expected ':'

A bracket you opened and never closed:

marks = [78, 85, 92 total = sum(marks)  File "marks.py", line 1    marks = [78, 85, 92            ^ SyntaxError: '[' was never closed

A line that does not line up with any block above it:

def grade(score):    if score >= 90:        return "A"      return "B"  File "grade.py", line 4    return "B"              ^ IndentationError: unindent does not match any outer indentation level

Fix: Add the colon, close the bracket, or re-indent the block. For indentation, set your editor to insert four spaces when you press Tab. Mixed tabs and spaces look identical on screen and are different to Python.

Python 3.14, released in October 2025, also catches misspelled keywords. Typing whille True: now returns SyntaxError: invalid syntax. Did you mean 'while'? where older versions only say invalid syntax.

4. IndexError: list index out of range

scores = [78, 85, 92] for i in range(1, len(scores) + 1):    print(scores[i])85 92 Traceback (most recent call last):  File "scores.py", line 3, in <module>    print(scores[i])          ~~~~~~^^^ IndexError: list index out of range

What it means: A list of three items has positions 0, 1 and 2. This loop asks for positions 1, 2 and 3.

Read the output before the traceback. The first score, 78, never printed. That tells you the loop starts in the wrong place as well as ending in the wrong place.

Fix: Loop over the items directly. You only need index numbers when the task asks for positions.

for score in scores:    print(score)

5. TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

def average(nums):    total = sum(nums)    print(total / len(nums)) result = average([80, 90, 100]) print(result + 5)90.0 Traceback (most recent call last):  File "average.py", line 6, in <module>    print(result + 5)          ~~~~~~~^~~ TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

What it means: The function printed the answer and handed nothing back. A function with no return gives None, so result is None.

Fix: Replace print with return inside the function. Any time you see NoneType in an error, look for a function that forgot to return.

6. EOFError: EOF when reading a line

n = int(input()) values = [] for _ in range(n):    values.append(int(input())) extra = input() print(sum(values))Traceback (most recent call last):  File "sum.py", line 5, in <module>    extra = input() EOFError: EOF when reading a line

What it means: The program asked for input and none was left. This one ranks third in Pritchard's data and it shows up mostly on autograders such as Gradescope or zyBooks. On your own machine the program waits for you to type, so you never see it.

Fix: Call input() exactly as many times as the assignment specifies, in the same order. Remove leftovers such as a final "press Enter to exit" line.

7. No error, wrong answer

def average(scores):    for s in scores:        total = 0        total += s    return total / len(scores) print(average([80, 90, 100]))33.333333333333336

The expected answer is 90.0. No traceback will help, so use steps 4 and 5 of the routine. We expect total to reach 270. Print it on each pass:

        print(f"{s=} {total=}")s=80 total=80 s=90 total=90 s=100 total=100

total never grows because total = 0 sits inside the loop and wipes it on every pass. Move that line above the for. Then test an empty list. You get ZeroDivisionError: division by zero, which is worth handling if the assignment mentions empty input.

Java errors and how to fix them

Java reports problems at two different times. Compiler errors (1 to 4 below) appear before the program starts. Exceptions (5 and 6) appear while it runs. The last two produce no message at all. All output comes from OpenJDK 21, and each snippet sits inside a class with a main method.

1. error: cannot find symbol

public class Grades {    public static void main(String[] args) {        int totalScore = 0;        int[] marks = {78, 85, 92};        for (int i = 0; i < marks.length; i++) {            totalScore += marks[i];        }        System.out.println(totalscore);    } }Grades.java:8: error: cannot find symbol        System.out.println(totalscore);                           ^  symbol:   variable totalscore  location: class Grades 1 error

What it means: The compiler does not recognize a name. The symbol line says whether it was looking for a variable, a method or a class, which narrows the search.

Fix: Java is case-sensitive, so totalscore and totalScore are different names. Other common causes are a missing import (for Scanner or ArrayList), a variable declared inside a loop and used after it, and calling a method that the class does not have.

2. error: ';' expected and reached end of file while parsing

int count = 3 System.out.println(count);Grades.java:3: error: ';' expected        int count = 3                     ^

The caret shows where the semicolon belongs. A missing closing brace is harder, because the compiler only notices at the very end of the file:

public class Grades {    public static void main(String[] args) {        int count = 3;        if (count > 2) {            System.out.println(count);    } }Grades.java:7: error: reached end of file while parsing } ^

Fix: Line 7 is fine. The if on line 4 never closes. Let your editor auto-format the file and the indentation will show which block is open. This is the most frequent mistake in the Kent data and also the fastest to fix, at a median of 17 seconds.

3. error: incompatible types: possible lossy conversion from double to int

int total = 255; int average = total / 3.0;Grades.java:5: error: incompatible types: possible lossy conversion from double to int        int average = total / 3.0;                            ^

What it means: Dividing by 3.0 produces a decimal number, and an int cannot hold the decimal part. Java refuses to drop it without being told to.

Fix: Declare the result as double average. Use a cast, (int) (total / 3.0), only when you really want the decimals cut off. Watch for the opposite problem too: 255 / 2 with two int values gives 127 with no warning.

4. error: missing return statement

static String letter(int score) {    if (score >= 90) {        return "A";    } else if (score >= 80) {        return "B";    } }Grades.java:8: error: missing return statement    }    ^

What it means: The compiler checks every path through the method. A score of 70 skips both branches and reaches the end with nothing to return.

Fix: Add a final return after the last branch, or end the chain with a plain else.

5. NullPointerException

String[] names = new String[3]; names[0] = "Maya"; names[1] = "Jordan"; for (int i = 0; i < names.length; i++) {    System.out.println(names[i].toUpperCase()); }MAYA JORDAN Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.toUpperCase()" because "names[i]" is null at Roster.main(Roster.java:7)

What it means: The code called a method on something that holds no object. A new array of objects starts out full of null, and names[2] was never filled.

Fix: Read the part after "because". From JDK 15 onward the message names the exact thing that was null. Then give it a value before use, or check for null first. If your message shows <local1> where the variable name should be, compile with javac -g to get the real names.

6. ArrayIndexOutOfBoundsException

int[] marks = {78, 85, 92, 64, 70}; for (int i = 0; i <= marks.length; i++) {    System.out.println(marks[i]); }78 85 92 64 70 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5 at Roster.main(Roster.java:5)

What it means: The message gives you both numbers. The array has length 5, so its positions run from 0 to 4, and the loop asked for position 5.

Fix: Change <= to <. Every value printed before the crash, which tells you the bug is in the final pass of the loop.

7. No error: comparing strings with ==

Scanner in = new Scanner(System.in); String answer = in.nextLine(); if (answer == "yes") {    System.out.println("Access granted"); } else {    System.out.println("Access denied"); }

Type yes and the program prints Access denied.

What it means: On objects, == asks whether two variables point to the same object in memory. It does not compare the characters. The typed text and the literal "yes" are two separate objects with the same content.

Fix: Use answer.equals("yes"). This bug is confusing because == sometimes appears to work when both sides are literals in your code. In the Kent study it was one of the slowest mistakes to fix, with a median over 1,000 seconds.

8. No error: Scanner skips the next input

Scanner in = new Scanner(System.in); System.out.print("Age: "); int age = in.nextInt(); System.out.print("Name: "); String name = in.nextLine(); System.out.println("[" + name + "] is " + age);

Enter 19, then Maya, and the output is [] is 19. The program never waits for the name.

What it means: nextInt() reads the digits and leaves the Enter key press in the buffer. nextLine() then reads that leftover empty line.

Fix: Add a bare in.nextLine(); straight after nextInt() to clear the line. A cleaner habit is to read everything with nextLine() and convert with Integer.parseInt().

SQL errors and how to fix them

SQL gives you four errors with a message and three with none, and the silent three are harder to catch. All output below comes from PostgreSQL 18. MySQL words its errors differently, so we give its error code where that helps you search.

The examples use two small tables.

students

student_idnamemajoradvisor_id
1MayaCS10
2JordanCSNULL
3PriyaMath11
4LeoMathNULL

enrollments

enrollment_idstudent_idcoursegrade
11Databases91
21Algorithms84
32Databases77
43Calculus88
53Databases69

1. syntax error at or near

SELECT name, major, FROM students;ERROR:  syntax error at or near "FROM"

What it means: The database met a word it did not expect. The mistake sits just before the quoted word. Here it is the extra comma after major. MySQL reports the same thing as error 1064 and quotes the text that follows the problem.

Fix: Remove the comma. Then check the two relatives of this mistake:

  • A missing comma gives no error. SELECT name major FROM students runs and returns one column called major that holds the names. SQL reads name major as name AS major.
  • Double quotes are not for text in PostgreSQL. WHERE major = "CS" fails with column "CS" does not exist. Use single quotes for values. MySQL accepts both by default, which is why a query can work at home and fail on the course server.

2. column must appear in the GROUP BY clause

SELECT student_id, course, AVG(grade) FROM enrollments GROUP BY student_id;ERROR:  column "enrollments.course" must appear in the GROUP BY clause or be used in an aggregate function

What it means: Each group becomes one row. Student 1 has two courses, and the database has no rule for picking which one to show. MySQL raises error 1055 and mentions only_full_group_by.

Fix: Decide what the question asks. For the average per student, drop course from the SELECT. For the average per student per course, add course to the GROUP BY.

SQLite runs this query and picks a course for each student on its own. The result looks reasonable, which is how wrong grouping queries get submitted. In the Taipalus study, grouping mistakes appeared in more than 60% of queries on both grouping exercises.

3. aggregate functions are not allowed in WHERE

SELECT student_id, AVG(grade) FROM enrollments WHERE AVG(grade) > 80 GROUP BY student_id;ERROR:  aggregate functions are not allowed in WHERE

What it means: WHERE filters single rows before any grouping happens, so an average does not exist yet. MySQL calls this error 1111, "Invalid use of group function".

Fix: Filter groups with HAVING, which runs after GROUP BY.

SELECT student_id, AVG(grade) FROM enrollments GROUP BY student_id HAVING AVG(grade) > 80;

4. column reference is ambiguous

SELECT student_id, name, course FROM students JOIN enrollments ON students.student_id = enrollments.student_id;ERROR:  column reference "student_id" is ambiguous

What it means: Both tables have a student_id column and the query does not say which one to show. MySQL's version is error 1052.

Fix: Write students.student_id. Better, give each table a short alias and prefix every column whenever a query touches more than one table.

5. No error: = NULL returns nothing

SELECT name FROM students WHERE advisor_id = NULL;

This returns zero rows, although Jordan and Leo have no advisor.

What it means: NULL stands for "unknown". Comparing anything to an unknown value with = is never true, so no row passes the filter.

Fix: Use IS NULL or IS NOT NULL.

SELECT name FROM students WHERE advisor_id IS NULL;

6. No error: a missing join condition multiplies your rows

SELECT s.name, e.course FROM students s, enrollments e;

This returns 20 rows. There are only 5 enrollments.

What it means: With no join condition, the database pairs every student with every enrollment: 4 times 5. Leo, who takes no courses, appears five times.

Fix: Join on the shared key. The result drops to the correct 5 rows.

SELECT s.name, e.course FROM students s JOIN enrollments e ON e.student_id = s.student_id;

Run SELECT COUNT(*) after adding each join. If the count jumps far above what you expect, a join condition is missing or wrong.

7. No error: AND runs before OR

The task: list CS or Math students who have no advisor.

SELECT name, major FROM students WHERE major = 'CS' OR major = 'Math' AND advisor_id IS NULL;

This returns Maya, Jordan and Leo. Maya has an advisor and should not be there.

What it means: AND binds tighter than OR. The database reads the filter as "CS students, plus Math students with no advisor".

Fix: Add parentheses, or use IN. Both return Jordan and Leo.

WHERE (major = 'CS' OR major = 'Math') AND advisor_id IS NULLWHERE major IN ('CS', 'Math') AND advisor_id IS NULL

Operator mistakes like this one appeared in up to 62.2% of queries on a single exercise in the Taipalus study.

Debugging tools worth learning this semester

Print statements are fine for one or two values. Once a bug involves a loop and several variables, a debugger is faster.

LanguageToolWhat it doesUse it when
Pythonprint(f"{total=}")Prints the variable name and its value together (Python 3.8 and later)You want a quick look at one or two values
Pythonbreakpoint()Pauses the program on that line and opens pdb, the built-in debuggerYou need to step through a loop or inspect several variables
JavaIDE breakpoints in IntelliJ IDEA, Eclipse, VS Code or BlueJClick in the margin, run in debug mode, and watch every variable change line by lineYou have an exception or wrong output
JavajshellRuns a single line of Java without a class or main method (JDK 9 and later)You are unsure what a method returns
SQLBuild the query in stagesStart with SELECT * from one table, then add one join or filter at a time and check the row countThe query runs and the result is wrong
AnyExplain the code aloud, line by lineForces you to state what each line does, which exposes the line you cannot explainYou have been stuck for 15 minutes

Five pdb commands are enough to start: n runs the next line, s steps into a function, p total prints a value, c continues to the next breakpoint, and q quits.

Before you submit

Code that runs once on your machine is not finished. Go through this list before every submission.

  • Run it from a clean start. Restart the Python kernel or recompile every Java file. Old variables and stale class files hide bugs.
  • Run the sample input from the assignment sheet. Compare your output with the expected output character by character. Autograders check spacing, capital letters and line breaks.
  • Test the edges. Try empty input, a single item, zero, a negative number and the largest value the task allows.
  • Remove debugging leftovers. Delete extra print lines and any input() or nextLine() call the task did not ask for.
  • Check the names. File names, class names and function names must match the specification exactly. In Java, a public class must sit in a file with the same name.
  • Check SQL results by count. Confirm the number of rows makes sense, then look at how your query treats NULL values.
  • Read the rubric one more time. Marks are often lost on a missing comment header or the wrong file format, long after the bug is fixed.

When to stop and ask for help

Give a single error 30 minutes. If you have run out of new ideas by then, more time alone rarely helps, and asking is the efficient move.

A good request for help has four parts:

  1. The smallest piece of code that still shows the problem.
  2. The full error text, copied and pasted. A paraphrase such as "it says something about null" hides the detail a helper needs.
  3. What you expected to happen.
  4. What you have already tried.

Take those four things to office hours, your teaching assistant or the course forum. Writing them down solves the problem surprisingly often, because step 3 forces you to state your assumption.

If you use an AI assistant, check your course policy first. Ask it to explain the error message, not to rewrite your file. You still have to explain every line you submit.

If the deadline is close and you are still stuck, we can help. Send your assignment brief and your code to AssignmentDude. One of our programmers will find the bug and explain what went wrong, so the next one costs you less time.

Frequently asked questions

What is the most common error in programming assignments?

In Java, it is mismatched brackets, braces or quotes. A University of Kent study of 37 million student compilations counted 793,232 of them in one year. By error message, Java students see "cannot find symbol" most. In Python, "SyntaxError: invalid syntax" comes first and "NameError: name is not defined" second.

What is the difference between a syntax error, a runtime error and a logic error?

A syntax error breaks the rules of the language, so the program will not start. A runtime error, or exception, stops a program that has already started, for example when it divides by zero. A logic error produces no message. The program runs to the end and gives the wrong answer.

Why does the error message point to the wrong line?

The message marks the place where the language could no longer make sense of your code. That is often one line after the real mistake. A missing bracket, quote, colon or semicolon on line 11 is usually reported on line 12, so check the line above the one named.

How do I debug code that runs but gives the wrong answer?

Pick a small input where you can work out the correct answer by hand. Write down the value you expect a key variable to have at one point in the program. Print that variable or stop there in a debugger. The first place where the real value differs from your expectation is where the bug is.

Why does my code work on my computer but fail the autograder?

The three usual causes are output format, input handling and environment. Autograders compare output exactly, so an extra space or prompt can fail a test. Reading more input than the test provides raises errors such as Python's EOFError. A different language version or a hard-coded file path on your machine can also break the run.

How long should I try to fix a bug before asking for help?

About 30 minutes on a single error is a sensible limit. If you have no new idea to test by then, prepare the smallest code that shows the problem, the full error text, what you expected and what you tried, and take it to office hours or the course forum.

Similar Reads

Browse topics →

More in How To

Browse all in How To →

Discussion (0 comments)

0 comments

No comments yet. Be the first!