Python Keywords and Identifiers

Python Keywords and Identifiers

 

Keywords are the reserved words that cannot be used as variable names or function names. Identifiers are the name of the variables that is identifiers are named memory location that is assigned some specific value or the name of the function or methods.

 

Python Keywords

Keywords are the reserved words that cannot be used as variable names or function names. The keywords are used in syntax or structure of the python programming language. Keywords are case sensitive that is an upper case keyword will matter a lot to a lower case letter keyword. In python programming language there are total 33 keywords. There are three keywords that are written as they are and the remaining keywords are written in lower case letters. These three keywords are listed below:

  1. True
  2. None
  3. False

It can be seen that they are starting from capital letter and the other letters are small letters.

The list of remaining keywords is given below:

Keyword Description
class the class keyword is used to define a class in Python object oriented programming for example class student (object)
and and is the logical operator. It is a binary operator which generates a true result only if both of the conditions are true.
as as is the part of the with as statement that is used when the user wants to execute two operations as a pair.
assert assert keyword is used ensure that a certain condition is true.
break break keyword is used to indicate that the loop must be stopped now.
continue continue keyword is used repeat the loop a number of times.
def def keyword is used to define a function.
del del keyword is used to delete a something from dictionary.
elif elif keyword is used for else if condition.
else else keyword is used to indicate the else condition.
except except keyword is used to handle an exception when it is occurred.
exec exec keyword is used to run a string as the Python.
finally finally keyword is used to handle exception that if an exception is occurred the system should do this.
for for keyword is used with the for loop that is repeated a specific number of times.
from from keyword is used to import small programs or modules.
global global keyword is used to declare that a global variable is going to be used.
if if keyword is used with if condition to run a block of statements if a condition is true.
import import keyword is used just like the from keyword to import a part of program of module.
in in keyword is used in the for loop.
is is keyword is used to check the equality of something it results in a true or a false.
lambda lambda keyword is used to create or make a small function.
not not is the logical operator. It is unary operator that complements a certain condition that is true to false or false to true etc.
or or is the logical operator. It is a binary operator that is used to check a condition. It returns a true if one of the conditions is true in a statement.
pass pass keyword is used show that a certain block of a control flow is empty.
print print keyword is used to display the result.
raise raise keyword is used to raise an exception every time something becomes wrong.
return return keyword is used to return a value.
try try keyword is used to try a certain block of statement when an exception is occurred.
while while keyword is used with the while condition.
with with keyword is used to make a variable do as another variable is doing.
yield yield keyword is used pause.

 

Examples of Keywords

The keywords of python programming language can vary from versions to versions for example a keyword in Python 2 may not be used in other versions like Python 3.

True, False

True and False are truth values obtained as a result when a logical operation is being performed on two operands using the logical operators either “and” or “or”. To understand working of true and false, consider the following example:

CODE

>>> 1>5

False

>>> 5 == 5

True

true-or-false

First statement is false that is 1 is smaller than 5 hence the interpreter returns False. Second statement is true therefore, interpreter returns true. In python the value of true is 1 and the value of false is 0. When you add two “true” values the result will be 2. Consider the following example:

CODE

>>> True == 1

True

>>> False == 0

True

>>> True + True

2

>>> True + False

1

>>> False + False

0

values-the-result-will-be-2

 

None

None is used to represent a NULL value. None is a constant in python. None is an object that has a data type that is none type. In a python program multiple none objects cannot be created but the object can be assigned to other variables. It should also be noted that “none” cannot be assigned a 0, false or an empty string. Consider the following example:

CODE

>>> None == 0

False

>>> None == []

False

>>> a = None

>>> b = None

>>> a == b

True

none

The functions of void type also return none automatically. Although there is not a return statement at the end of the functions of void type but none is returned by a void function. Consider the following example in which we will be using def keyword to define a function of void type and we will demonstrate that none is returned by a void function:

CODE

>>> def void_addition():

          x = 1

          y = 3

          z = x + y

>>> a = void_addition()

>>> print(a)

When you press the enter key, the output will appear:

when-you-press-the-enter-key

You can see that none is displayed at the output. The above program is defining a function that cannot return a value and when “a” is printed “none” is returned by the interpreter but there are some operations in the function that are being performed.

If a function definition has a condition to be met then if the condition is true then the interpreter returns a true otherwise the interpreter will return “none”. Consider the following example in which we are using a condition that if the entered number is an odd number then interpreter should return true otherwise it should return none.

CODE

>>> def oddNumber(x):

          if (x % 2) != 0:

                   return True

>>> y = oddNumber(2)

>>> print(y)

When you press the enter key none will be displayed because 2 is an even number:

2-is-an-even-number

 

and, or, not

and, or , and not are the binary logical operators that are used to check a condition in python. The logical “and” operator generates a true result only if both of the conditions are true. The truth table of the logical and operator is given below:

A B A and B
True True True
True False False
False True False
False False False

or returns a true if one of the conditions is true in a statement. The truth table for or operator is given below:

A B A or B
True True True
True False True
False True True
False False False

Not is a unary operator that complements a certain condition that is true to false or false to true etc. The truth table for not operator is given below:

A not A
True False
False True

 

Examples of and, or, not

Consider the following lines of code:

CODE

>>> True and True

True

>>> True and False

False

>>> False and False

False

>>> True or False

True

>>> not False

True

>>> not True

False

examples-of-and-or-not

 

as

as is the part of the with as statement that is used when the user wants to execute two operations as a pair. as keyword is used to give a different name to a part of the program when it is imported. This name is user defined. Consider the following example to understand the concept of as keyword:

There is a standard math module in python. If the user wants to calculate cosine pi using alias then it can be done using the as keyword:

CODE

>>> import math as myAlias

>>> myAlias.cos(myAlias.pi)

OUTPUT

-1.0

output

In the above example the standard math module is imported and is given a name “anAlias” using the as keyword. Therefore, the standard math module will be referred by the name “anAlias”. The above example calculated cosine of pi that is cos(pi) which resulted in the answer -1.0.

 

assert

assert keyword is used to ensure that a certain condition is true. It is mostly used in the debugging process. Consider the following example to understand the assert keyword:

CODE

>>> x = 3

>>> assert x >4

Traceback (most recent call last):

  File “<pyshell#1>”, line 1, in <module>

    assert x >4

AssertionError

assertionerror

In the above example we assigned a value to x that is 3 and we also used the assert keyword or we assumed that x is greater than 4. Therefore, an assertion error is occurred. We can also generate an error message for better understanding using the assert keyword. Consider the following example:

CODE

>>> x = 3

>>> assert x > 4, “The value entered is smaller”

Traceback (most recent call last):

  File “<pyshell#3>”, line 1, in <module>

    assert x > 4, “The value entered is smaller”

AssertionError: The value entered is smaller

generated-an-error-message

In this way we have generated an error message.

 

break, continue

break keyword is used to indicate that the loop must be stopped now. continue keyword is used repeat the loop a number of times. Both of the keywords are used inside a for loop or a while loop in python. The control is transferred to the other statements after the loop when break keyword is used. Consider the following examples for break and continue keywords:

CODE

>>> for j in range (1, 10):

          if j == 2:

                   break

          print(j)

OUTPUT

1

for-loop

In the above example a for loop is used that starts from 1 and stops at 10. Inside the for loop there is a condition that if the counter variable becomes equal to 2 then the loop must break, this is done by using the break keyword. At the end the counter variable is printed and 1 is printed. If in the condition we specify that when counter variable becomes equal to 3 then the loop must stop the output will be:

1

2

Consider the following example for continue keyword:

CODE

>>> for j in range (1, 10):

          if j == 4:

                   continue

          print(j)

OUTPUT

1

2

3

5

6

7

8

9

continue-statement

In the above example we used continue statement and it prints all the values but when the condition becomes true that iteration is not run. And then all the values are printed except 4.

 

class

The class keyword is used to define a class in Python object oriented programming for example class student (object). Classes should be defined in a module. Consider the following example:

class student:

def function (parameters of function):

def function (parameters of function):

 

def

The def keyword is used to define a user defined function in Python. A function is a block of statements that is used to perform certain specific task defined by the user. The following is the user defined function:

def function (parameters of function):

 

del

The del keyword is used to delete the reference of a variable. Consider the following example:

CODE

>>> x= y = 2

>>> del x

>>> x

Traceback (most recent call last):

  File “<pyshell#20>”, line 1, in <module>

    x

NameError: name ‘x’ is not defined

>>> y

OUTPUT

2

initialized-x-at-2-and-y-at-2

In the above example we initialized x at 2 and y at 2 also therefore, x became equal to y and then we deleted the variable x or the reference of the variable x and when we wanted to show the value of x an error occurred that x is not defined. y was not deleted and when we displayed the variable y the value of y is displayed.

We can also use del to delete something from the list or from the dictionary. To delete an item from a list consider the following example:

CODE

>>> x = [‘q’, ‘w’, ‘e’]

>>> del x[2]

>>> x

OUTPUT

[‘q’, ‘w’]

we-initialized-x-as-a-list-of-items

In the above example, we initialized x as a list of items. The list contained q, w and e and when we used the command del x[2] that deleted the third item from the list of x and the output is [‘q’, ‘w’]. As the array starts from 0 hence when we deleted x[2], the third item will be deleted.

 

if, else, elif

if keyword is used with if condition to run a block of statements if a condition is true.

else keyword is used to indicate the else condition.

elif keyword is used for else if condition. elif is the short form for else if.

All the three keywords are used in decision making statements. When we want to execute a block of statement that is based on the condition that is true then we use the if and elif keywords. The else keyword is used to execute the block of statement when the condition is false. Consider the following example:

CODE

>>> def if_case(x):

          if x == 1:

                   print(‘you entered 1’)

          elif x == 2:

                   print(‘You entered 2’)

          else:

                   print(‘You entered a value other than 1 and 2’)

>>> if_case(1)

>>> if_case(3)

>>> if_case(2)

OUTPUT

you entered 1

You entered a value other than 1 and 2

You entered 2

the-value-of-x

In the above example, the value of x is passed to the function and if the value of variable x matches with any of the conditions the corresponding print statement is executed. If the value of x matches with none of the above conditions then else statement will be executed.

 

except, raise, try

except keyword is used to handle an exception when it is occurred.

raise keyword is used to raise an exception every time something becomes wrong.

try keyword is used to try a certain block of statement when an exception is occurred.

In short all the three keywords are used to handle exceptions in python. Exceptions are the errors that occurred in a program in python. Some of the exceptions are TypeError, ValueError, etc. The statement try… except is used to catch the exception in python. And the exceptions can be raised using the raise keyword. Consider the following example to understand these keywords:

CODE

>>> def example(number):

          try:

                   a = 1/number

          except:

                   print(‘An exception occurred’)

                   return

          return a

>>> print(example(14))

0.07142857142857142

>>> print(example(0))

An exception occurred

None

in-the-above-example

In the above example, we defined a function in which used try and except keywords to catch exception. In the try block, a is the value that will be obtained after the division by a number that will be passed by the user. If the number passed by the user is 0, an exception will be occurred because dividing any number by 0 is infinity. Hence an error message is displayed when user tried to divide 1 by 0.

The ZeroDivisionError can also be raised explicitly using the raise keyword.

 

finally

finally keyword is used to handle exception that if an exception is occurred what should the system do. The block of the statements under the finally keyword must runs even if there is an exception. Consider the following example:

try:

          block of statement

except exceptionNumber1:

          block of exceptionNumber1

except exceptionNumber2:

          block of exceptionNumber2

else:

          block of statement

finally:

          block of statement

In the above example if an error occurs in the block of statement of try keyword then the exception or error will be handled in the else statement of exception statements. The block of statement of the finally keyword will be executed must even if there is any exception.

 

for

for keyword is used with the for loop that is repeated a specific number of times. We can execute the for loop as many times as we want by defining the counter variable. We can use the for loop for string of list in python. Consider the following example in which we are using for loop for to print the names of students in a list:

CODE
>>> StudentNames = [‘Stuart’, ‘Bills’, ‘Faddy’]

>>> for j in StudentNames:

          print(j)

OUTPUT

Stuart

Bills

Faddy

faddy

 

from, import

from keyword is used to import small programs or modules.

import keyword is used just like the from keyword to import a part of program of module. For example math is the standard module in python we can import math to perform functions like sine, cosine etc. using the import keyword:

import math

The above command will import the standard module math and we can use the functions defined in math such as cosine function as math.cos(). If we want o import only the cosine function from the math module then we will use from keyword. Consider the following example:

from math import cos

using this command we will able to use the cosine function as cos() simple there will be no need of using math.cos().

 

global

global keyword is used to declare that a global variable is going to be used. If the user wants to change the value of a global variable inside a function then he must declare that variable globally using the global keyword. If the user does not declare the variable as global then the scope of that variable will be local. Consider the following example:

CODE

>>> x = 5

>>> def displayX():

          print(x)

>>> def insertX():

          global x

          x = 2

>>> def insertX1():

          x = 3

>>> displayX()

5

>>> insertX()

>>> displayX()

2

>>> insertX1()

>>> displayX()

2

displayx

In the above example, the displayX function printing the value of variable x, insert function is used to modify or change the value of x, x is declared globally here so that its value can be changed. In the output when the displayX() function is called it displays 5. When we call the insertX() function the value of x is changed to 2 and when the displayX () function is called again 2 is printed. The last function is insertX1 that again changes the value of x, although variable x is global now but it is invisible outside the function and hence its value is not changed and again 2 is printed.

 

in

in keyword is used in the for loop. It is also used to find a value in a sequence and if the value is found it returns true and if the value is not found it returns false. Consider the following example to use the in keyword to find a value in a sequence.

CODE

>>> x = [1, 2, 3, 4, 5]

>>> 7 in x

False

>>> 2 in x

True

2-in-x

The variable x is initialized with a list of items containing integers from 1 to 5. We used the in keyword to find an item from the list. If the item is found it returns true otherwise false.

Consider the following example in which the in keyword is used in for loop:

CODE

>>> for j in range(1, 5):

          print(j)

OUTPUT

1

2

3

4

for-j-in-range

 

is

is keyword is used to check that if two variables are referring to the same variable or not. It results in a true or a false. Consider the following example:

CODE

>>> True is False

False

>>> False is False

True

>>> False is True

False

>>> True is True

True

>>> None is None

True

none-is-none

The difference between is and == is that == is used to check that if two variables are equal or not that is if they have the same value or not and “is” is used to check that if two variables are referring to the same variable or not.

Two empty lists are equal but are not identical that is these two empty lists are saved in different memory location that is why they are not identical. Consider the following example to demonstrate this concept:

CODE

>>> [] == []

True

>>> [] is []

False

>>> ‘ ‘ == ”

False

>>> []==[]

True

>>> ”==”

True

>>> {}=={}

True

>>> {} is {}

False

>>> [] is []

False

false

 

Lambda

lambda keyword is used to create or make a small function having no name. This function has no return statement but an expression that is evaluated and the value obtained is returned. Consider the following example:

CODE

>>> x = lambda  y: y+2

>>> for j in range(1, 5):

          print(x(j))

OUTPUT

3

4

5

6

lambda

In the above example, we used an inline function defined by the keyword lambda. The function has a variable y and the value of y is passed from for loop. There is an expression in function y+2 which takes the value of the counter variable in the loop and adds 2 to it then the result is printed.

 

nonlocal

The nonlocal keyword is similar to global keyword. The difference is that nonlocal variables are declared in nested functions. A nested function is a function inside another function. The non local variable is known to the outer function enclosing the inner function. If the user wants to change the values of a variable inside a nested function then he must declare the variable non local otherwise it will be considered to be a local variable. Consider the following example in which we have declared a variable as non local in a nested function.

CODE

>>> def function1():

          x = 2

          def function2():

                   nonlocal x

                   x = 4

                   print(“Function 2: “, x)

          function2()

          print(“function1: “, x)

>>> function1()

OUTPUT

Function 2:  4

function1:  4

function1

In the above example, function1 is the outer function in nested function and function2 is the inner function of nested function. In function1 the value of x is 2 and in the function2 x is declared to be non local and then its value is changed. Now the value of x is 4. When function1 is called the value of x is 4 and when function2 is called the value of x is 4. Therefore, we conclude that we can modify the value of x in nested function using the keyword nonlocal.

Consider the following example in which we will not be using the keyword nonlocal:

CODE

>>> def function1():

          x= 2

          def function2():

                   x = 4

                   print(“Function 2: “, x)

          function2()

          print(“function1: “, x)

>>> function1()

OUTPUT

Function 2:  4

function1:  2

nonlocal-keyword

In the above example, we did not use nonlocal keyword hence inside the function2 or inner function of nested function a new variable is defined with a local scope. Both of the variables are different are known to only functions in which they are defined.

 

pass

pass keyword is used show that a certain block of a control flow is empty. In short the pass statement is referred to as a null statement in python. The pass keyword is used to create a blank body of a function or class in python so that if the user does not want to implement the function or class then he can create a blank body and use it later. Consider the following example:

CODE

>>> def function():

          pass

def-functionIn the above example a function is defined and its body is empty. Consider the following example in which we will be creating class and will keep the body of the class as empty:

CODE

>>> class abc:

          pass

pass

 

return

return keyword is used to return a value from a function. If no value is returned hen None will be returned. Consider the following example:

CODE

>>> def function1():

          x = 1

          return x

>>> def function2():

          x = 2

>>> print(function1())

>>> print(function2())

OUTPUT

1

None

return-key-word
In the above example, function1 () is using the return key word and has returned the variable x. The value of x is printed. On the other hand, function2 () has initialized the variable x but is not using the keyword return to return the value of x hence None is displayed.

 

while

while keyword is used with the while loop. The block of statements inside a “while” loop are executed until the condition becomes false. The loop will also terminate when a break statement is executed. Consider the following example:

CODE

>>> j = 1

>>> while(j<=5):

          print(j)

          j = j+ 1

OUTPUT

1

2

3

4

5

counter-variable

In the above example, j is the counter variable that starts with 1 and the loop terminates when j becomes equal to 5. An increment of 1 is being done to j.

 

with

The with keyword is used to open a file then writing something to it and closing it. Consider the following example:

CODE

>>> with open(‘asd.txt’, ‘w’) as myFile:

          f.write(‘I love my Country’)

In the above example, with keyword is used to open the file asd.txt and is given the name myFile. ‘w’ is used to open the file in writing mode.

 

yield

The yield keyword is used to return a generator inside a function. Generator is used when there is a large list of values and this list is taking a lot of memory hence generator will generate one item of the list at a time instead of storing the whole list in memory. Consider the following example:

CODE

>>> def generatorExample():

          for j in range(5):

                   yield j+1

>>> x = generatorExample()

>>> for j in x:

          print(j)

OUTPUT

1

2

3

4

5

generatorexample

In the above example a function named generatorExample() is defined in which the value of j is yielded after an increment of 1. One item or one value of the list is generated at a time.

 

Python Identifiers

Identifiers are the names of variables, functions, methods or class etc. The identifiers are different for each entity hence differentiating the entities from each other.

 

Rules for writing Identifiers in Python

  1. Identifier can contain letters both upper case and lowercase from (a-z) or (A-Z). Identifier can also contain underscore (_). Underscore is used to clarify the name of the identifier for example my_file is clearer than myfile.
  2. We cannot start an identifier from a digit or number for example 3file is invalid but file3 is valid.
  3. We cannot use the keywords as the names of identifiers. Consider the following example to demonstrate this:

                            >>> while = 1

                            SyntaxError: invalid syntax

syntaxerror

  1. Special symbols cannot be used as the name or between the names of identifiers such as &, #, $, %, etc. Consider the following example:

                          >>> asd$ = 1

                         SyntaxError: invalid syntax

invalid-syntax

  1. Identifier can be of any length.
  2. Blank spaces are not allowed in the name of identifier.

Key points to remember

  1. Python is a case sensitive programming language and variables with same name but the difference of upper case and lower case letters are not the same for example x and X are different.
  2. The names of variables should be meaningful that when a user looks back the code after a long time he should be able to understand that what this variable is for? For example a counter variable of a loop is recommended to be named as count instead of c etc.
  3. In a variable name if there are more than one word then they should be separated by an underscore (_).
  4. To make a variable name more meaningful the user should capitalize each word in variable name. This is concept is known as camel case style. For example the variable should be named as GeneratorExample instead of generatorexample.