QuizCure
Find Available Solution Here!

Learn cause for Traceback (most recent call last): with a possible Fix

Deepak Nov 21, 2024

Disclosure: This post may include affiliate links which means we will get a commission if you purchase through my links.

The term traceback references to an error message produced by Python code that throws an exception. It gives us traceback details on problems brought on by a specific piece of code.Stack traces are exceptions that are also thrown by other programming languages like Java, etc. We may troubleshoot these exceptions by looking at the file name, line number, and executed code block details (function, params, or another statement).

Developers have to be aware of issues to use traceback, which contains details such as file name, function call, line number, and exception name. Beginners may find traceback difficult to understand at first, but it is a useful learning way of understanding the issue with the reported mistake and fixing it appropriately.

In Python, it's good to go through errors reported from bottom to top.

Let's understand Traceback (most recent call last): with the following example:

def introduce():
	return "Hello, I'm Test python script"
print(introduces())

Result:

  File "test.py", line 4, in <module>
    print(introduces())
NameError: name 'introduces' is not defined

Explanation: Here introduces() function is not defined in the program. This kind of error generally causes spelling/typing mistakes.

Now let's understand the traceback error report in detail:
Throw Traceback error message as below:
Line 1: File "test.py", line 5, in
Exception caused at line number 5 of script test.py
Line 2: print(introduces())
Pointing code from where issue generated
Line 3: NameError: name 'introduces' is not defined
Contains traceback Exception name as NameError With error message as the name 'introduces' is not defined which is self-explanatory.

Note. NameError is reported if Python tries to evaluate a variable, function, disc, etc. which is not defined but used in the code block. Like in the above program, it tries to evaluate introduces function but this function does not exist.

Traceback most recent call last in python

Let's explore some common exceptions we met during program execution such as:

IndexError: list index out of range

When we attempt to retrieve items from the list using an index that does not exist, an exception for index out of range is raised.

List index out of range is demonstrated by the code below.

employee = ["John", "Peter", "Alex", "Camren"]
print(employee[4])
    

Result:

Traceback (most recent call last):
  File "test.py", line 2, in <module>
    print(employee[4])
IndexError: list index out of range

    

Explanation: IndexError is an exception with the message index out of range . The software attempts to retrieve items from the employee list at index 4, yet the employee list has a length of 4 and an index range of 0 to 3. When trying to run code employee[4], it complains that index 4 does not contain any items.

.

Traceback (most recent call last): return error report containing line number, error name and relevant error message to identify the problem and apply fix accordingly.

Solution:

To avoid this index out-of-range issue we can check the condition before attempting index value

def getEmployee(index):
	employee = ["John", "Peter", "Alex", "Camren"]
	if(len(employee) <= index):
	 return "Index out of range"
	else:
	  return employee[index]

print(getEmployee(4))

    

Explanation:

Here we have a function getEmployee that receives the index as an argument and returns the employee name based on a passing index. Condition len(employee) <= index checks whether the received index is greater than or equal to the length of the employee list. If the index is larger than the list length then it returns the message Index out of range else returns the employee name.

Browse Coursera's catalog of free and paid courses. Enroll in the courses that you prefer to learn.

KeyError in the dictionary

KeyError is raised when we try to fetch an item usually from a dictionary that doesn't exist.

Let's understand with the following example code

def getEmployee(index):
	employee = {"J" : "John", "p" : "Peter", "A" : "Alex", "C" : "Camren"}
	return employee[index]

print(getEmployee("J"))

    

Result: John

Exaptation: All good. We have values associated with passing key J and return value as John.

What if we call the same function with another key that doesn't exist? Evaluate for the key K as below

def getEmployee(index):
	employee = {"J" : "John", "p" : "Peter", "A" : "Alex", "C" : "Camren"}
	return employee[index]

print(getEmployee("K"))

    

Result:

Traceback (most recent call last):
  File "test.py", line 5, in <module>
    print(getEmployee("K"))
  File "test.py", line 3, in getEmployee
    return employee[index]
KeyError: 'K'
    

Explanation: It raised Traceback (most recent call last): error report as KeyError and notifying us about key 'K' with some details about function call and line number.

Solution: We can avoid KeyError issues by applying the required condition before fetching dictionary elements as below

def getEmployee(key):
	employee = {"J" : "John", "P" : "Peter", "A" : "Alex", "C" : "Camren"}
	if key not in an employee:
	  return "Key Doesn't exist!"
	else:
	  return employee[key]

print(getEmployee("K"))
    

Result: Key Doesn't exist!

Explanation: Condition key not in employee checks whether a received key exists in a dictionary or not.

If it exists, it returns relevant value to the calling function otherwise it returns a user-defined message Key Doesn't exist!

Modulenotfounderror (ImportError: No module named requests )

ImportError is raised when the Python interpreter can't find the imported package in the Python script. There can be multiple reasons behind Modulenotfounderror such as

  • Spelling/Typing mistake in the imported module name
  • The included package is not installed
  • The interpreter can't find the path of the included module.

The following example program demonstrates Modulenotfounderror

import requests
x = requests.get('https://www.quizcure.com')
print(x.status_code)
    

Result:

Traceback (most recent call last):
  File "test.py", line 1, in <module>
    import requests
ImportError: No module named requests
    

Explanation:

Since requests are not installed on my server while using the get function from requests package it complains and throws an exception as ImportError with the error message No module named requests.

Solution:

Install requests package.

pip install requests

NameError (undefined name error)

NameError (undefined name error) is generally caused due to following common reasons

  • Misspelled builtIn function name or user-defined function
  • Human errors typing while defining variable name, module name, and class name within the local or global scope.
  • Accessing variables is out of its scope

Let's understand with below program

Misspelled builtin function name or user-defined function

employee = ["John", "Peter", "Alex", "Camren"]

def getEmployee(index):
	if(len(employee) <= index):
	 return "Index out of range"
	else:
	  return employee[index]

print(getEmploye(2))
 

Result: NameError: name 'getEmploye' is not defined

Explanation: As we can see, the calling function in print is getEmploye instead of getEmployee. Therefore it raised a NameError here.

Undefined param name:

Below program demonstrates NameError for undefined variable

var = 'hello'
print(va)
 

Result: NameError: name 'va' is not defined

Explanation; Here we are trying to access variable va that is not defined in the program

Accessing variable is out of its scope:

Let's understand with a below simple example

def inner():
  x = "inner Function"

print(x)
 

Result: NameError: name 'x' is not defined

What above code mean:

This inner variable x defined inside the function is only accessible within the function scope because it is a local variable for function inner therefore it raises NameError while accessing outside of the function scope.

TypeError

TypeError occurs when trying to execute an inappropriate object type operation. Following are common causes behind TypeError:

  • Performing non-identical object-type operations.
  • Using string indices to access list elements instead of integers or slices.
  • Treating non-callable object as callable.

Performing non-identical object type operations.

def sum(num):
    print (num + 5)

sum("test")
 

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

Explanation:

  • Created function sum to add received number to integer 5. Therefore function expects a num argument as an integer value.
  • Passing the string value test while calling function sum here causes TypeError with the self-explanatory message as can only concatenate str.

To fix this issue We need to ensure the same object-type operation while adding numbers or concatenating strings.

Therefore following two programs will work fine:

def sum(num):
    print (num + "5")

sum("test")

Result: test5

def sum(num):
    print (num + 5)

sum(10)
 

Result: 15

Using string indices to access list elements instead of integers or slices

employee = ["John", "Peter", "Alex", "Camren"]

print(employee["1"])

Result: TypeError: list indices must be integers or slices, not str

Explanation:

  • Define a list of names.
  • Trying to access a list with string indices "1". We can see the result as it complains and raises TypeError with message list indices must be integers or slices, not str

To fix this issue we need to access a list with integer values.

print(employee[1])

Will print: Peter

Treating the non-callable object as callable

Let's understand with the below example code

txt = "hello"

def demo():
    global txt
    txt = "there"


demo()
print(txt())

Result: TypeError: 'str' object is not callable

Explanation:

  • Let's suppose we have a function demo that is modifying the global variable txt value within a function block.
  • Calling demo function to set global param with new value there Now here we trying to print txt and treat it as callable which complains and raises TypeError with an error message as the 'str' object is not callable

To fix, just print txt like

print(txt)

Result: there

How to fix Traceback File error?

The most frequent problem caused by utilizing inaccurate Python versions to parse strings is this one. In order to fix the issue, please verify that the Python function being used to read the expression is compatible with the current Python version.

Using the input function to read a string often leads to problems

Python version < 3.x

Use raw_input() rather than input() function to read strings since the input function will evaluate any expression supplied to it and will consequently throw an error while raw input won't.

With Python 3.x

When using Python 3.x, you can use the input function, which is equivalent to raw input in Python 2.x.

Was this post helpful?

Send Feedback

Practice Multiple-Choice Questions

  • ?
    What will be the result for the following code?
    print(me)
    me="hello"
    
    Options are:
  • ?
    What is the output for the following code?
    def getEmployee(index):
    	employee = {"J" : "John" "p" : "Peter", "A" : "Alex", "C" : "Camren"}
    	return employee[index]
    
    print(getEmployee("J"))
    
    Options are:
    Try your hand at more Multiple-choice Exercises

Connect With QuizCure


Follow Us and Stay tuned with upcoming blog posts and updates.

Contributed By

Deepak

Deepak

QC STAFF
51 Posts
  • PHP
  • JAVA
  • PYTHON
  • MYSQL
  • SEO

You May Like to Read

Scroll up