Keywords in Python Python Variables Functions Classes
Keywords in Python Python Variables Functions Classes
Keywords in Python are reserved words that have special meanings and serve specific purposes in
the language syntax. Python keywords cannot be used as the names of variables, functions,
and classes or any other identifier.
or not is if
We can also get all the keyword names using the below code.
import keyword
print(keyword.kwlist)
Output:
The list of keywords are:
['False', 'None', 'True',"__peg_parser__ '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']
With Syntax Highlighting – Most of IDEs provide syntax-highlight feature. You can see Keywords
appearing in different color or style.
Look for SyntaxError – This error will encounter if you have used any keyword incorrectly. Note that
keywords can not be used as identifiers (variable or a function name).
Let’s categorize all keywords based on context and understand each with help of example.
Category Keywords
Control Flow if, else, elif, for, while, break, continue, pass, try, except, finally, raise,
Keywords assert
None: This is a special constant used to denote a null value or a void. It’s important to remember
that 0, any empty container(e.g. empty list) does not compute to None. It is an object of its datatype
– NoneType. It is not possible to create multiple None objects and can assign them to variables.
print(False == 0)
print(True == 1)
print(None == 0)
print(None == [])
Output
True
True
False
False
not keyword – returns ‘True’ if the expression is ‘False’, and vice versa.
a = True
b = False
# Logical operations
in keyword (membership operator) – Check if a value exists in a sequence (like a list, tuple,
or string). It returns True if value is found.
# example 1
print(3 in [1,2,3])
# example 2
if 's' in 'geeksforgeeks':
else:
is keyword – Check if two variables point to the same object in memory. It returns True if the
objects are identical.
# example 1
print(2 is 2)
# example 2
a = [1, 2, 3]
b=a
c = [1, 2, 3]
print(a is b)
print(a is c)
x=0
if x > 0:
print("Positive")
elif x < 0:
print("Negative")
else:
print("Zero")
while: Has a similar working like “for”, used to control flow and for looping.
break: “break” is used to control the flow of the loop. The statement is used to break out of
the loop and passes the control to the statement following immediately after loop.
continue: “continue” is also used to control the flow of code. The keyword skips the current
iteration of the loop but does not end the loop.
if num == 2:
print(num)
# Output: 0 1
count = 0
count += 1
if count == 3:
print(count)
# Output: 1 2
pass keyword: 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.
The code contains a for loop that iterates 10 times with a placeholder statement ‘pass',
indicating no specific action is taken within the loop.
n = 10
for i in range(n):
# pass can be used as placeholder
pass
try : This keyword is used for exception handling, used to catch the errors in the code using
the keyword except. Code in “try” block is checked, if there is any type of error, except block
is executed.
finally : No matter what is result of the “try” block, “finally” is always executed.
assert: This function is used for debugging purposes. Usually used to check the correctness
of code. If a statement is evaluated to be true, nothing happens but when it is false,
” AssertionError ” is raised. One can also print a message with the error, separated by a
comma .
Example 1: The provided code demonstrates the use of several keywords in Python:
1. try and except : Used to handle exceptions, particularly the ZeroDivisionError , and print an
error message if it occurs.
2. finally : This block is always executed, and it prints “This is always executed” regardless of
whether an exception occurs.
3. assert : Checks a condition, and if it’s False , raises an AssertionError with the message
“Divide by 0 error.”
4. raise : Raises a custom exception ( TypeError ) with a specified error message if a condition is
not met.
a, b = 4, 0
try:
print(k)
except ZeroDivisionError:
finally:
# This block is always executed regardless of the exception
print(a / b)
if temp != "geeks":
Output
Example 2: This code uses the raise keyword to raise a custom TypeError exception if two strings are
not equal.
if temp != "geeks":
Output
Note: For more information refer to our tutorial Exception Handling Tutorial in Python.
del is used to delete a reference to an object. Any variable or list value can be deleted using del.
s = "GeeksForGeeks"
print(s)
del s
print(s)
Output
def keyword – Defines a function named fun using the def keyword. When the function is
called using fun().
def fun():
print("Inside Function")
fun()
Output
Inside Function
class Dog:
attr1 = "mammal"
attr2 = "dog"
Note: For more information, refer to our Python Classes and Objects Tutorial .
yield : This keyword is used like return statement but is used to return a generator.
The ‘return' keyword is used to return a final result from a function, and it exits the function
immediately. In contrast, the ‘yield' keyword is used to create a generator, and it allows the function
to yield multiple values without exiting. When ‘return' is used, it returns a single value and ends the
function, while ‘yield' returns multiple values one at a time and keeps the function’s state.
# Return keyword
def fun():
s=2
# Return the value of S
return s
print(fun())
# Yield Keyword
def fun():
yield 1
yield 2
yield 3
print(value)
Output
2
1
2
3
Lambda keyword is used to make inline returning functions with no statements allowed internally.
# Lambda keyword
g = lambda x: x*x*x
print(g(7))
Output
343
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.
This code demonstrates how to use the with statement to open a file named 'file_path' in write
mode ('w'). It writes the text 'hello world !'to the file and automatically handles the opening and
closing of the file. with statement is used for better resource management and ensures that the file
is properly closed after the block is executed.
as Keyword In Python
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.
This code uses the Python math module, which has been imported with the alias gfg. It calculates
and prints the factorial of 5. The math.factorial() function is used to calculate the factorial of a
number, and in this case, it calculates the factorial of 5, which is 120.
print(gfg.factorial(5))
Output
120
import : This statement is used to include a particular module into current program.
from : Generally used with import, from is used to import particular functionality from the module
imported.
The ‘import' keyword is used to import modules or specific functions/classes from modules, making
them accessible in your code. The ‘from' keyword is used with‘import' to specify which specific
functions or classes you want to import from a module. In your example, both approaches import
the ‘factorial' function from the ‘math' module, allowing you to use it directly in your code.
# import keyword
print(math.factorial(10))
# from keyword
print(factorial(10))
Output
3628800
3628800
global: This keyword is used to define a variable inside the function to be of a global scope.
non-local : This keyword works similar to the global, but rather than global, this keyword declares a
variable to point to variable of outside enclosing function, in case of nested functions.
In this code, the ‘global' keyword is used to declare global variables ‘a' and ‘b'. Then, there’s a
function ‘add' that adds these global variables and prints the result.
The second part of the code demonstrates the ‘nonlocal' keyword. The function fun contains a
variable var1, and within the nested function gun, we use nonlocal to indicate that we want to
modify the var1 defined in the outer function fun. It increments the value of var1and prints it.
a = 15
b = 10
def add():
c=a+b
print(c)
add() # Output: 25
def fun():
var = 10
def gun():
nonlocal var
var += 10
print(var)
gun()
fun() # Output: 20
Output
25
20
Note: For more information, refer to our Global and local variables tutorial in Python.
Async programming allows you to run tasks concurrently, improving efficiency, especially when
dealing with I/O-bound operations. The async and await keywords in Python are used to define and
manage asynchronous functions.
async: Used to declare a function as asynchronous, allowing it to run concurrently with other tasks.
import asyncio
await: Used to pause the execution of an async function until the awaited task is complete.
import asyncio
await func()
asyncio.run(main())