List of Python Keywords (With Examples)

List of Python Keywords (With Examples)

13 Apr 2024
Beginner
81 Views
19 min read
Learn via Video Course & by Doing Hands-on Labs

Python Programming For Beginners Free Course

List of Python Keywords: An Overview

Python Keywords are one of the very beginner concepts of the Python language that you definitely need to know for basic Python programs. In this Python Tutorial, you will get to know What is Keywords in Python with examples, Types of Keywords in Python, How to identify Python Keywords and their usage. To delve deeper into various concepts of Python, enroll in our Python Certification Training right now!

Read More: Top 50 Python Interview Questions and Answers

What are Python Keywords?

Keywords in Python are predefined words, that are not to be used as any other kind of identifiers like for example, variable names or function names. These keywords are a part of the syntax in the language with a special meaning associated to them. They play a major role in python code by defining its structure and logic.

Here is a list of keywords in Python:

Falseawaitelseimportpass
Nonebreakexceptinraise
Trueclassfinallyisreturn
andcontinueforlambdatry
asdeffromnonlocalwhile
assertdelglobalnotwith
asyncelififoryield

Python keywords might be different depending on the version you're using, as in, some new ones might get introduced or some existing ones might not be there. So it is better to always check what keywords are there. You can do that with the help of 'keyword' module like this:

import keyword

print(keyword.kwlist)

When you run this code in Python Compiler you will get a list of Python keywords printed as in the below output:

Output

['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']

Read More: Python Developer Salary

How to Identify Python Keywords

As we already discussed, that keywords might change depending on what version you're using. So, it's important to check whether the keywords you're using are correct or not. There are a few methods with the help of which you can identify if a word you have used is a keyword or not. These methods are as follows:

  • Use an IDE With Syntax Highlighting

There are several IDEs that provide features like syntax highlighting. What they do is when you write a code in Python using these IDEs with syntax highlighting, the keywords will get highlighted. Keywords appear to be in a different color or style that help the programmers to easily identify them while writing the code or reviewing it.

  • Use Code in a REPL to Check Keywords

You can also use a REPL (Read-Eval-Print Loop) environment like we have Python's interactive interpreter or Jupyter Notebook. They have features that help developers for testing small snippets of code with potential keywords. This will help them verify if the keywords they are using are recognized as a keyword by Python or not so they can make required changes then and there.

  • Look for a SyntaxError

Another method is looking for SyntaxError in your Python code. If you notice that a SyntaxError has occurred, you will know that you have used a keyword incorrectly because keywords can not be used as identifiers in Python like a variable name or a function name.

Classification of Python Keywords

CategoryDescriptionExample
ReservedThe reserved keywords are the ones that are reserved for specific purposes.if, else, for, while, return, etc.
Control FlowThe control flow keywords control the execution flow in Python programs.if, else, elif, for, while, break, continue, return, etc.
DeclarationThe declaration keywords are used for declaring variables, functions, classes and other entities.def, class, lambda, global, nonlocal, etc.
Exception HandlingThe exception handling keywords are used for exception handling purposes.try, except, finally, raise, assert, etc.
MiscellaneousThe miscellaneous keywords have their own unique purposes in python.True, False, None, and, or, not, etc.

Read More: Python Career Opportunities: Is it worth learning Python in 2024?

Python Keywords and Their Usage

Now, let's take a look on the usage of different types of keywords in Python:

1. Value Keywords

The value keywords are used for representing specific values in Python.
  • True, False- They both are used in logical expressions and represent the boolean values 'True' and ' False'.
  • None- It is used to represent that there is no value or it is null.

Example of Value keywords

print(True)
print(False)
print(None)

Output

True
False
None

2. Operator Keywords

The operator keywords are used to perform logical and comparison operations in a Python program.
  • and-It will return 'True' when both the operands are 'True'.
  • or-It will return 'True' when at least one of the operand is 'True'.
  • not-It will return the opposite of the operand.
  • in-It checks that whether a specified value is present in the given sequence.
  • is-It compares the identity of objects.

Example of Operator keywords

a = True
b = False
print(a and b)
print(a or b)
print(not a)
print(5 in [1, 2, 3, 4, 5])
print(5 is 5)

Output

False
True
False
True
True

3. Control Flow Keywords

The control flow keywords are used to execute code blocks with conditional statements.
  • if-It will execute a code block if the condition is 'True'.
  • elif-It is the short form of 'else if'. It will put another alternative condition for checking if the 'if' condition is 'False'.
  • else-It will execute a code block if none of the conditions are 'True'.

Example of Control Flow keywords

x = 10
if x > 5:
    print("x is greater than 5")
elif x == 5:
    print("x is equal to 5")
else:
    print("x is less than 5")

Output

x is greater than 5

4. Iteration Keywords

The iteration keywords are used to control loop execution.
  • for-It iterates over the elements of a specified sequence.
  • while-It will execute a code block as long as the condition is 'True'.
  • break-It is used for terminating the loop before completion.
  • continue-It is used for skipping the current iteration and continue with the next one.
  • else-It will execute a code block when the has completed without a 'break' statement.

Example of Iteration keywords

for i in range(5):
    if i == 3:
        break
    print(i)
else:
    print("Loop completed successfully")

Output

0
1
2

5. Structure Keywords

The structure keywords are used for defining structure of a program.
  • def-It defines a function.
  • class-It defines a class.
  • with-It uses context managers to simplify resource management.
  • as-It renames or aliases imported modules or objects.
  • pass-It indicates that no action needs to be taken.
  • lambda- It creates an anonymous function.

Example of Structure keywords

def example_function():
    pass

class ExampleClass:
    pass

with open('example.txt', 'r') as file:
    data = file.read()

lambda_func = lambda x: x * x
print(lambda_func(5))

Output

25

6. Returning Keywords

The returning keywords are used for returning values from functions and generators.
  • return-It will exit a function and may also return a value.
  • yield-It will stop the execution of a function and will return a value to the caller while the state of the function remains constant.

Read More: Functions in Python

Example of Returning keywords

def example_function():
    return 42

def generator_function():
    yield 1
    yield 2
    yield 3

print(example_function())
print(list(generator_function()))

Output

42
[1, 2, 3]

7. Import Keywords

The import keywords are used for importing symbols and modules in Python.
  • import-It will import a whole module.
  • from-It will import specific symbols from a module.
  • as-It will alias the imported symbols or modules.

Example of Import keywords

import math
from datetime import datetime as dt

print(math.pi)
print(dt.now())

Output

3.141592653589793
<current date and time>

8. Exception-Handling Keywords

The exception handling keywords in Python are used for handling exceptions in a python program.
  • try-It will start and check a code block that may have an exception but not execute it.
  • except-It is used for checking and handling exceptions.
  • raise- It will raise an exception.
  • finally-It will execute a code no matter if any exceptions occurs or not.
  • else-It will execute the code if there is no exception occurring in the 'try' block.
  • assert-When the condition is 'False', an 'AssertionError' is raised to assert a condition.

Example of Exception-Handling keywords

try:
    x = 1 / 0
except ZeroDivisionError:
    print("Error: Division by zero")
else:
    print("No error occurred")
finally:
    print("Cleanup code")

assert 2 + 2 == 4, "Math is broken"

Output

Error: Division by zero
Cleanup code

9. Asynchronous Programming Keywords

The asynchronous programming keywords are used for asynchronous programming in Python.
  • async-It is used for defining a coroutine function.
  • await-It will pause the execution of a coroutine function until its own coroutine function completes.

Example of Asynchronous Programming keywords

import asyncio

async def example_coroutine():
    await asyncio.sleep(1)
    print("Async function executed")

async def main():
    await example_coroutine()

asyncio.run(main())

Output

Async function executed

10. Variable Handling Keywords

The variable handling keywords are used for manipulating and scoping variables in Python.
  • del-It will delete a variable from a collection.
  • global-It is used for declaring a variable with a global scope.
  • nonlocal-It is used for declaring a variable with a scope of the nearest function just outside the current one.

Example of Variable Handling keywords

x = 10
print(x)
del x
print(x)  # Raises NameError because x is deleted

Output

10
NameError: name 'x' is not defined

Summary
Through this article, we introduced different types of keywords used in python with their usage and proper examples. It is important to understand them well and utilize all these keywords in the correct manner to write efficient Python code that is also free from errors. To learn more about other core concepts of Python Programming, consider enrolling in our Python Certification Course.

FAQs

Q1. What are 36 keywords in Python?

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

Q2. What are Python keywords?

Python keywords are specific reserved words whose meanings are predefined in the language and they can not be used as identifiers like variable names or function names.

Q3. Is type a Python keyword?

'type' is not a keyword that is reserved like others but actually a built in function in Python which is used for finding the type of an object or for creating new types dynamically.

Q4. Can we use is in Python?

Yes, 'is' is used as a keyword in python for identity testing. It is used for checking if two variables are referring to the same object.

Q5. Are there 33 or 35 keywords in Python?

There are a total of 35 keywords in Python as of Python 3.11. Keywords change with versions as new ones might be introduced and existing ones might get removed.
Share Article
Batches Schedule
About Author
Sakshi Dhameja (Author and Mentor)

She is passionate about different technologies like JavaScript, React, HTML, CSS, Node.js etc. and likes to share knowledge with the developer community. She holds strong learning skills in keeping herself updated with the changing technologies in her area as well as other technologies like Core Java, Python and Cloud.

Self-paced Membership
  • 22+ Courses
  • 750+ Hands-On Labs
  • 300+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A
  • 10+ Real-world Projects
  • Career Coaching
  • Email Support
Upto 66% OFF
KNOW MORE..

To get full access to all courses

Accept cookies & close this