Top 10 Python Errors & How to Fix Them — CBSE AI Students Guide

Your program was working five minutes ago. Now it crashes with a red error message you have never seen before. This guide covers the 10 most common Python errors CBSE AI students encounter — what causes each one, what the error message actually means, and exactly how to fix it.

Bookmark this page before your practical exam.

What You’ll Learn

  • The 10 most common Python errors in CBSE AI practicals — by name and cause
  • How to read an error message (most students skip the most useful part)
  • The exact fix for each error — tested and working
  • A pre-submission checklist to catch errors before your teacher does

How to Read a Python Error Message

Before the list of errors, learn this skill — it will save you hours.

When Python crashes, it shows a traceback followed by the error type and message. Most students read only the last line. Read the second-to-last line first — it shows the exact line of code that caused the crash.

Traceback (most recent call last):
  File "program.py", line 5, in <module>
    marks = int(input("Enter marks: ")
                                      ^
SyntaxError: '(' was never closed

Here: line 5 is where the problem is. The ^ arrow points to the exact character. The last line says SyntaxError: '(' was never closed — that is the fix: add a closing ).


Error 1: SyntaxError

What it means: You wrote something Python cannot understand — a typo, a missing bracket, or a wrong keyword.

Common causes:

python

# Missing closing bracket
print("Hello"           # SyntaxError: '(' was never closed

# Missing colon after if/for/while/def
if marks > 33           # SyntaxError: expected ':'
    print("Pass")

# Using = instead of == in a condition
if marks = 90:          # SyntaxError: invalid syntax
    print("Excellent")

Fix:

python

print("Hello")          # ✅ closed bracket

if marks > 33:          # ✅ colon at end
    print("Pass")

if marks == 90:         # ✅ double equals for comparison
    print("Excellent")

Quick rule: Every if, for, while, def, and class line must end with a colon. Every opening bracket (, [, { must have a matching closing bracket.


Error 2: IndentationError

What it means: Python uses spaces (indentation) to define code blocks. An IndentationError means your indentation is inconsistent or missing.

python

# Missing indentation inside if block
if marks > 33:
print("Pass")           # IndentationError: expected an indented block

# Mixed tabs and spaces
if marks > 33:
    print("Pass")       # 4 spaces
	print("Good")       # 1 tab — IndentationError: unexpected indent

Fix:

python

if marks > 33:
    print("Pass")       # ✅ 4 spaces consistently
    print("Good")       # ✅ same 4 spaces

Golden rule: Use 4 spaces for every level of indentation. Never mix tabs and spaces in the same file. In Jupyter Notebook, pressing Tab automatically inserts 4 spaces — use it consistently.


Error 3: NameError

What it means: You used a variable or function name that Python doesn’t recognise — usually because it was never defined, or has a typo.

python

print(marks)            # NameError: name 'marks' is not defined
# Fix: define the variable first
marks = 85
print(marks)            # ✅

# Typo in variable name
total = 100
print(totla)            # NameError: name 'totla' is not defined
print(total)            # ✅ correct spelling

Common in practical file programs: Defining a variable in one cell but trying to use it in another cell after restarting the Jupyter kernel. When you restart the kernel, all variables are wiped — you must run the cells in order from the top.


Error 4: TypeError

What it means: You tried to perform an operation on the wrong type — adding a number to a string, for example.

python

# Trying to add user input (string) to a number
age = input("Enter age: ")      # input() returns a STRING
next_year = age + 1             # TypeError: can only concatenate str (not "int") to str

# Fix: convert input to int first
age = int(input("Enter age: "))
next_year = age + 1             # ✅ 
print("Next year age:", next_year)

python

# Calling a non-callable as a function
marks = 85
marks()                 # TypeError: 'int' object is not callable
# Fix: marks is a variable, not a function — don't add ()
print(marks)            # ✅

The #1 cause of TypeError in CBSE practicals: Forgetting to wrap input() with int() or float(). Every input from a user arrives as text. Always convert it before doing maths.


Error 5: ValueError

What it means: The type is correct but the value doesn’t make sense for that operation.

python

# Trying to convert text to int
marks = int("eighty-five")      # ValueError: invalid literal for int() with base 10: 'eighty-five'

# Trying to convert a decimal string to int
marks = int("85.5")             # ValueError: invalid literal for int() with base 10: '85.5'
# Fix: use float() first, then int() if needed
marks = int(float("85.5"))      # ✅ → 85

# numpy reshape with incompatible dimensions
import numpy as np
arr = np.array([1,2,3,4,5])
arr.reshape(2, 3)               # ValueError: cannot reshape array of size 5 into shape (2,3)
# Fix: 5 elements can't fill a 2×3 grid (6 slots) — use (1,5) or add one element
arr.reshape(1, 5)               # ✅

Error 6: IndexError

What it means: You tried to access a list or array position that doesn’t exist.

python

students = ["Arjun", "Priya", "Kiran"]     # indices: 0, 1, 2
print(students[3])      # IndexError: list index out of range

# Fix: last valid index is len(list) - 1 = 2
print(students[2])      # ✅ → "Kiran"
print(students[-1])     # ✅ → "Kiran" (negative indexing from end)

Common in NumPy programs:

python

import numpy as np
arr = np.array([10, 20, 30])
print(arr[5])           # IndexError: index 5 is out of bounds for axis 0 with size 3

Quick check: Before accessing list[i], confirm i < len(list). In Python, a list of 5 elements has indices 0, 1, 2, 3, 4 — index 5 does not exist.


Error 7: ModuleNotFoundError

What it means: You tried to import a library that is not installed in your Python environment.

python

import numpy as np         # ModuleNotFoundError: No module named 'numpy'

Fix — in Jupyter Notebook:

python

# Run this in a cell to install the missing library
import subprocess
subprocess.run(["pip", "install", "numpy"])

Then restart the kernel and re-import.

Fix — in Anaconda Prompt / Terminal:

pip install numpy
pip install pandas
pip install matplotlib
pip install opencv-python
pip install scipy

Why this happens at school: School computers sometimes have a different Python environment than where Anaconda was installed. Confirm with your teacher that you are running the correct kernel in Jupyter — check the top right corner of Jupyter Notebook for the kernel name (should say “Python 3” or similar).


Error 8: AttributeError

What it means: You called a method or attribute on an object that doesn’t have it — usually because the variable type is not what you expect.

python

# Calling a list method on an integer
x = 42
x.append(10)            # AttributeError: 'int' object has no attribute 'append'

# Calling a string method on a number
marks = 85
print(marks.upper())    # AttributeError: 'int' object has no attribute 'upper'

Common in Pandas programs:

python

import pandas as pd
df = pd.read_csv("data.csv")
df.Head()               # AttributeError: 'DataFrame' object has no attribute 'Head'
# Fix: Python is case-sensitive
df.head()               # ✅ lowercase

Rule: Python method names are case-sensitive. df.Head() is not the same as df.head(). When you see object has no attribute, check the spelling and case of the method name first.


Error 9: FileNotFoundError

What it means: Python cannot find the file you referenced — usually a CSV or image file.

python

df = pd.read_csv("rainfall.csv")
# FileNotFoundError: [Errno 2] No such file or directory: 'rainfall.csv'

Why it happens: The file exists on your computer, but not in the folder Jupyter Notebook is looking in.

Fix — find where Jupyter is looking:

python

import os
print(os.getcwd())      # Prints the current working directory

Move your CSV file to that folder. Or provide the full file path:

python

df = pd.read_csv(r"C:\Users\Arjun\Documents\AI_Practicals\rainfall.csv")

The r before the string makes it a raw string — necessary on Windows where backslashes would otherwise be interpreted as escape characters.

For images in OpenCV:

python

import cv2
img = cv2.imread("photo.jpg")
print(img)              # prints None if file not found — OpenCV doesn't raise an error, it returns None
if img is None:
    print("Image not found — check file name and location")

Error 10: ZeroDivisionError

What it means: Your code tried to divide a number by zero.

python

# Direct division by zero
result = 10 / 0         # ZeroDivisionError: division by zero

# Hidden division by zero — common in average calculations
total_marks = 0
num_students = 0
average = total_marks / num_students    # ZeroDivisionError if num_students = 0

Fix — add a guard condition:

python

if num_students > 0:
    average = total_marks / num_students
    print("Average:", average)
else:
    print("No students to calculate average for.")

This appears in CBSE practical programs that calculate averages or percentages from user input — if a student accidentally types 0 for the denominator, the program crashes without a guard.


Pre-Submission Checklist

Run through this before submitting your practical file or sitting the Lab Test:

  • Every program has a # Program to... comment at the top
  • All library imports are at the top of the cell/file (import numpy as np)
  • input() values are converted with int() or float() before calculations
  • All indentation uses 4 spaces consistently — no mixed tabs
  • Every if, for, while line ends with a colon :
  • Variable names are spelled consistently throughout (no marks vs Marks)
  • CSV and image files are in the same folder as the notebook
  • All programs have been run and output is visible below the code cell
  • No cell shows [*] on the left — that means it’s still running or crashed

Quick Revision Box

ErrorOne-Line CauseQuick Fix
SyntaxErrorPython can’t understand the code — typo, missing : or bracketCheck for missing colons and unclosed brackets
IndentationErrorWrong spacing inside if/for/while blocksUse exactly 4 spaces consistently
NameErrorVariable used before being definedDefine the variable first; check spelling
TypeErrorWrong data type for an operationWrap input() with int() or float()
ValueErrorRight type, wrong valueCheck what values the function accepts
IndexErrorList/array position doesn’t existCheck that index < len(list)
ModuleNotFoundErrorLibrary not installedpip install library-name in terminal
AttributeErrorMethod doesn’t exist on that objectCheck spelling and case of method name
FileNotFoundErrorFile not in current folderRun os.getcwd() and move file there
ZeroDivisionErrorDividing by zeroAdd if denominator > 0: guard

Practice Questions

Q1 (2 marks): A student writes the following code and gets a TypeError. Identify the error and write the corrected code.

python

marks = input("Enter marks: ")
percentage = (marks / 100) * 100
print(percentage)

Model Answer: The error occurs because input() returns a string, and you cannot divide a string by a number. Fix: convert the input to a float first.

python

marks = float(input("Enter marks: "))
percentage = (marks / 100) * 100
print(percentage)

Q2 (MCQ): Which error occurs when you try to access mylist[10] but the list only has 5 elements?

a) TypeError b) ValueError c) IndexError d) NameError

Answer: c) IndexError — the index 10 is outside the valid range (0 to 4) for a 5-element list.


Frequently Asked Questions

Q1: My program runs in IDLE but crashes in Jupyter Notebook. Why? The most common reason: different Python environments. IDLE uses the system Python while Jupyter uses the Anaconda Python. A library installed for one may not be available in the other. Always use Jupyter Notebook for CBSE practicals (the CBSE-recommended tool) and install all libraries through Anaconda.

Q2: I get a red error message but the output still appears. Is that a problem? It depends. Some warnings appear in red but are not errors — they do not stop execution. True errors (the ones listed here) stop your program and show “Error” in the message. If your output is correct despite a red message, check if it says Warning rather than Error. Warnings are usually safe to ignore for CBSE practicals, but mention them in your Viva if asked.

Q3: How do I fix an error I have never seen before? Copy the last line of the error message (e.g., AttributeError: 'NoneType' object has no attribute 'shape') and search it on Google exactly as written. Python errors are extremely well documented — you will almost always find the answer within the first two results.


Read Next