FREE E LEARNING PLATFORM
HOMEEXCEPTIONSOOPSJVMINTRO
 

Python Keywords and Identifiers with examples




In this article, we will discuss Keywords and Identifiers in Python with the help of examples.

What is a Python Keyword?

python-keywords

A python keyword is a reserved word which you can’t use as a name of your variable, class, function etc. These keywords have a special meaning and they are used for special purposes in Python programming language. For example – Python keyword “while” is used for while loop thus you can’t name a variable with the name “while” else it may cause compilation error.

There are total 33 keywords in Python 3.6. To get the keywords list on your operating system, open command prompt (terminal on Mac OS) and type “Python” and hit enter. After that type help() and hit enter. Type keywords to get the list of the keywords for the current python version running on your operating system.

python-keywords

Example of Python keyword

In the following example we are using while keyword to create a loop for displaying the values of variables num as long as they are greater than 5.

num = 10
while num>5:
    print(num)
    num -= 1

Output

output1

Python Identifiers

Variable name is known as identifier. There are few rules that you have to follow while naming the variables in Python.
For example here the variable is of integer type that holds the value 10. The name of the variable, which is num is called identifier.
num = 10

1. The name of the variable must always start with either a letter or an underscore (_). For example: _str, str, num, _num are all valid name for the variables.
2. The name of the variable cannot start with a number. For example: 9num is not a valid variable name.
3. The name of the variable cannot have special characters such as %, $, # etc, they can only have alphanumeric characters and underscore (A to Z, a to z, 0-9 or _ ).

4. Variable name is case sensitive in Python which means num and NUM are two different variables in python.

Python identifier example

In the following example we have three variables. The name of the variables num, _x and a_b are the identifiers.

# few examples of identifiers

num = 10
print(num)

_x = 100
print(_x)

a_b = 99
print(a_b)

Output

output2







Leave Comment