Identifiers in Python Programs
In this tutorial, you will learn the concept of identifiers in Python programs.
A name in the Python program is called an identifier. It can be a class name or function name or module name or variable name. Example, a = 10
Video Tutorial
Rules to define identifiers in Python:
1. The only allowed characters in Python are,
- alphabet symbols (either lower case or upper case) and digits. That is (a to z or A to Z or 0 to 9)
- underscore symbol (_)
By mistake, if we are using any other symbol like $ then we will get a syntax error.
- cash = 10 Correct statement
- ca$h =20 Incorrect Statement
2. Identifier should not start with digit,
- 123total Incorrect Statement
- total123 Correct statement
3. Identifiers are case-sensitive. Of course, Python language is case sensitive language.
- total=10
- TOTAL=999
- print (total) # Prints10
- print (TOTAL) #Prints 999
Identifier:
1. Alphabet Symbols (Either Upper case OR Lower case). That is (A to Z or a to z)
2. If the Identifier is started with Underscore (_) then it indicates it is private.
3. The identifier should not start with Digits. But identifier may contain digits except for the first character.
4. Identifiers are case-sensitive. Example total and Total are two different identifiers.
5. We cannot use reserved words as identifiers. Eg: def=10 or if = 20 or print = “Hello World”
6. There is no length limit for Python identifiers. But not recommended to use too lengthy identifiers.
7. Dollar ($) Symbol is not allowed in Python, that is $ symbol should not be a part of python identifier.
Test your Understanding
Q. Which of the following are valid Python identifiers?
1) 123total
2) total123
3) java2share
4) ca$h
5) abc_abc
6) def
7) if
Answer: Correct statements are — 2, 3, 5 as they follow the rules, set for defining identifiers.
Incorrect Statements are — 1 here identifier starts with digits, 4 here identifier has a special character that is $, 6 and 7 here both def and if are keywords.
Note:
If identifier starts with _ (Underscore) symbol then it indicates that it is private
If the identifier starts with two underscore symbols ie _ _, which indicates that the identifier is strongly private.
Finally, if the identifier both starts and ends with two underscore symbols, which indicates that the identifier is a language-defined special name. Eg: __add__ , __init__ and __str__
Summary:
In this tutorial, you have learned the definition of Identifiers in Python Programs, The rules to define identifiers, and examples for valid and invalid identifiers.
If you like the tutorial, share it with your friends. Do like our Facebook page for regular updates.