List of all Keywords and Identifiers in Python
Python Keywords and Identifiers
Keywords in Python
Python Keywords and Meanings
Python Keywords with Examples
Python Keywords
Python keywords are special reserved words that have specific meanings and purposes. Python keyword cannot be used as variable name, function name, or any other identifier.
The latest version of Python is 3.9. Python 3.9 has a set of keywords that are reserved words that cannot be used as variable names, function names, or identifiers. In other words Python keywords are special reserved words that have specific meanings and purpose.
Python Keywords are used to define the syntax and structure of the Python programming language. All Keywords in Python are case sensitive. They must be spelled exactly as it is. All keywords in python are in lower case letters except these 3 keywords (True, False and None).
What is a Python Keyword ?
A python keyword is a reserved word which should not use as a variable name, class name, function name.
What are Keywords in Python ?
Keywords are the reserved words in Python. We cannot use a keyword as a variable name, function name or any other identifier. Keywords in Python are case sensitive.
Is print a keyword in Python ?
In Python 3.+ it is not a keyword but it is a keyword in Python 2. The print has been removed from Python 2 as keyword and included as built-in function in Python 3.
All keywords in python are in lowercase or uppercase ?
In Python all the keywords are case sensitive. All keywords in python are in lowercase letters except these 3 keywords (True, False and None are in title case).
Which Keywords are Capitalized in Python ?
True, False and None keywords are capitalized while the other keywords are in lower case in Python. In Python, keywords are case sensitive.
How Many Keywords are there in Python Programming Language ?
There are 36 keywords in Python 3.9 programming language. These keywords are always available, you need not to import them into your code. Python keywords are different from Python's built-in functions and Python Data Types. The built-in functions and data types are also always available. Following are the list of all Keywords in Python Programming Language
List of Keywords in Python Programming
List of All Python Keywords
How to Get and Print all Keywords from Python ?
For printing the list of all the keywords from Python, you should use the "keyword.kwlist" statement after importing the "keyword" module. It returns the list of all the keywords available in the installed Python version. Following Python programme prints the list of all the keywords from Python.
How to Get and Print all Keywords from Python Example
import keyword print(keyword.kwlist)
The above programme will print the list of Python keywords as follows.
['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']
How to get the Python keywords list on your operating system ?
Run the command prompt and type python then press enter. After that type help() and hit enter. Then after type keywords and press enter to get the list of Python keywords for the current Python version running on your operating system.
The Python help shows the Python keywords list as Here is a list of the Python keywords. Enter any keyword to get more help. Following screen shot showing the list of keywords from Python help.
List of Python Keywords and Description with Examples
Python Keywords and Identifiers with examples
What is False Keyword in Python ?
The False keyword is a Boolean value, and result of a comparison operation. The False keyword is the same as 0 zero. True and False are truth values in Python. They are the results of comparison operations or logical (Boolean) operations in Python. The below print(3 > 7) statement returns False.
Note : The False keyword in Python is a title case keyword, so False keyword's first letter must be in capital letter.
False Keyword Example
print(3 > 7) false_variable = False if false_variable: print("This is True Statement") else: print("This is False Statement")
What is None Keyword in Python ?
None is a special constant in Python that represents the absence of a value or a null value. The None keyword in Python is used to define a null value or no value at all. Void functions that do not return anything will return a None object automatically. None is also returned by functions in which the program flow does not encounter a return statement.
Note : The None keyword in Python is a title case keyword, so None keyword's first letter must be in capital letter.
None Keyword Example
none_variable = None if none_variable: print("None is True") else: print("None is not True")
What is True Keyword in Python ?
The True keyword is a Boolean value, and result of a comparison operation. Other than 0 zero is True. True and False are truth values in Python. They are the results of comparison operations or logical (Boolean) operations in Python. The below print(3 < 7) statement returns True.
Note : The True keyword in Python is a title case keyword, so True keyword's first letter must be in capital letter.
True Keyword Example
print(3 < 7) true_variable = True if true_variable: print("This is True Statement") else: print("This is False Statement")
What is __peg_parser__ Keyword in Python ?
The __peg_parser__ keyword is a new keyword in Python 3.9. The __new_parser__ was renamed to __peg_parser__ recently.
What is and Keyword in Python ?
The and keyword is a logical operator. and, or, not are the logical operators in Python. Logical operators are used to combine conditional statements. The return value will only be True if both statements return True, otherwise it will return False.
and Keyword Example
x = 7 y = 8 if x > 3 and y < 10: print("Both statements are True") else: print("At least one statement is False")
What is as Keyword in Python ?
The as keyword is used to create an alias. as is used to create an alias while importing a module. It means giving a different name to a module while importing it in Python.
as Keyword Example
import calendar as c print(c.month_name[1])
What is assert Keyword in Python ?
The assert keyword is used when debugging code. The assert keyword lets you test if a condition in your code returns True, if not, the program will raise an AssertionError. assert is check if our assumptions are true. assert find bugs more conveniently. assert is followed by a condition.
assert Keyword Example
= "welcome" # if condition returns False, AssertionError is raised assert x == "good bye", "x should be welcome"
What is async and await Keyword in Python ?
The async and await keywords are provided by the asyncio library in Python. They are used to write concurrent code in Python. The async keyword is equal to synchronized keyword in Java.
async and await Keyword Example
import asyncio async def main(): print('Hello') await asyncio.sleep(1) print('world') loop = asyncio.get_event_loop() loop.run_until_complete(main()) # asyncio.run(main())
What is break Keyword in Python ?
The break statement is used to break out of a loop. It is used inside for and while loops to alter the normal behaviour. break will end the loop it is in and control flows to the statement immediately below the loop.
break Keyword Example
for i in range(1, 11): if i == 7: break print(i)
What is class Keyword in Python ?
The class keyword is used to define a new user defined class in Python. Class is a collection of related attributes and methods. Classes can be defined anywhere in a program. But it is a good practice to define a single class in a module.
class Keyword Example
class Person: name = "HudaTutorials.com" def print_person_name(self): print("Name : " + self.name) p = Person() p.print_person_name()
You may have noticed the self parameter in function definition inside the class but we called the method simply as p.printPersonName() without any arguments.
In Python programme calling a method with a list of n arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method's object before the first argument.
The first argument of the function in class must be the object itself. This is conventionally called self. You can named it yourself.
What is continue Keyword in Python ?
The continue keyword is used to end the current iteration in a for loop or a while loop, and continues to the next iteration. The continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not terminate but continues on with the next iteration.
continue Keyword Example
for i in range(1, 11): if i == 7: continue print(i)
What is def Keyword in Python ?
The def keyword is used to create or define a user defined function in Python. Function or Method is a block of related statements, which together does some specific task.
Which keyword is used to define methods in Python ?
The def keyword is used to define methods in Python. Python has simple rules to define a function in Python. Function blocks begin with the keyword def followed by the function name and parentheses ( ) ends with colon : . The colon : is used to define a block of code in Python.
def Keyword Example
def say_hello(): print("This is Python function definition") print("Hello Welcome to Python Keywords Tutorial") say_hello()
What is del Keyword in Python ?
The del keyword 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.
del Keyword Example
python_variable = "This is Python variable" # del KEYWORD DELETE THE PYTHON VARIABLE del python_variable try: # BELOW STATEMENT SHOWS VARIABLE CAN BE UNDEFINED WARNING print(python_variable) except NameError: print("Python variable is not defined") else: print("sure, Python variable was defined")
What is elif Keyword in Python ?
The elif keyword is used in conditional statements. It is same as else if.
elif Keyword Example
a = 7 if a == 1: print('One') elif a == 7: print('It is Seven') else: print('Something else')
What is else Keyword in Python ?
The else keyword is used in conditional statements (if statements), and decides what to do if the condition is False. The else keyword can also be use in try...except blocks. The else keyword in a try...except block to define what to do if no errors were raised.
else Keyword Example
a = 7 if a == 1: print('One') else: print('else statement executed')
What is except Keyword in Python ?
The except keyword is used in try...except blocks. It defines a block of code to run if the try block raises an error.
except Keyword Example
try: x = 1 / 0 except ZeroDivisionError: print("You cannot divide with zero")
What is finally Keyword in Python ?
The finally keyword is used to create a block of code that follows a try block. The finally block of code is always executed whether an exception has occurred or not. The finally block is useful to close objects and clean up resources.
finally Keyword Example
try: print(10 / 2) except ZeroDivisionError: print("You cannot divide with zero") else: print("No Exception occurred") finally: print("Python Programme Execution Completed")
What is for Keyword in Python ?
A for keyword is used to create a for loop. We use for when we know the number of times we want to loop. In Python for keyword is used to iterate through a sequence, list and tuple.
for Keyword Example
# PYTHON FOR LOOP EXAMPLE for i in range(1, 11): print(i)
What is from Keyword in Python ?
The from keyword is used to import only a specified section from a module. In other words from is used to import specific attribute or function into the current namespace.
from Keyword Example
from math import cos print(cos(0))
What is global Keyword in Python ?
The global keyword is used to create global variables. global is used to declare that a variable inside the function is global i.e. outside the function scope.
global Keyword Example
x = "Welcome" def my_function(): global x x = "Hello World" my_function() # GLOBAL SCOPE print(x)
What is if Keyword in Python ?
The if keyword is used to create conditional statements (if statements), and allows you to execute a block of code only if a condition is True.
if Keyword Example
x = 7 if x > 1: print(str(x) + " is greater than 1")
What is import Keyword in Python ?
The import keyword is used to import modules into the current namespace. Below example import the datetime module and display the system date and time. In other words import keyword is used to import other modules into a Python script. For example we can use the import keyword to import the math module into the namespace. The as keyword is used to give a module a different alias. The import keyword uses Python's module import mechanism to load a module.
import Keyword Example
import datetime system_date_and_time = datetime.datetime.now() print(system_date_and_time)
What is in Keyword in Python ?
The in keyword is used to check if a value is present in a sequence (list, range, string). Another usage of in keyword is also used to iterate through a sequence in a for loop. The in keyword returns True if the value is present, else it returns False.
in Keyword Example
fruits = ["apple", "banana", "orange"] if "orange" in fruits: print("Yes fruits contains orange") arr = [7, 2, 9, 1, 3] for i in arr: print(i)
What is is Keyword in Python ?
The is keyword is used for testing object identity in Python. It is used to test if the two variables refer to the same object. The is keyword returns True if the objects are identical and False if are not identical.
is Keyword Example
arr1 = ["apple", "banana", "orange"] arr2 = arr1 print(arr1 is arr2) x = ["apple", "banana", "orange"] y = ["apple", "banana", "orange"] print(x is y)
What is lambda Keyword in Python ?
The lambda keyword is used to create an anonymous function (function with no name). It is an inline function that does not contain a return statement. It consists of an expression that is evaluated and returned.
A lambda function can take any number of arguments, but can only have one expression. The expression is evaluated and the result is returned.
lambda Keyword Example
my_function = lambda x: x + 2 print(my_function(5)) sum_of_two_no = lambda x, y: x + y print(sum_of_two_no(5, 3))
What is nonlocal Keyword in Python ?
The nonlocal keyword indicates that particular variables live in an enclosing scope and should be rebound there. The nonlocal keyword is used to work with variables inside nested functions, where the variable should not belong to the inner function. Use the keyword nonlocal to declare that the variable is not local.
nonlocal Keyword Example
def func1(): a = 3 def func2(): nonlocal a a = 7 print("Inner function: ", a) func2() print("Outer function: ", a) func1()
What is not Keyword in Python ?
The not keyword is the logical operator in Python. The not operator is used to invert the truth value. The not keyword will return True if the statement(s) are not True, otherwise it will return False.
not Keyword Example
x = False print(not x)
What is or Keyword in Python ?
The or keyword is the logical operator in Python. The or keyword used to combine conditional statements. The or keyword will return True if any of the operands is True, otherwise it will return False.
or Keyword Example
x = 7 if x > 1 or x < 10: print("x is greater than 1 or less than 10") else: print("Condition Fails")
What is pass Keyword in Python ?
The pass is a null statement in Python. Nothing happens when it is executed. It is used as a placeholder. Empty code is not allowed in loops, function definitions, class definitions, or in if statements. If we have a function that is not implemented yet, but we want to implement it in the future, it will throw IndentationError exception. Instead of this, we construct a blank body with the pass statement. We can do the same thing in an empty class as well.
pass Keyword Example
def func1(args): pass class Person: pass print("Successfully Executed")
What is raise Keyword in Python ?
The raise keyword is used to raise an exception. The raise keyword is equal to throw keyword in Java. We can raise an exception explicitly with the raise keyword. You can raise exceptions of user defined exceptions as well as Python system defined exceptions using the raise keyword of Python.
raise Keyword Example
myvar = "" if myvar == None or myvar == "": raise ValueError("Value should not Blank")
What is return Keyword in Python ?
The return keyword is used inside a function to exit it and return a value. If you won't return a value explicitly, None is returned automatically in Python.
return Keyword Example
def func1(): x = 7 return x def func2(): a = 10 # 7 is returned print(func1()) # None is returned automatically print(func2())
What is try Keyword in Python ?
Python try keyword is used in exception handling in Python programming language. It is same as try keyword in Java programming language. The try keyword is used in try...except blocks. It defines a block of code test if it contains any errors. You can define different blocks for different error types.
try Keyword Example
try: x = 1 / 0 except: print("Something went wrong")
What is while Keyword in Python ?
The while keyword is used to create a while loop. The statements inside a while loop continue to execute until the condition for the while loop evaluates to False or a break statement is encountered.
while Keyword Example
x = 1 while x <= 10: print(x) x = x + 1
What is with Keyword in Python ?
The with keyword is used to wrap the execution of a block of code within methods defined by the context manager. Context managers are a really helpful structure in Python. Each context manager executes specific code before and after the statements you specify.
Using with gives you a way to define code to be executed within the context manager's scope. The most basic example of this is when you are working with file I/O in Python. After the code is executed, the file pointer closes automatically. Even if your code in the with block raises an exception, the file pointer would still close.
with Keyword Example
with open("yourtextfile.txt") as text_file: for text in text_file: print(text.strip())
What is yield Keyword in Python ?
The yield keyword is used inside a function like a return statement. But yield returns a generator. When a function has a yield statement, what gets returned is a generator. The generator can then be passed to Python's built-in next() to get the next value returned from the function.
When you call a function with yield statements, Python executes the function until it reaches the first yield keyword and then returns a generator. These are known as generator functions.
In other words yield is a keyword in Python that is used to return from a function without destroying the states of its local variable and when the function is called, the execution starts from the last yield statement. Any function that contains a yield keyword is termed as generator.
What is Generator in Python ?
Generator is an iterator that generates one item at a time in Python. A large list of values will take up a lot of memory. Generators are useful in this situation as it generates only one value at a time instead of storing all the values in memory.
When to use yield keyword instead of return keyword in Python ?
You can use yield keyword in a generator function is defined like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return.
yield Keyword Example
def get_countries(): yield "India" yield "USA" yield "Canada" yield "United Kingdom" country_names = get_countries() print(next(country_names)) print(next(country_names))