Keywords and Identifiers In Python

In this Python article, we will discuss Keywords, Identifiers, rules to create identifiers and will also implement some examples.

1. Keywords

Keywords are the pre-defined words having special meaning to the language compiler.

We can’t name our variable, function, or other entity using these keywords.

Python keywords are case sensitive. We have in total of 33 keywords in python3.7.

andasassert
breakclasscontinue
elifdeldef
elseexceptFalse
finallyforfrom
globalifimport
lambdaisin
Nonenonlocalnot
orpassraise
returnTruetry
whilewithyield
Python Keyword

But in latest version of python we have 3 additional keyword

__peg_parser__ awaitasync

To check the keywords of your python version type help() and then keywords in your Python console.

Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec  7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> help()
Welcome to Python 3.9's help utility!

help> keywords
Here is a list of the Python keywords.  Enter any keyword to get more help.

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

help> exit

However, is it possible that using only these words we can write our code? And the answer is No, it’s not possible and that’s why we have another concept called identifiers.


2. Identifiers

Identifiers are like naming a newborn kid. Whenever a kid is born we give it a name, the same thing we do in Python when we create an entity like a variable, class, the function we give it a name example varname, ClassName, funcname etc.

REMEMBER: Python is case-sensitive that means it treats lower and upper case letter differently. Example – name and Name both are different

2.1. Rules for creating an identifier

  • Can’t use a reserved word mainly because it will create confusion for the compiler as well as it will give an error.
>>> break = 1
SyntaxError: invalid syntax
  • Can’t start an identifier with a digit (0-9)
>>> 123varname = 1
SyntaxError: invalid syntax
  • Should not contain any special character other than A-Z, a-z, _
>>> var$name=1
  File "<stdin>", line 1
    var$name=1
       ^
SyntaxError: invalid syntax
  • Try to avoid using two underscores (_) in the beginning and at the end of the variable name
    Example __private__, __len__ because python use these to create special variables or functions in framework classes.

2.2. Example of Valid Identifiers

  • Z2T09
  • _Abc
  • My_Work
  • _HELLO_hi
  • Hello123

2.3. Example of Invalid Identifiers

  • 123HEllo -> can’t start an identifier with a number.
>>> 123hello=1
SyntaxError: invalid syntax
  • My.work -> can’t use any special character (except _ )
>>> My.work =1
Traceback (most recent call last):
  File "<pyshell#28>", line 1, in <module>
    My.work =1
NameError: name 'My' is not defined
  • HI-Bye -> can’t use any special character (except _ )
>>> HI-Bye = 1
SyntaxError: cannot assign to operator
  • break -> can’t use any keyword as an identifier
>>> break = 1
SyntaxError: invalid syntax

3. Examples of Keywords

3.1. and , or , not , True , False

and, or, not are logical operators which after comparing the operands return a boolean value i.e. either True or False.

# and returns true if both the operands are true else it returns false
print(True and False)

# or returns true if any of the operands are true else it returns false
print(True or False)

# not returns the opposite True--> False   False--> True
print(not(True))
Output:-
False
True
False

3.2. if, elif, else, for, in

if, elif, else are conditional statements that choose the set of statements for execution, depending on the expression’s return value.

for is used to perform a set of instructions repeatedly until a certain condition is fulfilled.

in checks if the element is present or not in the list, tuple, or in a particular range, etc.

for i in range(10):
    if i%2==0: # true is number is divisible by 2
        print(i,"is a multiple of 2")
    elif i%3==0:   # true is number is divisible by 2
        print(i,"is a multiple of 3")
    else:   # true is number is not divissiblee by 2 nor by 3
        print(i,"is not a multiple of either 2 or 3")
Output:-
0 is a multiple of 2
1 is not a multiple of either 2 or 3
2 is a multiple of 2
3 is a multiple of 3
4 is a multiple of 2
5 is not a multiple of either 2 or 3
6 is a multiple of 2
7 is not a multiple of either 2 or 3
8 is a multiple of 2
9 is a multiple of 3

3.3. while , pass , break , continue

while loop iterates until a condition is true.

break statement enables a program to skip over a part of the code by forcing the termination of a loop.

continue statement also skip over a part of the code but instead of forcing the termination of the loop, it forces the next iteration of the loop to take place and skips the current one.

pass statement does nothing. The interpreter does not ignore this statement but since it is a null statement there is no output. So when we don’t want to do anything, or we want to implement a method in the future we use pass statement, otherwise we will get an error.

count = 1
while True:
    if count%2==0:  #only increment if multiple of 2
        count+=1
        continue
    elif count%3==0: #if count is a multiple of 3 then don't do anything
        pass
    else:
        print(count)
    
    if count>10:  #if count is greater than 10 break the loop
        break
    else:
        count+=1
Output:-
1
5
7
11

4. Conclusion

In this article, we discussed what are Keywords, what are identifiers, the rules of creating an identifier, examples of valid and invalid identifiers, examples and usage of some of the keywords, and things we need to avoid.


Helpful Links

Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.

Complete code samples are present on Github project.

Recommended Books


An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! 😊

Recommended -

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x