×

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 Combination

Python Combination Permutations and combinations are the important part of our mathematical tools. We use them often in our Python programs. In this tutorial, we will learn about combinations in Python...

6 minutes read.

Keyboard Jump Game in Python

Keyword hop (jump) game is a speed composing game that aides in further developing the composing velocity of players The object of Keyboard Jump (hop) Game Python Project is to fabricate...

7 minutes read.

Python Project Ideas for Beginners

Python project ideas for beginners Advanced Python is an amazing platform to grow and achieve success as a developer in the future. Python is a programming language that can be very...

7 minutes read.

Python Prime factorization

Python Prime factorization In this tutorial, we will design a program where we will find all the prime factors of a number. Then, we will print all these prime factors of...

3 minutes 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.

Socket Programming in Python

Socket Programming in Python In this tutorial, we will discuss network programming using Python programming language. We will explore all basic concept of network with Python script. Network Services in Python Python has...

9 minutes read.

Python OOPs: Class, Object, Inheritance and Constructor

Basic Object-Oriented Programming (OOP) Concepts in Python Python is similar to most general-purpose programming languages with an Object-Oriented environment system since its existence. Being an Object-Oriented Programming language, Python provides ease...

9 minutes read.

How to Iterate a List in Python

As we know, a List is one of the four unique data structures available in Python; in this article, we will deep dive into understanding iterating through a list and...

3 minutes read.

How To Take Multiple Inputs In Python

In C language, we make use of the scanf() function to obtain the values from the user and store it in the variable. Coming to the Python language, we use the...

5 minutes read.

How to find square root in python

How to find Square Root of a number In Python Python makes a lot of tasks easier by using different functions, modules, and libraires. There is an inbuilt function in Python...

6 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.

How to Iterate through a Dictionary in Python

In this tutorial, we will learn how to interate throught the dictionary in the Python programming, using different approaches with example. Introduction to Dictionary in Python Dictionary is a special type of...

4 minutes read.

How to check if the dictionary is empty in Python?

What is a dictionary in Python? A directory is a collection of data but data is not ordered. Unlike other data types, it does not hold a single value as its...

3 minutes read.

Python whois

What is whois? Whois is a protocol used to identify the owner of the registered domain name. It is a querying database that is used to record the registered users. WHOIS is...

4 minutes read.

Commands in Python

In this tutorial, we will see some of the widely used python commands along with their syntaxes and examples. To make Python more user-friendly, developers have provided these commands to...

12 minutes read.

Python String index() method

Python String index() method The string.index() method in Python finds the lower index of the first occurrence of the specified value or raise a ValueError if the substring is not found. Syntax index(sub[, start[, end]]) Parameter sub:...

2 minutes read.

How To Print Colored Text in Python

Changing the colour of certain parts of a string when printing the output of a Python programme to the terminal may make it easier to read. We can approach this...

3 minutes read.

Tuple in Python

Tuples Tuples are the same as the list but as we know that lists are mutable means we can change the data from it. In the tuple we cannot change the...

6 minutes read.

Python try catch exception

The try-except proclamation can deal with exceptions. Exceptions might happen when you run a program. Exceptions are blunders that occur during the execution of the program. Python won't educate you regarding...

3 minutes read.

Read Text files in Python

In Python, there are many ways to read text files. Before going into the detailed structure of reading a text file, let us understand how reading text files takes place...

4 minutes read.