The Wayback Machine - https://web.archive.org/web/20230513142351/https://www.geeksforgeeks.org/python-keywords/amp/

Python Keywords

Python Keywords: Introduction

Keywords in Python are reserved words that can not be used as a variable name, function name, or any other identifier.

List of all keywords in Python

andasassertbreak
classcontinuedefdel
elifelseexceptFalse
finallyforfromglobal
ifimportinis
lambdaNonenonlocalnot
orpassraisereturn
Truetrywhilewith
yield   

We can also get all the keyword names using the below code.

Example: Python Keywords List 




# Python code to demonstrate working of iskeyword()
 
# importing "keyword" for keyword operations
import keyword
 
# printing all keywords at once using "kwlist()"
print("The list of keywords is : ")
print(keyword.kwlist)
Output
The list of keywords is : 
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

Output:

The list of keywords is : 

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

Let’s discuss each keyword in detail with the help of good examples.

True, False, None

Example: True, False, and None Keyword




print(False == 0)
print(True == 1)
 
print(True + True + True)
print(True + False + False)
 
print(None == 0)
print(None == [])
Output
True
True
3
1
False
False

and, or, not, in, is

3 and 0 returns 0 

3 and 10 returns 10 

10 or 20 or 30 or 10 or 70 returns 10 

The above statements might be a bit confusing to a programmer coming from a language like C where the logical operators always return boolean values(0 or 1). Following lines are straight from the python docs explaining this:

The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

Note that neither and nor or restrict the value and type they return to False and True, but rather return the last evaluated argument. This is sometimes useful, e.g., if s is a string that should be replaced by a default value if it is empty, the expression s or ‘foo’ yields the desired value. Because not has to create a new value, it returns a boolean value regardless of the type of its argument (for example, not ‘foo’ produces False rather than ”.)

3 or 0 returns 3 

3 or 10 returns 3 

0 or 0 or 3 or 10 or 0 returns 3 

Example: and, or, not, is and in keyword




# showing logical operation
# or (returns True)
print(True or False)
 
# showing logical operation
# and (returns False)
print(False and True)
 
# showing logical operation
# not (returns False)
print(not True)
 
# using "in" to check
if 's' in 'geeksforgeeks':
    print("s is part of geeksforgeeks")
else:
    print("s is not part of geeksforgeeks")
 
# using "in" to loop through
for i in 'geeksforgeeks':
    print(i, end=" ")
 
print("\r")
 
# using is to check object identity
# string is immutable( cannot be changed once allocated)
# hence occupy same memory location
print(' ' is ' ')
 
# using is to check object identity
# dictionary is mutable( can be changed once allocated)
# hence occupy different memory location
print({} is {})

Output: 

True
False
False
s is part of geeksforgeeks
g e e k s f o r g e e k s 
True
False

Iteration Keywords – for, while, break, continue

Example: For, while, break, continue keyword




# Using for loop
for i in range(10):
 
    print(i, end=" ")
 
    # break the loop as soon it sees 6
    if i == 6:
        break
 
print()
 
# loop from 1 to 10
i = 0
while i < 10:
 
    # If i is equals to 6,
    # continue to next iteration
    # without printing
    if i == 6:
        i += 1
        continue
    else:
        # otherwise print the value
        # of i
        print(i, end=" ")
 
    i += 1
Output
0 1 2 3 4 5 6 
0 1 2 3 4 5 7 8 9 

Conditional keywords – if, else, elif

Example: if, else, and elif keyword




# Python program to illustrate if-elif-else ladder
#!/usr/bin/python
 
i = 20
if (i == 10):
    print("i is 10")
elif (i == 20):
    print("i is 20")
else:
    print("i is not present")
Output
i is 20

Note: For more information, refer to out Python if else Tutorial.

def

def keyword is used to declare user defined functions.

Example: def keyword




# def keyword
def fun():
    print("Inside Function")
 
 
fun()
Output
Inside Function

Return Keywords – Return, Yield

Example: Return and Yield Keyword




# Return keyword
def fun():
    S = 0
 
    for i in range(10):
        S += i
    return S
 
 
print(fun())
 
# Yield Keyword
 
 
def fun():
    S = 0
 
    for i in range(10):
        S += i
        yield S
 
 
for i in fun():
    print(i)
Output
45
0
1
3
6
10
15
21
28
36
45

class

class keyword is used to declare user defined classes.

Example: Class Keyword




# Python3 program to
# demonstrate instantiating
# a class
 
 
class Dog:
 
    # A simple class
    # attribute
    attr1 = "mammal"
    attr2 = "dog"
 
    # A sample method
    def fun(self):
        print("I'm a", self.attr1)
        print("I'm a", self.attr2)
 
 
# Driver code
# Object instantiation
Rodger = Dog()
 
# Accessing class attributes
# and method through objects
print(Rodger.attr1)
Rodger.fun()
Output
mammal
I'm a mammal
I'm a dog

Note: For more information, refer to our Python Classes and Objects Tutorial .

With

with keyword is used to wrap the execution of block of code within methods defined by context manager. This keyword is not used much in day to day programming.

Example: With Keyword




# using with statement
with open('file_path', 'w') as file:
    file.write('hello world !')

as

as keyword is used to create the alias for the module imported. i.e giving a new name to the imported module. E.g import math as mymath.

Example: as Keyword




import math as gfg
 
print(gfg.factorial(5))
Output
120

pass

pass is the null statement in python. Nothing happens when this is encountered. This is used to prevent indentation errors and used as a placeholder.

Example: Pass Keyword




n = 10
for i in range(n):
 
    # pass can be used as placeholder
    # when code is to added later
    pass
Output
 

Lambda

Lambda keyword is used to make inline returning functions with no statements allowed internally. 

Example: Lambda Keyword




# Lambda keyword
g = lambda x: x*x*x
 
print(g(7))
Output
343

Import, From

Example: Import, From Keyword




# import keyword
from math import factorial
import math
print(math.factorial(10))
 
# from keyword
print(factorial(10))
Output
3628800
3628800

Exception Handling Keywords – try, except, raise, finally, and assert

Example: try, except, raise, finally, and assert Keywords




# initializing number
a = 4
b = 0
 
# No exception Exception raised in try block
try:
    k = a//b  # raises divide by zero exception.
    print(k)
 
# handles zerodivision exception
except ZeroDivisionError:
    print("Can't divide by zero")
 
finally:
    # this block is always executed
    # regardless of exception generation.
    print('This is always executed')
 
# assert Keyword
# using assert to check for 0
print("The value of a / b is : ")
assert b != 0, "Divide by 0 error"
print(a / b)
 
# raise keyword
# Raises an user defined exception
# if strings are not equal
temp = "geeks for geeks"
if temp != "geeks":
    raise TypeError("Both the strings are different.")

Output

Can't divide by zero
This is always executed
The value of a / b is :
AssertionError: Divide by 0 error




# raise keyword
# Raises an user defined exception
# if strings are not equal
temp = "geeks for geeks"
if temp != "geeks":
    raise TypeError("Both the strings are different.")

Output

TypeError: Both the strings are different.

Note: For more information refer to our tutorial Exception Handling Tutorial in Python.

del

del is used to delete a reference to an object. Any variable or list value can be deleted using del.

Example: del Keyword




my_variable1 = 20
my_variable2 = "GeeksForGeeks"
 
# check if my_variable1 and my_variable2 exists
print(my_variable1)
print(my_variable2)
 
# delete both the variables
del my_variable1
del my_variable2
 
# check if my_variable1 and my_variable2 exists
print(my_variable1)
print(my_variable2)

Output

20
GeeksForGeeks
NameError: name 'my_variable1' is not defined

Global, Nonlocal

Example: Global and nonlocal keywords




# global variable
a = 15
b = 10
 
# function to perform addition
def add():
    c = a + b
    print(c)
 
# calling a function
add()
 
# nonlocal keyword
def fun():
    var1 = 10
 
    def gun():
        # tell python explicitly that it
        # has to access var1 initialized
        # in fun on line 2
        # using the keyword nonlocal
        nonlocal var1
         
        var1 = var1 + 10
        print(var1)
 
    gun()
fun()
Output
25
20

Note: For more information, refer to our Global and local variables tutorial in Python.

This article is contributed by Manjeet Singh(S. Nandini). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


Article Tags :