Python Identifiers with Examples

FREE Online Courses: Enroll Now, Thank us Later!

Want to know how to name different variables, functions, etc., in Python? Then let’s dive into this write-up and learn about it!

What are Identifiers in Python?

In Python Programming language, the naming words are called Identifiers. Identifiers are the tokens in Python that are used to name entities like variables, functions, classes, etc. These are the user-defined names.

In the below snippet, “number” and “name” are the identifiers given to the variables. These are holding the values 5 and “PythonGeeks” respectively.

Example on identifiers in Python:

number =5
name="PythonGeeks"

We can call these names whenever we want to use these values. For example, if we want to print the value, then we can refer to the name as shown below.

Example of printing the variable value:

print(number)
print(name)

Output:

5
PythonGeeks

Rules for Naming Identifiers in Python

Every word cannot be an identifier, some rules are to be followed while naming. The following are the rules for naming:

Rules for Naming Python Identifiers

a. It must start with a letter or the underscore (_). The following snippet shows variable names.

Example on identifier naming rules:

percentage =90.6
_name="PythonGeeks"
Num=3

b. It should not start with a number. In the below snippet, we can see that running the code gave a syntax error since the name of the variable started with 1.

Example of getting error on starting identifier with number:

1num=4

Output:

SyntaxError: invalid syntax

c. We must not use a keyword as an identifier. To see the list of keywords, you can type help() and then keywords.
The below snippet shows an error because “None” is a keyword and is used as a variable name.

Example of using keyword as identifier giving an error:

None=0

Output:

SyntaxError: cannot assign to None

d. It should only contain alpha-numeric characters and underscores (i.e., A-Z,a-z 0-9, and _ ). Any other character is not valid. Even spaces are not allowed.

The following code ran into an error because the variable name contained the character ‘@’, which is not acceptable.

Example of getting an error on using special characters in an identifier:

name@web="PythonGeeks"

Output:

SyntaxError: cannot assign to operator

e. The length of the identifier can be as long as possible, unless it exceeds the available memory. It is suggested to not keep more than 79 characters in a line according to the PEP-8 rules.

To sum it up, identifier lexically

  • Identifier => (letter | _) (letters | digit | _) #begins with letters or _ and contains only letters, numbers and _
  • Letter => lowercase | uppercase #letters can be either uppercase or lower case
  • Lowercase => ‘a’ … ‘z’ # lowercase letters go from a to z
  • Uppercase => ‘A’ ….’Z’ #uppercase letters go from A to Z
  • Digit => ‘0’…’9’ #Digits include integers from 0 to 9

Based on the naming rules, the names are of two types. The first ones are legal identifiers, those that follow the conventions for naming and the second type are the illegal ones that don’t follow. Some of the legal and illegal identifiers are given in the picture below.

Legal and illegal identifiers in Python

Testing the Validity of Python Identifiers

There is a way to test if a name is a legal identifier or not. We can do this using a predefined function ‘.isidentifier()’. Let us test some names.

Example of testing validity of a name as identifier:

'var1'.isidentifier()
'1Var'.isidentifier()
'$price'.isidentifier()
'name_1'.isidentifier()

Output:

True
False
False
True

But this prints true even if the name is a keyword.

Example of keyword identified as identifier:

'True'.isidentifier()

Output:

True

So we can use the function ‘keyword.iskeyword()’ to find if a name is a keyword or not. For this, you have to first import the module ‘keyword’.

Example of checking if a word is keyword:

import keyword
keyword.iskeyword('True')

Output:

True

Good Practices of Naming Python Identifiers

Before going to the next topic, let’s discuss some of the good practices while naming:

a. Give relevant names. This will help when referring to the code in the future. For example,

  • When you want to store the name of a person use ‘name’
  • For a function that adds two number, name it ‘add’ or ‘sum’

b. Prefer names longer than one character. This will make it readable.

  • For example, instead of using ‘n’, use ‘no_of_stds’.

c. When you have multiple words, separate them by underscore ( _ ). You can also use camel case or pascal case by capitalizing the first letter of the other words. This will make the name readable. For example,

  • To store number of students, use ‘no_of_stds’ or ‘count_of_students’
  • For a function that calculates the second-highest value is a list, use ‘second_highest’ or ‘secondHighest.

d. The names are case-sensitive in Python. So, it is better to be careful to not fall into this error.

  • In Python, Pythongeeks and PythonGeeks are treated differently.

e. It is better to keep the first letter of class names capital and other names small.

f. It is suggested to start only the private variables with underscore.

  • This is only to make it easy to distinguish private ones from the others.

g. Use double underscore either for special methods or during mangling only. Python uses double score for built-in special methods like __init__,etc.

Reserved Classes of Identifiers in Python

Some of the classes in Python have special meaning. These can be identified by their identifiers with leading and trailing underscores. Based on the pattern on these underscores, classes are of three types:

a. With single leading underscores (_*):

These store the results of last execution in the currently active interpreter. In Python, these are stored in a private module, __builtin__ module. This module is private because it cannot be imported by the usual method of importing other modules.

b. With leading and trailing double underscores (__*__):

These represent the names defined by the system (i.e., interpreter) to identify special methods. This set may extend further with additions and improvements in Python versions.

An example of such an identifier is __getitem__(), used for accessing variables in classes.

c. With leading double scores (__*):

These are used for private items in classes. These are mainly used for mangling and to avoid confusion between private names of parent and child classes.

Python Interview Questions on Identifiers

Q1. Find the identifiers in the below program.

def greatest(num1,num2):
  if(num1>num2):
    return num1
  elif(num1<num2):
    return num2
  else:
    return 0

  
num1=5
num2=10
highest=greatest(num1,num2)

Ans 1. Identifiers are the names given to variables, functions,etc. In the above code identifiers are: a,b,greatest, highest.

Q2. In the below code identify the identifiers that can give errors.

var_1=10
yield=5
1var =35
var@3=9.0
var-4=48
Var_5=34
true=8

Ans 2. The invalid identifiers in the above code are:

  • yield ( a keyword)
  • 1var (starting with number)
  • var@3 (containing @ symbol)
  • var-4 (containing – symbol)

Q3. Write a function to find the sum of two numbers using correct rules and best practices.

Ans 3. To find the sum we need two numbers, we need 4 identifiers. To store the numbers, one for the function and one to store the result. Let the names be ‘no_1’ , ‘no_2’, ‘add()’, and ‘sum’ respectively. The code is:

def add(no_1,no_2):
  sum=no_1 + no_2
  return sum

sum=add(11,34)
print(sum)

Output:

45

Q4. Use either ‘keyword.iskeyword()’ or ‘isidentifier()’ to find if the below can be used to name or not (1) Count (2) 5Var (3) in (4) var@3 (5) lambda.

Ans 4. To find if you can use a name as an identifier or not, you can use the ‘isidentifier()’ method. But it is true for keywords using this method . So, for keywords, we have to check using keyword.iskeyword().

Example of checking validity of an identifier:

'Count'.isidentifier()
‘'5Var'.isidentifier()
keyword.iskeyword('in')
'var@3'.isidentifier()
keyword.iskeyword('lambda')

Output:

True
False
True
False
True

Q5. Change the identifiers in the below code that violate the code or are not good names for readability.

def Adddiff(n,m):
  s=n+m
  d=n-m
  print("Sum of the numbers is:",s)
  print("Difference of the numbers is:",d)

  
Adddiff(43,34)

Ans 5. The function name starts with an uppercase letter. Either ‘d’ in ‘diff’ can be made capital for camelcase or underscore can be added. Other variables have single length and can change them to meaningful ones.

Example of following good practices while naming:

def add_diff(no1,no2):
  add=no1 + no2
  diff=no1 - no2
  print("Addition of the numbers is:",add)
  print("Difference of the numbers is:",diff)

  
add_diff(43,34)

Quiz on Python Identifiers

Conclusion

Hence, we learned about identifiers and the rules concerning them. Also, we saw how to test its validity. Then we saw some good practices of naming variables. And finally, we ended with some interview questions.
Hope you gained some knowledge from this write-up. Happy Coding!

You give me 15 seconds I promise you best tutorials
Please share your happy experience on Google | Facebook


1 Response

  1. Kay PAUL says:

    keuprul 5tbn.9vi

Leave a Reply

Your email address will not be published. Required fields are marked *