Python Keywords

Python keywords are reserved words that cannot be used for any other purpose such as variable names, function names, or other identifiers. Like other programming languages, all keywords are available without any import statement.

Currently, there are 35 keywords in Python.

1. How to List all Keywords

We can get a list of available keywords in the current Python version using the help() command.

>>> help("keywords")

Program output.

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

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

To get the information of a specific keyword, pass the keyword name into help() command.

>>> help("break")

The program output.

The "break" statement
*********************

break_stmt ::= "break"

"break" may only occur syntactically nested in a "for" or "while"
loop, but not nested in a function or class definition within that
loop.

It terminates the nearest enclosing loop, skipping the optional "else"
clause if the loop has one.

2. Using Python Keywords

The following table summarizes all the keywords in Python programming language, and how to use these keywords with simple examples.

Keyword TypeKeywords List
Value KeywordsTrue, False, None
Operator Keywordsand, or, not, in, is
Flow Control Keywordsif, elif, else, for, while, break, continue, else
Structural Keywordsdef, class, with, as, pass, lambda
Import Keywordsimport, from
Variable Declaration Keywordsdel, global, nonlocal
Value Returning Keywordsreturn, yield
Exception Handling Keywordstry, except, raise, finally, assert
Asynchronous Programming Keywordsasync, await

2.1. Value Keywords

Value keywords are assigned as values to the variables.

# True

Boolean value and same as 1. It is the result of a comparison operation.

print(5 < 6)  #True

# False

Boolean value and same as 0. It is the result of a comparison operation.

print(5 > 6)  #False

# None

It is used to define a null value, or no value at all. None is not the same as 0, False, or an empty string. None is a datatype of its own (NoneType) and only None can be None.

x = None

if x:
  print("x is True")
elif x is False:
  print ("x is False")
else:
  print("x is None")    #Prints 'x is None'

2.2. Operator Keywords

Operator keywords are used to compare a given value or expression against another value or expression. They produce a boolean result.

# and

logical AND operator. Return True if both statements are True.

x = (5 > 3 and 5 > 10)
print(x)  #False

# or

logical OR operator. Returns True if either of two statements is true. If both statements are false, the returns False.

x = (5 > 3 or 5 > 10)
print(x)  #True

# not

A logical operator and reverses the value of True or False.

x = False
print(not x)  #True

# in

It is used to check if a value is present in a sequence (list, range, string etc.). Also used to iterate through a sequence in a for loop.

fruits = ["apple", "banana", "cherry"]

if "banana" in fruits:
    print("yes")
 
for x in fruits:
    print(x)

# is

It is used to test if two variables refer to the same object.

a = ["apple", "banana", "cherry"]
b = ["apple", "banana", "cherry"]
c = a
 
print(a is b) # False
print(a is c) # True

2.3. Flow Control Keywords

Flow control keywords are used to control the application flow and write conditional statements.

# if

It is used to create conditional statements that allows us to execute a block of code only if a condition is True.

x = 5
 
if x > 3:
  print("The statement is true")

# elif

It is used in conditional statements and is short for else if.

i = 5
 
if i > 0:
      print("Positive")
  elif i == 0:
      print("ZERO")
  else:
      print("Negative")

# else

It decides what to do if the condition is False in if..else statement.

i = 5
 
if i > 0:
      print("Positive")
  else:
      print("Negative")

It can also be use in try...except blocks.

try:
    x > 10
except:
    print("Something went wrong")
else:
    print("Normally execute the code")

# for

It is used to create a for loop. A for loop can be used to iterate through a sequence, like a list, tuple, etc.

for x in range(1, 9):
    print(x)

# while

It is used to create a while loop. The loop continues until the conditional statement is false.

x = 0
 
while x < 9:
    print(x)
    x = x + 1

# break

It is used to break out a for loop, or a while loop.

i = 1
 
while i < 9:
    print(i)
    if i == 3:
      break
    i += 1

# continue

It is used to end the current iteration in a for loop (or a while loop), and continues to the next iteration.

for i in range(9):
    if i == 3:
      continue
    print(i)

# else

It decides what to do if the condition is False in if..else statement.

i = 5
 
if i > 0:
      print("Positive")
  else:
      print("Negative")

It can also be use in try…except blocks.

x = 5
 
try:
    x > 10
except:
    print("Something went wrong")
else:
    print("Normally execute the code")

2.4. Structural Keywords

Structural Keywords are used to declare and create various language constructs such as classes etc.

# def

It is used to create or define a function.

def my_function():
  print("Hello world !!")
 
my_function()

# class

It is used to create a class.

class User:
  name = "John"
  age = 36

# with

It is used to simplify exception handling.

# as

It is used to create an alias.

import calendar as c
print(c.month_name[1])  #January

# pass

t is used as a placeholder for future code. When the pass statement is executed, nothing happens, but you avoid getting an error when an empty code is not allowed.

Empty code is not allowed in loops, function definitions, class definitions, or in if statements.

for x in [0, 1, 2]:
        pass

# lambda

It is used to create small anonymous functions. They can take any number of arguments, but can only have one expression.

x = lambda a, b, c : a + b + c
 
print(x(5, 6, 2))

2.5. Import Keywords

Import keywords are used to import other classes and modules in the program.

# import

It is used to import modules.

import datetime

# from

It is used to import only a specified section from a module.

from datetime import time

2.6. Variable Declaration Keywords

Variable declaration keywords are used to declare the variables in different scopes.

# del

It is used to delete objects. In Python everything is an object, so the del keyword can also be used to delete variables, lists, or parts of a list, etc.

x = "hello"
 
del x

# global

It is used to create global variables from a no-global scope, e.g. inside a function.

def myfunction():
    global x
    x = "hello"

# nonlocal

It is used to declare that a variable is not local. It is used to work with variables inside nested functions, where the variable should not belong to the inner function.

def myfunc1():
    x = "John"
    def myfunc2():
      nonlocal x
      x = "hello"
    myfunc2()
    return x
 
print(myfunc1())

2.7. Value Returning Keywords

These keywords are used to return the value from function or a program.

# return

It is used to exit a function and return a value.

def sumNum():
        return 3+3

# yield

It is used to end a function and it returns a generator.

2.8. Exception Handling Keywords

These keywords are used to handle the exceptional conditions and throw exceptions where needed in the program.

# try

It defines a block of code ot test if it contains any errors.

# except

It defines a block of code to run if the try block raises an error.

try:
    x > 3
except:
    print("Something went wrong")

# raise

It is used to raise an exception, manually.

x = "hello"
 
if not type(x) is int:
    raise TypeError("Only integers are allowed")

# finally

It defines a code block which will be executed no matter if the try block raises an error or not.

try:
    x > 3
except:
    print("Something went wrong")
finally:
   print("I will always get executed")

# assert

It can be used for debugging the code. It tests a condition and returns True , if not, the program will raise an AssertionError.

x = "hello"
 
assert x == "goodbye", "x should be 'hello'"  # AssertionError

2.9. Asynchronous Programming Keywords

These keywords help writing the asynchronous application flows.

# async

It is used to declare a function as a coroutine, much like what the @asyncio.coroutine decorator does.

async def ping_server(ip):

# await

t is used to call async coroutine.

async def ping_local():
    return await ping_server('192.168.1.1')

Happy Learning !!

Comments

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.