×

Is Python Case-sensitive when Dealing with Identifiers

Yes, Python is a case-sensitive language while dealing with identifiers. Python is one of the top trending, widely-used programming languages. Python is a general-purpose programming language. It is a case-sensitive programming language, which means javatpoint and Javatpoint are not the same; they both are different in Python.

In this article, you will learn about that Python is a case-sensitive language. But before learning this, we should know what identifiers are, the naming rules of identifiers, the maximum length of the identifier, reserved keywords in Python, and reserved classes in python.

So first, let’s start with the identifiers in python.

What are Identifiers in Python?

An Identifier is used to identify the elements, or it is a name given to entities like variables, classes, objects, modules, functions and constants.

For any identifier, we have to follow some rules while giving a name to that particular identifier.

So let’s understand the rules of Identifiers in Python.

Naming Rules of Identifiers

  1. Variable or identifier names should not match with keywords.
  • Identifier name should start with the character [lowercase (a to z) or uppercase(A to Z)] or underscore(_). It cannot start with a digit.
  • Identifiers can be alphanumeric [combination of characters or digits (0 to 9)].
  • Variable or identifier name is case-sensitive.
  • You cannot use special characters (!,@,$,%,#, etc.) in Identifier’s name.
  • The identifier name can be of any length.

Examples of Python Valid Identifiers:

  • a0b: contains characters and numbers.
  • _xyz: starts with an underscore and contains characters.
  • a_BC: contains valid characters.
  • _: underscore is a valid identifier.
  • _1_xyz: starts with an underscore and contains characters and numbers.

Examples of Python Invalid Identifiers:

  • 98: Identifier names can’t be only digits.
  • 1xyz: Identifiers can’t start with a digit.
  • for: Identifier names should not match with keywords. And for is reserved keyword in python.
  • !xyz: Identifier names cannot start with special characters.
  • Xyz #12: The identifier’s name cannot use a special character.

How to Test if a String is a Valid Identifier?

If we want to check whether the identifier name is valid or not, then we use the string isidentifier() function.

Let’s take some examples on that and understand how to use the isidentifier() function:

Example:

#by using isidentifier() function
print("a0b".isidentifier())  
print("_xyz".isidentifier())  
print("_".isidentifier())  
print("!xyz".isidentifier())
print("98".isidentifier())  
print("xyz#1".isidentifier())

Output:

True
True
True
False
False
False

From the above example we understand that which identifier name is valid or invalid.

NOTE: If we use the isidentifier() function with reserved keywords, it will give the wrong answer because this method or function does not consider reserved keywords. So, for reserved keywords, we can use the keyword.iskeyword() function.

Maximum Length of Identifier in Python Language

Identifiers in python language can be unlimited in length. Although there is no restriction, PEP-8 recommends that you keep identifiers to a maximum of 79 characters for optimal readability.

Identifier Naming Best Practices in Python

  • Use Uppercase for the first character of each word if the class name consists of multiple words. For example, StudentData, PersonAge etc.
  • Capital letters should be used to begin class names. For example, Student, Person etc.
  • You can start the names of private variables with an underscore. For example, _personal_data etc.
  • If a function returns boolean values, it is best to start the name with "is".For example, isValid(), isPrime() etc.
  • If the names of variables, functions, and modules contain more than one word, an underscore should be used to separate them. For example, employee_name,person_age etc.
  • The initial and last characters in the identifier name shouldn't be underscored. Python's built-in types make use of it.
  • An identifier probably refers to a name defined by the language if it ends with two underscores. Avoid starting and ending your identifier name with underscores.
  • To make the purpose of identifiers clear, keep their names meaningful. For example, is_Boolean,student_name etc.
  • The identification name's length is unlimited. But make it short and clear.

Why Python is case-sensitive?

In HTML <p> and <P> are the same but in Python programming language it is not the same because we know that python language is a case-sensitive programming language, but what is the reason behind it?? Let’s understand it.

  • Because it distinguishes between identifiers like Variable and variable, Python is a case-sensitive language. It is concerned with capital letters and lowercase letters, to put it simply.
  • Python is utilised in many various subjects, hence Identifiers shouldn't be limited. In mathematics, we don't want to limit ourselves to variables and symbols, and the same is valid for Python.

Reserved Keywords in Python

In python, some words are reserved. That is called Python keywords. Python keywords have special meanings, uses and rules to use. These python keywords perform special tasks.

There are 36 reserved words in python 3.6. Below the list of python keywords of python 3.9 is given:

FalseNoneTrue__peg_parser__andas
assertasyncawaitbreakclasscontinue
defdelelifelseexceptfinally
forfromglobalifimportin
islambdanonlocalnotorpass
raisereturntrywhilewithyield

How to Check if a String is a Python Keyword?

You may use the keyword if you want to check that a particular word is a python keyword.iskeyword(string) method. If that string is a python keyword, it returns true else; it returns false. To use the keyword.iskeyword() function, you need to import the keyword module.

Example:

#import keyword module
import keyword
print(keyword.iskeyword("for")) # for is a python keyword it will returns true
print(keyword.iskeyword("Pass")) # Pass isn’t a python keyword it will return false
print(keyword.iskeyword("var")) # var isn’t a python keyword it will return false
print(keyword.iskeyword("await")) # await is a python keyword it will returns true
print(keyword.iskeyword("Lambda")) # Lambda isn’t a python keyword it will return false
print(keyword.iskeyword("Is"))# Is isn’t a python keyword it will return false
print(keyword.iskeyword("async"))async is a python keyword it will return true

Output:

True
False
False
True
False
False
True

NOTE: To know all reserved keywords, you may use keyword.kwlist.

Example:

#import keyword module
import keyword
#find all reserved keywords
print(keyword.kwlist)

Output:

['False', 'None', 'True', '__peg_parser__', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

Reserved Classes in Python

  1. Single leading underscore (_*): Using this identification, you can keep the outcomes of the most recent evaluation in your interactive interpreter. The module __builtin__ contains storage space for these outcomes. Since they are private, "from module import *" cannot be used to import them.
  2. Double leading and trailing underscores (__*__): Only system-defined names use this notation. The interpreter and its implementations define these names. For further names, this approach is not suggested.
  3. Leading double underscores (__*): These category names are appropriate for class descriptions. They have been changed to prevent name conflicts between the private variables of base classes and derived classes.

Is Python Case Sensitive?

Now you know what an identifier is. Let's understand is python case-sensitive by taking some examples.

Example-1:

# initializing a variable
num = 5


# trying to print num
print(Num)




Output:

NameError: name 'Num' is not defined

From the above example, we defined a variable num. Let’s try to print it. We can see that num and Num are not the same. That’s why we are getting a NameError, that Num is not defined.

Example-2:

# defining a function named greet
def greet():
	print("Hello world!")


# trying to call greet function
grEEt()

Output:

NameError: name 'grEEt' is not defined

From the above example, we defined a function greet. Let’s call it. We can see that python treats greet and grEEt differently. That is why we are getting NameError, that grEEt is not defined.

Example 3:

Reserved keywords are also case-sensitive in Python. Let’s understand with an example. We know “in” is a reserved keyword in python. Let’s try to use it as “In”.

# initializing a list
nums = [6, 1, 8, 4, 23, 9, 12, 3]
# printing if nums consists 6 or not
print(6 In  nums)

Output:

SyntaxError: invalid syntax

So here we can see we get a SyntaxError: invalid syntax. Because in python, in and in are different from each other.


Related Topics

Python Project Ideas for Advanced Developers

Best Python Project Ideas for Advanced Developers Python is an object-oriented, high-level, interpreted programming language created by a developer known Guido Van Rossum. Python is one of the languages that gathered...

9 minutes read.

Python Write Excel File

Python Write Excel File The Python xlwt module is used to write an excel file and perform multiple operations on it. It can be used to write text, numbers, and formulas for multiple...

3 minutes read.

Python List sort() method

The list.sort () method in Python sorts the items of the list in place. Syntax list.sort(key=None, reverse=False) Parameter reverse: If a Boolean value ‘True’ is passed, the  sorting will be done in the descending order else for ‘False’...

2 minutes read.

Python Letter to Number

Python Letter to Number In this tutorial, we will convert the given letters into numbers using a Python. We will convert the given letter into the letter value as defined in...

3 minutes read.

How to implement classifiers in Python

What is classification? Classification is a type of supervised machine learning problem with a categorical target (response) variable. Given the known label in the training data, the classifier approximates a mapping...

4 minutes read.

How to run Python code from the command prompt

The Windows operating system's command-line interpreter is CMD or Command Prompt. The "MS-DOS Prompt" is comparable to Command.com, used in DOS and Windows 9x computers. It is similar to Unix...

3 minutes read.

Python for Data Analysis

Data analysis uses various techniques to read, illustrate, manipulate and evaluate a particular data. You can have access to the data and keep the data updated regularly. You can append...

4 minutes read.

Classes & Objects in Python

Classes and Objects are used in most modern programming languages, mainly in Object-oriented Programming languages. What is meant by Object Oriented Programming language? Usage of objects and their components in order to...

7 minutes read.

What is online python free IDE

An IDE is an acronym that stands for “Integrated development environment.” It is a software environment that has a software development package that consists of the code editor and builds...

4 minutes read.

Python Dictionary clear() method

Python Dictionary clear() method The dictionary.clear() method in Python removes all the elements from a dictionary. Syntax dictionary.clear() Parameter NA Return None Example 1 # Python program explaining # the dictionary.clear() method # initialising the dictionary fruits =...

1 minute read.

Python vs Java

There are a lot of programming languages out there, and every day, a new programming language is developing in some parts of the world. Each programming language is a mixture...

5 minutes read.

Captcha Code in Python with Example

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

6 minutes read.

Python Printf Style Formating

String objects have one special implicit activity: the % administrator (modulo). This is otherwise called the string designing or interjection administrator. Given design % values (where configuration is a string),...

3 minutes read.

Find Last Occurrence of Substring using Python

Introduction When planning to work with strings, we may need to determine whether a substring is present. This issue is rather typical, and there have been numerous discussions about how to...

3 minutes read.

Run exec python from PHP

PHP (which is a recursive abbreviation for PHP Hypertext Preprocessor) is one of the most broadly involved web improvement innovations on the planet. PHP code utilized for creating sites and...

4 minutes read.

Python Struct

Python Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

How to append an Array in Python

A group of objects kept at adjacent memory regions is known as an array. It is a container with a set capacity for a certain number of things, all of...

7 minutes read.

Python zip() Function

Python zip() Function The zip() function makes an iterator that aggregates elements from each of the iterables and returns an iterator of tuples. Syntax zip(*iterables) Parameter iterables: Iterator objects that will be joined together Return This function...

1 minute read.

Python Random shuffle( ) method

The shuffle() is used to change the positions of the elements in the mutable sequences. The shuffle( ) function will change the positions of the elements in the sequence of...

3 minutes read.

Artificial intelligence mini projects ideas in python

Artificial intelligence "The human race started from the invention of the wheel", and today we are about to advance to the Industrial level 4.0, where machines can work, talk, think and...

6 minutes read.