EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

Python NameError

Home » Software Development » Software Development Tutorials » Python Tutorial » Python NameError

Python NameError

Introduction to Python NameError

The following article provides an outline for Python NameError. NameError is a kind of error in python that occurs when executing a function, variable, a library or a string without quotes that have been typed in the code without any previous Declaration. In other words when the global or a local name cannot be identified by the interpreter upon execution throws a NameError. It can be viewed in the last line of the error message to understand the NameError where the function, variable, package or string that has not been declared will be shown in the message saying the respective function, package, variable “is not defined”.

Syntax of Python NameError

When writing a function with a name we often miss to call the exact function name in the future which will lead to a NameError.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Example:

Code:

## Functions which return values
def calc_sum(x,y):
op = x + y
return(op)
ss = calc_sum(5,10)
print(ss)

Output:

Python NameError 1

For the same function lets see the NameError.

Code:

## Functions which return values
def calc_sum(x,y):
op = x + y
return(op)
ss = calc_su(5,10)
print(ss)

Output:

Python NameError 2

It was originally written to perform some operation between two numbers and named as calc_sum but upon calling it we used the name calc_su so it is not defined previously and it will throw us a NameError.

How NameError Works?

When working with user-defined variables in coding the NameError often occurs due to the difficulty in identifying the local/global values for the interpreter.

Popular Course in this category
Python Training Program (36 Courses, 13+ Projects)36 Online Courses | 13 Hands-on Projects | 189+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.8 (8,318 ratings)
Course Price

View Course

Related Courses
Programming Languages Training (41 Courses, 13+ Projects, 4 Quizzes)Angular JS Training Program (9 Courses, 7 Projects)

Example:

Code:

l1 = [1,2,5,8,9] l2 = [1,5.6,"hello"] # mix of data types
l1[1] = 100 # muting the 1st position of l1 to 100
print(l1)
del l1[2] # delete from a position 2
print(l1)

Output:

Python NameError 3

Code:

l1 = [1,2,5,8,9] l2 = [1,5.6,"hello"] # mix of data types
l1[1] = 100 # muting the 1st position of l1 to 100
print(l1)
del l[2] # delete from a position 2

Here we are performing a delete operation on a variable l that is not defined.

Only l1 & l2 have been defined and the interpreter can only identify l1 & l2 variables. So if we operate on l which is not defined it will throw us a NameError.

Output:

Python NameError 4

There are cases of NameError that also occurs during operations done with python library or a package. Where if we miss to import the package or library or if we haven’t defined the name of that package or library and upon executing an operation using that library, we will get a NameError

Example:

Code:

l10 = [1,2,6,7,4,5,7,8,6,3] l11 = [1,2,6,7,4,5,7,8,6,3,1000] ## numpy operations
np.mean(l11)
np.median(l11)
np.std(l11)

Output:

Python NameError 5

We haven’t imported the numpy library as np and upon executing the operation we will the NameError.

Code:

import numpy as np
l10 = [1,2,6,7,4,5,7,8,6,3] l11 = [1,2,6,7,4,5,7,8,6,3,1000] ## numpy operations
print(np.mean(l11))
print(np.median(l11))
print(np.std(l11))

Output:

Python NameError 6

There is another kind of NameError that occurs when we fail to insert a string value inside the quotes and the interpreter identifies it as a variable and throws a NameError.

Example:

Code:

print('Its a Beautiful day')
name=('Bala')
print(name,'Its a Beautiful day')

Output:

Python NameError 7

Code:

Error,
print('Its a Beautiful day')
name=(Bala)
print(name,'Its a Beautiful day')

Here we fail to put the string inside the quotes so the console will throw us the NameError.

Output:

fail to put the string inside the quotes

Avoiding NameErrors in Python

The NameError can be avoided easily by using the Python Error handling technique or exception handling which denotes the user about the NameError that is occurring in the block of code without actually throwing an error.

The most common errors that occur in python is the SyntaxError & NameError. When we write our code and if it is not accepted by the programming language, then arises the SyntaxError. SyntaxError can be corrected by following the guidelines of the programming language in a way the interpreter could understand. The NameError can be avoided by using a technique called Exception Handling.

Code:

defmy_func():
x="Name Error Exception"
print(y)
my_func()

Output:

Python NameError 9

Even if we write code without any SyntaxError, the program can result in runtime errors. These are called Exceptions. There are numerous built-in exceptions available in Python and One such exception is NameError Exception.

In Python, the NameError exception comes into picture when we try to use or refer a name that is not defined locally or globally.

Example:

For NameError Exception handling.

Code:

try:
x="Name Error Exception"
print(y)
except NameError:
print("Name Error Exception is Caught")

Output:

Exception is caught

The try block allows us to check and see that our code will throw an error or not. We can use this block to trail our code to see if there may be potential for errors to occur.

The Except Block will allow us to write the part where we want to handle the error. We can use this block to denote the user on want went wrong without the console throwing errors.

We can also use a Finally block along with try and except to continuously run the code without termination by indicating only the exception message.

Example:

Finally block.

Code:

name='Smith'
try:
print("Hello" " "+ name)
except NameError:
print("Name is not denoted")
finally:
print("Have a nice day")

Output:

Finally block

Since the name is denoted the code has successfully run without throwing the exception.

Below we have deleted the name denoted we can see the exception message thrown.

Code:

name='Smith'
try:
print("Hello" " "+ name)
except NameError:
print("Name is not denoted")
finally:
print("Have a nice day")
del name
try:
print("Hello " + name)
except NameError:
print("Name is not denoted")

Output:

we can see the exception message thrown

The finally block allows us to run the code without termination since the name denoted is deleted. The finally blocks will get executed even if the try block raises an exception message. We can use this technique to overcome the NameError.

Conclusion

The main take away to remember in python NameError is the failure of the interpreter to identify the name or text we have used in our code. We have seen in detail about the NameError that occurs in Python programming language and the techniques to overcome the NameError.

Recommended Articles

This is a guide to Python NameError. Here we discuss how NameError works and avoiding NameErrors in python respectively. You may also have a look at the following articles to learn more –

  1. Python Input String
  2. Python String Operations
  3. Python Sort List
  4. Python Constants

Python Training Program (36 Courses, 13+ Projects)

36 Online Courses

13 Hands-on Projects

189+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
Python Tutorial
  • Exception
    • Python Exception Handling
    • Custom Exception in Python
    • Indentation Error in Python
    • Python IOError
    • Python EOFError
    • Python NotImplementedError
    • Python TypeError
    • Python ValueError
    • Python AssertionError
    • Python Unicode Error
    • Python NameError
    • Python StopIteration
    • Python OverflowError
    • Python KeyboardInterrupt
  • Basics Part I
    • Introduction To Python
    • What Is Python
    • Careers in Python
    • Advantages of Python
    • Uses of Python
    • Python Features
    • Python Fast And python psyco
    • Python ImportError
    • Benefits and Limitations of Using Python
    • What can I do with?Python
    • Is Python a scripting language
    • Is Python Object Oriented
    • Is Python Open Source
    • Python Socket Programming
    • Useful Tips on Python Programming
    • Python You Should Be Using It
    • Python Web Development
    • Python Programming Beginners Tutorails
    • Practical Python Programming for Non-Engineers
    • Python Programming for the Absolute Beginner
    • Versions of?Python
  • Basic Part II
    • Comments in Python
    • Finally in Python
    • Python Multiline Comment
    • Python Data Types
    • Python Variables
    • Python Variable Types
    • Python Global Variable
    • Python Variable Scope
    • Python Private Variables
    • Python Default Arguments
    • Python Command-line Arguments
    • Indentation in Python
    • Object in Python
    • Python Keywords
    • Python Literals
    • Pointers in Python
    • Iterators in Python
    • Python User Input
    • Python Enumerate
    • Python Commands
    • Type Casting in Python
    • Python Identifiers
    • Python Constants
    • What is NumPy in Python?
    • Cheat Sheet Python
  • Frameworks
    • Python Frameworks
    • Python Compilers
    • Python Editors
    • Best Compiler for Python
    • Python IDE for Windows
    • Python IDE on Linux
  • Installation
    • How To Install Python
    • Install Python on Linux
    • Install Python on Windows
    • Install Anaconda Python
  • Operator
    • Python Operators
    • Arithmetic Operators in Python
    • Python Comparison Operators
    • Logical Operators in Python
    • Assignment Operators in Python
    • Unary Operators in Python
    • String Operators in Python
    • Boolean Operators in Python
    • Identity Operators in Python
    • Python Bitwise Operator
    • Python Remainder Operator
    • Python Modulus Operator
  • Control Statement
    • Conditional Statements in Python
    • Control Statements in Python
    • If Condition in Python
    • If Statement in Python
    • If Else Statement in Python
    • else if Statement in Python
    • Nested IF Statement in Python
    • Break Statement in Python
    • Python Switch Statement
  • Loops
    • Loops in Python
    • For Loop in Python
    • While Loop in Python
    • Do While Loop in Python
    • Python Nested Loops
    • Python Infinite Loop
    • Python Event Loop
  • Sorting
    • Sorting in Python
    • Sorting Algorithms in Python
    • Bubble Sort in Python
    • Merge Sort in Python
    • Heap Sort in Python
    • Quick Sort in Python
    • Python Sorted Function
  • Function
    • Python Built-in Functions
    • Math Functions in Python
    • Python String Functions
    • Trigonometric Functions in Python
    • Python Input Function
    • Python Input String
    • Python String Operations
    • Python Stream
    • Python Multiline String
    • Python Regex
    • Python Regex Tester
    • Python regex replace
    • Python File Methods
    • Python Import CSV
    • Python Read CSV File
    • Python write CSV file
    • Python Delete File
    • Python File readline
    • Python if main
    • Python Main Method
    • List Method in Python
    • Python List Length
    • Recursive Function in Python
    • Copy List in Python
    • Python Range Function
    • Python Substring
    • Python list remove()
    • Python List Index
    • Python Set Function
    • Python len Function
    • Python eval()
    • Python Counter
    • ord Function in Python
    • strip Function in Python
    • Split Function in Python
    • Python Round Function
    • Python Map Function
    • Python String Join
    • Python format() Function
    • Python Contextlib
    • Python Compare Strings
    • Python Return Value
    • Python List count
    • Filter in Python
    • Python Slice String
    • Python Absolute Value
    • Python Trim String
    • Python Type Function
    • Lowercase in Python
    • Python xrange
    • Python yield
    • Python Find String
    • Max Function in Python
    • Python Power Function
    • pop() in Python
    • Python argparse
    • Python Pickle
    • Python Zip Function
    • Python Split String
    • super() in Python
    • Python Extend
    • Python String Replace
    • Python PEP8
    • Python Filter Function
    • Python if then else
    • Lambda in Python
    • Python BeautifulSoup
    • Python Sleep
    • Python Function Generator
    • Python @classmethod decorator
    • Python Endswith
    • Python BufferedReader
    • Python Async
    • Python Parser
    • Python SystemExit
    • Python pip
    • Python kwargs
  • Array
    • Arrays in Python
    • 2D Arrays In Python
    • 3d Arrays in Python
    • Multidimensional Array in Python
    • Python Array Functions
    • String Array in Python
    • Python Sort Array
    • Python Array Length
  • Inheritance
    • Inheritance in Python
    • Single Inheritance in Python
    • Multiple Inheritance in Python
    • Interface in Python
  • Advanced
    • Scope in Python
    • Python Collections
    • Constructor in Python
    • Destructor in Python
    • Python Overloading
    • Overriding in Python
    • Function Overloading in Python
    • Method Overloading in Python
    • Operator Overloading in Python
    • Method Overriding in Python
    • Encapsulation in Python
    • Static Method in Python
    • Assert in Python
    • Python References
    • Python Virtualenv
    • Python mkdir
    • Logistic Regression in Python
    • Dictionary in Python
    • Regular Expression in Python
    • Python Import Module
    • Python OS Module
    • Python Sys Module
    • Python Generators
    • Abstract Class in Python
    • Python File Operations
    • Sequences in Python
    • Stack in Python
    • Queue in Python
    • Tuples in Python
    • Python Magic Method
    • Python Sets
    • Python Set Methods
    • Priority Queues in Python
    • Reverse Engineering with Python
    • String Formatting in Python
    • Python isinstance
    • String Length Python
    • Python Concurrency
    • Python List
    • Python Initialize List
    • Python Unique List
    • Python Sort List
    • Python Reverse List
    • Python Empty List
    • List Comprehensions Python
    • List Operations in Python
    • Python Database Connection
    • Python SQLite
    • Python SQLite Create Database
    • Send Mail in Python
    • Bash Scripting and Python
    • Violent Python Book
    • NLP in Python
    • Matplotlib In Python
    • Gray Hat Python: Security
    • Python Subprocess
    • Python Threading Timer
    • Python Threadpool
    • Python Statistics Module
    • How to Call a Function in Python?
    • Python Curl
    • JSON in Python
    • Python json.dumps
    • Python Turtle
    • Python Unit Test
    • pass Keyword in Python
    • Tokenization in Python
    • Random Module in Python
    • Python Multiprocessing
    • Python getattr
    • Collection Module in Python
    • Print Statement in Python
    • Python Countdown Timer
    • Python Context Manager
    • File Handling in Python
    • Python Event Handler
    • Python Print Table
    • Python Docstring
    • Python Dictionary Keys
    • Python Iterator Dictionary
    • Python Class Attributes
    • Python Dictionary Methods
    • Namedtuple Python
    • Namedtuple Python
    • Namedtuple Python
    • Python Class Constants
    • Python Validation
    • Python Switch Case
    • Python Rest Server
    • Python Yield vs Return
    • Python Pickle vs JSON
  • Tkinter
    • Tkinter Widgets
    • Python Tkinter Button
    • Python Tkinter Canvas
    • Tkinter Frame
    • Tkinter LabelFrame
    • Python Tkinter Label
    • Tkinter Scrollbar
    • Tkinter Listbox
    • Tkinter Spinbox
    • Tkinter Checkbutton
    • Tkinter Menu
    • Tkinter Menubutton
    • Tkinter OptionMenu
    • Tkinter Messagebox
    • Tkinter Grid
    • Python Tkinter Entry
    • Tkinter after
    • Tkinter Colors
    • Tkinter Font
    • Tkinter PhotoImage
    • Tkinter TreeView
    • Tkinter Notebook
    • Tkinter Bind
    • Tkinter Icon
    • Tkinter Window Size
    • Tkinter Color Chart
    • Tkinter Slider
    • Tkinter Calculator
  • Programs
    • Patterns in Python
    • Star Patterns in Python
    • Swapping in Python
    • Factorial in Python
    • Fibonacci Series in Python
    • Reverse Number in Python
    • Palindrome in Python
    • Random Number Generator in Python
    • Prime Numbers in Python
    • Armstrong Number in Python
    • Strong Number in Python
    • Leap Year Program in Python
    • Square Root in Python
    • Python Reverse String
    • Python Object to String
    • Python Object to JSON
    • Python Classmethod vs Staticmethod
  • Python 3
    • Python 3 Commands
    • Python 3 cheat sheet
  • Interview Question
    • Python Interview Questions And Answers

Related Courses

Python Certification Course

Programming Languages Courses

Angular JS Certification Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - Python Training Program (36 Courses, 13+ Projects) Learn More