Table of contents
1.
Introduction
2.
List of Keywords in Python
3.
Getting the List of All Python Keywords
4.
True, False, None Keyword in Python
5.
and, or, not, in, is In Python
6.
Iteration Keywords – for, while, break, continue in Python
7.
Conditional Keywords in Python - if, else, elif
8.
Structure Keywords in Python: def, class, with, as, pass, lambda
9.
Return Keywords in Python - Return, Yield
10.
Import, From in Python
11.
Exception Handling Keywords in Python – try, except, raise, finally, and assert
12.
del in Python
13.
Global, Nonlocal in Python
14.
Frequently Asked Questions 
14.1.
Why can't I use Python keywords as variable names?
14.2.
Can I add my own keywords to Python?
14.3.
How do I remember all the Python keywords?
15.
Conclusion
Last Updated: Dec 15, 2024
Easy

Python Keywords

Author Ravi Khorwal
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Python is a very popular language for every experienced developers, because of its readability & versatile nature. Python's simplicity allows you to perform complex tasks with ease, making it a favorite among coding enthusiasts & professionals. 

Python Keywords

This article will guide you through the essential building blocks of Python programming: keywords. Understanding these keywords is crucial as they are the fundamental commands that define the structure & syntax of Python code. We'll talk about the various Python keywords, their usage, & how they can empower your coding projects. 

List of Keywords in Python

Python has a set of reserved words known as keywords. These keywords have specific meanings and cannot be used as variable names, function names, or identifiers. Below is a table of Python keywords:

KeywordKeywordKeywordKeyword
Falseawaitelseimport
Nonebreakexceptin
Trueclassfinallyis
andcontinueforlambda
asdeffromnonlocal
assertdelglobalnot
asyncelififor
passraisetryyield
returnwhilewithmatch
caseexcept*  

Getting the List of All Python Keywords

To see all the keywords Python has, you can use a simple tool that's built into Python itself. This tool is part of something called the keyword module. Think of a module like a toolbox that Python gives you. Inside this keyword module, there's a specific tool that lists all the keywords for you.

  • To use this tool, you first need to tell Python, "Hey, I want to use this toolbox." You do this by writing a line of code that says import keyword. This is like saying, "Python, please open the keyword toolbox."
     
  • Once you've told Python to open the toolbox, you can then ask it to show you all the keywords. You do this with a command that looks like this: print(keyword.kwlist). This is like saying, "Python, please print out the list of all your special keywords."
     

Here's how you can try it yourself:

import keyword


# This line asks Python to print the list of all keywords

print(keyword.kwlist)


When you run this code, Python will show you a list of its keywords. This list includes words like True, False, None, and, or, if, else, and many more. Each of these words has a special job in Python, and knowing them is like knowing the basic rules of how to write Python code.

By running this simple piece of code, you get a complete list of Python's keywords, which is the first step in understanding how to use them in your programs.

True, False, None Keyword in Python

In Python, True, False, and None are special keywords that represent important concepts.

  • True and False are used in Python to represent truth values. It's like saying yes (True) or no (False) to a question. These are used when you want to check if something is correct or not. For example, in a program, you might want to check if a number is bigger than another. Python uses True or False to tell you the answer.
     
  • None is a bit different. It's used to represent the idea of nothing or no value. Imagine you have a box, and you want to show that the box is empty. In Python, you would say the box is None. It's a way to tell Python, "There's nothing here."
     

Here's a simple example to show how True and False might be used:

# Checking if 10 is greater than 5

is_greater = 10 > 5  # This will be True because 10 is indeed greater than 5


# Printing the result

print(is_greater)  # This will print True


And here's how you might see None used:

# Creating a variable with no value

no_value = None


# Checking if no_value is None

is_none = no_value is None  # This will be True, because no_value has no value


# Printing the result

print(is_none)  # This will print True


Understanding True, False, and None is crucial because they help you control the flow of your program, allowing you to make decisions and handle situations where there might not be a value.

and, or, not, in, is In Python

In Python, and, or, not, in, and is are keywords used to compare things and decide what to do based on those comparisons. Let's break down what each one does:

  • and is used to check if two things are both true. If they are, then and gives back True. It's like saying, "If this and that are both true, then do something."
     
  • or is used when you only need one of two things to be true. If either is true, or gives back True. It's like saying, "If this or that is true, then do something."
     
  • not flips the truth value. If something is true, not makes it false, and if something is false, not makes it true. It's like saying, "If this is not true, then do something."
     
  • in checks if a value is inside a collection, like a list or a string. If the value is there, in gives back True. It's like asking, "Is this item in the list?"
     
  • is is used to check if two things are really the same thing, not just equal. It's like asking, "Is this thing exactly the same thing as that thing?"
     

Here's an example showing and, or, and not:


# Using and

both_true = (5 > 2) and (9 > 1)  # Both are true, so this is True


# Using or

one_true = (5 < 2) or (9 > 1)  # One statement is false, and the other is true, so this is True


# Using not

flip_false = not (5 < 2)  # 5 is not less than 2, so this is False, but not makes it True
print(both_true)  # Prints True
print(one_true)   # Prints True
print(flip_false) # Prints True


And here's how you might use in and is:

# Using in

item_in_list = 3 in [1, 2, 3, 4, 5]  # Checks if 3 is in the list


# Using is

same_object = (5 * 1) is 5  # Checks if '5 * 1' is exactly the same object as 5
print(item_in_list) # Prints True
print(same_object)  # This might print False, because 'is' checks for the same object, not just equal values


These keywords help you make decisions in your code based on conditions, allowing your programs to react differently to different situations.

Iteration Keywords – for, while, break, continue in Python

Iteration keywords help you repeat tasks in Python. This is like doing the same thing over and over again until a condition is met.

  • for is used to go through items in a list or any other sequence, one by one. It's like saying, "For each item in this list, do something."
     
  • while keeps doing something as long as a condition is true. It's like saying, "While this is true, keep doing something."
     
  • break stops the loop immediately, no matter where it is in the loop. It's like an emergency stop button for loops.
     
  • continue skips the rest of the loop and starts the next iteration. It's like saying, "Skip the rest and start the loop again."
     

Here's how you might use a for loop:

# Using for loop

for number in [1, 2, 3, 4, 5]:
    print(number)  # This will print numbers 1 through 5, one at a time


And a while loop example:

# Using while loop

count = 1
while count <= 5:
    print(count)  # This will print numbers 1 through 5, one at a time
    count += 1  # This adds 1 to count, so eventually, the loop will stop


Here's how break works:

# Using break

for number in range(10):  # This goes from 0 to 9
    if number == 3:
        break  # This stops the loop when number is 3
    print(number)  # This will print 0, 1, and 2, then stop


And an example with continue:

# Using continue

for number in range(5):  # This goes from 0 to 4
    if number == 2:
        continue  # This skips the rest of the loop when number is 2
    print(number)  # This will print 0, 1, 3, and 4 (skipping 2)

Conditional Keywords in Python - if, else, elif

Conditional keywords in Python help you make decisions in your code. They let you choose different actions based on certain conditions.

  • if is used to check a condition. If the condition is true, Python will do something. It's like saying, "If this is true, then do this."
     
  • else is used together with if. It tells Python what to do when the if condition is not true. It's like saying, "If the first condition isn't true, then do this instead."
     
  • elif stands for "else if". It's used after an if statement to check another condition if the first one isn't true. It's like saying, "If the first condition isn't true, check this one next."
     

Here's a simple example using if, else, and elif:

# Using if, else, and elif

age = 20
if age < 18:
    print("You're too young.")
elif age < 21:
    print("You're almost there.")
else:
    print("You're old enough!")


In this example, Python checks if age is less than 18. If that's true, it prints "You're too young." If not, it checks if age is less than 21. If that's true, it prints "You're almost there." If neither condition is true, it prints "You're old enough!"

Structure Keywords in Python: def, class, with, as, pass, lambda

Structure keywords in Python help you organize your code into reusable pieces. These pieces can be functions, classes, or context managers.

  • def is used to define a function. A function is a block of code you can use over & over. It's like a recipe that you can follow whenever you need to make a specific dish.
     
  • class is used to define a class. A class is like a blueprint for creating objects. Objects can have properties and actions, much like real-world objects.
     
  • with and as are often used together to set up a context. This is helpful when you need to set things up and tear them down automatically, like opening and closing a file.
     
  • pass is like a placeholder. It's used when you need to write something syntactically, but you don't want to do anything yet.
     
  • lambda creates small, anonymous functions. These are functions without a name, useful for short, throwaway functions.
     

Here's a basic example using def to create a function:

# Defining a simple function

def greet(name):
    print(f"Hello, {name}!")
# Using the function
greet("Alice")


This function, greet, takes a name and prints a greeting. You can use this function with any name.

For class, here's a simple example:

# Defining a simple class

# Defining a simple class
class Greeter:
    def __init__(self, name):
        self.name = name
    
    def greet(self):
        print(f"Hello, {self.name}!")
# Creating an object from the class
greeter = Greeter("Bob")
greeter.greet()


This Greeter class lets you create objects that can greet by name. Each Greeter object knows its name and can greet using it.

Return Keywords in Python - Return, Yield

In Python, return and yield are keywords used in functions to give back a result to the part of the program that called the function.

  • return is used in a function to end the function and send back a value to where the function was called. It's like completing a task and giving the results back.

 

  • yield is a bit special. It's used in functions known as generators. With yield, a function gives back a value and pauses there. Later, it can pick up where it left off. This is useful when dealing with a lot of data that you don't want to handle all at once.
     

Here's an example using return:

# A function using return

def add_numbers(a, b):
    result = a + b
    return result  # This sends the result back to where the function was called

# Calling the function and storing the result

sum = add_numbers(5, 3)
print(sum)  # This will print 8


In this example, the add_numbers function adds two numbers and uses return to give the result back.

Now, here's a simple example with yield:

# A generator function using yield

def count_up_to(max):
    count = 1
    while count <= max:
        yield count  # This gives back the current count and pauses
        count += 1  # Next time, it continues from here


# Using the generator

for number in count_up_to(5):
    print(number)  # This will print numbers 1 through 5, one at a time


In this count_up_to function, yield lets it give back each number one at a time, pausing between each.

Understanding return and yield helps you control how and when your functions give back results, making your code more flexible and powerful.

Import, From in Python

In Python, import and from are keywords used to bring in code from other files or libraries. This is like getting tools or ingredients you need from somewhere else to use in your current project.

  • import is used to bring in a whole library or a file. When you use import, you're saying, "I want to use everything from this toolbox."
     
  • from is used with import to bring in specific parts of a library or file. It's like saying, "I only need this one tool from the toolbox."
     

Here's how you might use import:

import math  # This brings in the whole math library

# Now you can use things from the math library

result = math.sqrt(16)  # This uses the sqrt function from the math library to find the square root of 16
print(result)  # This will print 4.0


And here's an example using from and import together:

from math import sqrt  # This only brings in the sqrt function from the math library

# Now you can use sqrt directly, without saying math.sqrt

result = sqrt(16)  # This finds the square root of 16
print(result)  # This will print 4.0


Using import and from lets you access a vast array of functions and tools that Python and other developers have written, saving you time and effort in writing your own solutions for common problems.

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

When writing code, sometimes things go wrong. Exception handling keywords in Python help you deal with errors gracefully, making sure your program can handle unexpected issues without crashing.

  • try is used to test a block of code for errors. It's like saying, "Let's see if this works."
     
  • except is used to handle the error. It's like saying, "If there was a problem, do this instead."
     
  • raise is used to trigger an error on purpose. It's like pressing an alarm button to alert that something went wrong.
     
  • finally is used for code that should run no matter what, even if there's an error. It's like saying, "Do this both when things go right and when things go wrong."
     
  • assert is used for debugging, to check if something is true. If it's not, the program will raise an error. It's like saying, "This must be true; if not, there's a problem."
     

Here's a simple example using try and except:

# Trying something that might cause an error

try:
    result = 10 / 0  # Dividing by zero causes an error
except ZeroDivisionError:
    print("You can't divide by zero!")  # This will run if there's a ZeroDivisionError


In this case, since dividing by zero is not allowed, the except block will run, and you'll see "You can't divide by zero!" printed out.

Now, let's see how finally works:

try:
    result = 10 / 0
except ZeroDivisionError:
    print("You can't divide by zero!")
finally:
    print("This will run no matter what.")  # This will always run, even if there's an error


No matter what happens in the try block, "This will run no matter what." will always be printed because of the finally block.

del in Python

In Python, del is a keyword used to delete things. You can use it to remove items from a list, delete variables, or even remove slices from a list.

Using del, you can clean up your code by getting rid of things you don't need anymore. It's like tidying up your room by throwing away trash or putting away things you're done using.

Here's an example of using del to delete a variable:

# Creating a variable
my_variable = "Hello, world!"
# Deleting the variable
del my_variable
# Trying to print the variable after deleting it will cause an error
# print(my_variable)  # This would cause an error because my_variable no longer exists


And here's how you might use del with a list:

# Creating a list
my_list = [1, 2, 3, 4, 5]
# Deleting the third item in the list (remember, counting starts at 0 in Python)
del my_list[2]
# Now my_list is [1, 2, 4, 5]
print(my_list)


del is useful for managing memory and keeping your code clean by removing items that are no longer needed.

Global, Nonlocal in Python

In Python, global and nonlocal are keywords used to work with variables that are outside the current scope. They help you change variables that are not directly inside the function or block of code you are working with global is used to tell Python that you want to use and change a variable that was defined outside of the current function.

  • Nonlocal is used in nested functions to refer to variables in the outer function (but not global variables).
     
  • Using global allows you to modify a variable outside of the current function, which can be helpful when you need to keep track of something throughout your program.
     

Here's an example of using global:

# Defining a global variable
counter = 0
def increment_counter():
    global counter  # Telling Python we want to use the global counter
    counter += 1  # Incrementing the counter
# Calling the function
increment_counter()
print(counter)  # This will print 1, because the global counter was incremented


Nonlocal is used when you have a function inside another function and you want to modify a variable in the outer function.

Here's an example of using nonlocal:

def outer_function():
    outer_counter = 0
  def inner_function():
        nonlocal outer_counter  # Telling Python we want to use the outer_counter from the outer function
        outer_counter += 1  # Incrementing the outer_counter
     inner_function()
    print(outer_counter)  # This will print 1, because the inner function incremented the outer_counter
outer_function()

Frequently Asked Questions 

Why can't I use Python keywords as variable names?

Python keywords are reserved words that have special meanings. They tell Python how to structure and control your code. Using them as variable names would confuse Python, making it hard to understand what your code is supposed to do. It's like trying to use a screwdriver as a key; it's not meant for that purpose and won't work as expected.

Can I add my own keywords to Python?

No, you can't add your own keywords to Python. Keywords are a core part of the Python language that is defined by Python itself. However, you can create your own functions and classes, which let you extend Python's capabilities in ways that suit your needs. It's like building your own custom tools to complement the standard toolbox.

How do I remember all the Python keywords?

You don't need to memorize all Python keywords right away. As you practice coding in Python, you'll naturally start to remember them. You can also use coding tools or editors that highlight keywords, helping you recognize and learn them over time. It's like learning the pieces in a game; the more you play, the better you know what each piece does.

Conclusion

Understanding Python keywords is crucial for writing effective Python code. These special words are the building blocks of Python programming, helping you structure your code, define functions, make decisions, handle errors, and much more. By mastering Python keywords, you unlock the full potential of this powerful programming language, enabling you to create efficient, readable, and robust code. 

You can refer to our guided paths on the Code360. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass