Keywords in Python


Like other languages, Python also has some reserved words. These words hold some special meaning. Sometimes it may be a command, or a parameter etc. We cannot use keywords as variable names.

The Python Keywords are

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

The True & False Keywords

The True and False are the truth value in Python. Comparison operators returns True or False. Boolean variables also can hold them.

Example code

Live Demo

#Keywords True, False
print(5 < 10) #it is true
print(15 < 10) #it is false

Output

True
False

The class, def, return Keywords

The class keyword is used to define new user-define class in Python. The def is used to define user-defined function. And the return keyword is used to go back from a function and send a value to the invoker function.

Example code

#Keywords Class, def, return
class Point: #Class keyword to define class
   def __init__(self, x, y): #def keyword to define function
      self.x = x
      self.y = y
   def __str__(self):
      return '({},{})'.format(self.x, self.y) #return Keyword for returning
p1 = Point(10, 20)
p2 = Point(5, 7)
print('Points are: ' + str(p1) + ' and ' + str(p2))

Output

Points are: (10,20) and (5,7)

The if, elif, else Keywords

These three keywords are used for conditional branching or decision making. When the condition is true for the if statement, it enters the if block. When it is false, it searches for another condition, so if there are some elif block, it checks the condition with them. And finally, when all conditions are false, it enters into the else part.

Example code

#Keywords if, elif, else
defif_elif_else(x):
   if x < 0:
      print('x is negative')
   elif x == 0:
      print('x is 0')
   else:
      print('x is positive')
if_elif_else(12)
if_elif_else(-9)
if_elif_else(0)

Output

x is positive
x is negative
x is 0

The try, except, raise, finally Keywords

These keywords are used to handle different exceptions in Python. In the try block, we can write some code, which may raise some exceptions, and using the except block, we can handle them. The finally block is executed even if there is an unhandled exception.

Example code

#Keywords try, except, raise, finally
defreci(x):
   if x == 0:
      raise ZeroDivisionError('Cannot divide by zero') #raise an exception
   else:
      return 1/x
deftry_block_example(x):
   result = 'Unable to determine' #initialize
   try: #try to do next tasks
      result = reci(x)
   except ZeroDivisionError: #except the ZeroDivisionError
      print('Invalid number')
   finally: # Always execute the finally block
      print(result)
try_block_example(15)
try_block_example(0)

Output

0.06666666666666667
Invalid number
Unable to determine

The for, in, is, not Keywords

The for keyword is basically the for loop in Python. and the in keyword is used to check participation of some element in some container objects. There are another two keywords, these are is and not. The is keyword is used to test the identity of an object. The not keyword is used to invert any conditional statements.

Example code

#Keywords for, in, is, not
animal_list = ['Tiger', 'Dog', 'Lion', 'Peacock', 'Snake']
for animal in animal_list: #iterate through all animals in animal_list
   if animal is 'Peacock': #equality checking using 'is' keyword
      print(animal + ' is a bird')
   elif animal is not 'Snake': #negation checking using 'not' keyword
      print(animal + ' is mammal')

Output

Tiger is mammal
Dog is mammal
Lion is mammal
Peacock is a bird

The from, import Keywords

The import keyword is used to import some modules into the current namespace. The from…import is used to import some special attribute from a module.

Example code

Live Demo

#Keywords from, import
from math import factorial
print(factorial(12))

Output

479001600

The global Keyword

The global keyword is used to denote that a variable, which is used inside a block is global variable. When the global keyword is not present, the variable will act like read only. To modify the value, we should use the global keyword.

Example code

#Keyword global
glob_var = 50
defread_global():
   print(glob_var)
def write_global1(x):
   global glob_var
   glob_var = x
def write_global2(x):
   glob_var = x
read_global()
write_global1(100)
read_global()
write_global2(150)
read_global()

Output

50
100
100

The lambda Keyword

The lambda keyword is used to make some anonymous function. For anonymous functions, there is no name. It is like an inline function. There is no return statement in the anonymous functions.

Example code

Live Demo

#Keyword lambda
square = lambda x: x**2
for item in range(5, 10):
   print(square(item))

Output

25
36
49
64
81

The nonlocal Keyword

The nonlocal keyword is used do declare a variable in a nested function is not local to it. So it is local for the outer function, but not the inner function. This keyword is used to modify some nonlocal variable value, otherwise it is in read only mode.

Example code

#Keyword nonlocal
defouter():
   x = 50
   print('x from outer: ' + str(x))
   definner():
      nonlocal x
      x = 100
      print('x from inner: ' + str(x))
   inner()
   print('x from outer: ' + str(x))
outer()

Output

x from outer: 50
x from inner: 100
x from outer: 100

The pass Keyword

The pass keyword is basically the null statement in Python. When the pass is executed, nothing happens. This keyword is used as a placeholder.

Example code

#Keyword pass
defsample_function():
   pass #Not implemented now
sample_function()

Output

 
(No Output will come)

The while, break, continue, and Keywords

The while is the while loop in Python. The break statement is used to come out from the current loop, and the control moves to the section, which is immediately below the loop. The continue is used to ignore the current iteration. It moves to the next iteration in different loops.

The and keyword is used for logical and operation in Python, when both of the operands are true, it returns a True value.

Example code

#Keywords while, break, continue, and
i = 0
while True:
   i += 1
   if i>= 5 and i<= 10:
      continue #skip the next part
   elifi == 15:
      break #Stop the loop
   print(i)

Output

1
2
3
4
11
12
13
14

The with, as Keywords

The with statement is used to wrap the execution of a set of codes, within a method, which is defined by the context manager. The as keyword is used to create an alias.

Example code

#Keyword with, as
with open('sampleTextFile.txt', 'r') as my_file:
   print(my_file.read())

Output

Test File.
We can store different contents in this file
~!@#$%^&*()_+/*-+\][{}|:;"'<.>/,'"]

The yield Keyword

The yield keyword is used to return a generator. The generator is an iterator. It generates one element at a time.

Example code

#Keyword yield
defsquare_generator(x, y):
   for i in range(x, y):
      yield i*i
my_gen = square_generator(5, 10)
for sq in my_gen:
   print(sq)

Output

25
36
49
64
81

The del, or Keywords

The del keyword is used to delete the reference of an object. And the or keyword performs the logical or operation. When at least one of the operands is true, the answer will be true.

Example code

#Keywords del, or
my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110]
index = []
for i in range(len(my_list)):
   if my_list[i] == 30 or my_list[i] == 60:
      index.append(i)
for item in index:
   del my_list[item]
print(my_list)

Output

[10, 20, 40, 50, 60, 80, 90, 100, 110]

The assert Keyword

The assert statement is used for debugging. When we want to check the internal states, we can use assert statement. When the condition is true, it returns nothing, but when it is false, the assert statement will raise AssertionError.

Example code

#Keyword assert
val = 10
assert val > 100

Output

---------------------------------------------------------------------------
AssertionErrorTraceback (most recent call last)
<ipython-input-12-03fe88d4d26b> in <module>()
      1#Keyword assert
      2val=10
----> 3assertval>100

AssertionError: 

The None Keyword

The None is a special constant in Python. It means null value or absence of value. We cannot create multiple none objects, but we can assign it to different variables.

Example code

#Keyword None
deftest_function(): #This function will return None
   print('Hello')
x = test_function()
print(x)

Output

Hello
None

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements