When you begin learning a new spoken language, the first thing you master is its core vocabulary, the words that have fixed meanings and cannot be changed. Programming languages work the exact same way.
In Python, these foundational words are known as Keywords. Understanding them is essential for writing clean, efficient, and error-free code. Let's break down what they are, why they matter, and how they are categorized.
Table of Contents
What is a Python Keyword?
A Python Keyword is a reserved word that has a specific, predefined meaning and purpose within the language. Because the Python interpreter relies on these words to understand the structure and logic of your code, you cannot use keywords as regular names. This means you cannot name your variables, functions, classes, or constants after them. Doing so will immediately trigger a SyntaxError.
Characteristics of Keywords
1. Strictly Case-Sensitive: Python treats uppercase and lowercase letters as entirely different characters. The interpreter will only recognize a keyword if it matches the exact casing defined by the language rules.
- The vast majority of Python keywords are entirely lowercase (e.g., if, else, and).
- There are exactly three keywords that begin with a capital letter: True, False, and None.
Note:
If you type true or IF, Python will treat them as regular variable names, not keywords.
2. Reserved and Cannot Be Used as Identifiers: Because keywords are woven into the fundamental grammar of the language, they are completely off-limits for naming your own code elements. You cannot use a keyword as a:
- Variable name
- Function name
- Class name
- Constant or directory key
If you attempt to assign a value to a keyword, Python's parser will reject it immediately
3. Trigger Compile-Time (Syntax) Errors: If you misuse a keyword, Python flags it as a SyntaxError, not a runtime error. This means the Python interpreter catches the mistake during the initial parsing phase (when it builds the abstract syntax tree) and refuses to execute a single line of your script until it is fixed.
4. They Have Fixed, Hardcoded Meanings: The behavior of a keyword is deeply embedded in Python's core compiler logic. Unlike built-in functions (such as print() or len()), which can technically be overwritten or shadowed by custom code. Their functional meaning remains identical across every script, module, and project.
5. Numbers Evolve with Python Versions: The total count of keywords is not fixed permanently; it changes as the core Python development team introduces new language features or deprecates old ones.
- In Python 2, there were roughly 31 keywords.
- In Python 3, keywords like exec and print became built-in functions, while new keywords like as, True, False, with, and None were introduced.
- More recent versions introduced asynchronous programming keywords (async and await), bringing the total count to 35 keywords in modern Python 3.
Conditional Keywords
These keywords are used for decision-making and controlling the flow of execution.
Keywords:
- if Keyword: Evaluates a condition. If the condition is true, its indented block of code runs.
- else Keyword: Acts as a final catch-all block that runs automatically if none of the previous conditions were met.
- elif Keyword: Checks an alternative condition only if all preceding if or elif conditions turned out to be false.
Example
# Python program to implement conditional keywords
score = 85
if score == 90:
print("Grade: A")
elif score == 80:
print("Grade: B")
else:
print("Grade: C")
Output
Grade: C
Explanation
- Line-by-Line Execution: Python checks the if statement first, finds that 85 == 90 is false, and skips it.
- The Decision: It moves to the elif statement, evaluates 85 == 80 as false, and skips it.
- The Exit: Because a true condition was not found, Python executes the else block and finishes the program.
Looping Keywords
Looping keywords allow you to execute a block of code repeatedly. Python has two primary keywords for creating loops: for and while.
Keywords:
for
while
for Keyword: Used to iterate over a sequence (like a list, tuple, string, or a range of numbers), a predetermined number of times.
Example:
# Python program to implement for keyword for i in range(5): print(i)
Output:
0
1
2
3
4
Explanation:
- The for keyword tracks the sequence generated by range(5) (which is 0, 1, 2, 3, 4).
- It assigns each number to the variable i one by one, executing the print statement exactly five times before stopping automatically.
while Keyword: Repeats a block of code continually as long as a specified condition remains true.
Example:
# Python program to implement while keyword
count = 1
while count = 3:
print("Count is",count)
count += 1
Output:
Count is 1
Count is 2
Count is 3
Explanation:
- The while keyword checks if count = 3 is true before every turn.
- It runs the print block and increments count each time, automatically exiting the loop the moment count becomes 4.
Loop Control Keywords
These keywords modify the behavior of loops.
Keywords:
break Keyword: The break statement is used to terminate the loop immediately. When Python encounters a break, it exits the loop and executes the statements that follow the loop.break
continue
pass
Example:
# Python program to show the working
# of break keyword
for i in range(1, 11):
if i == 6:
break
print(i)
Output:
Explanation:1
2
3
4
5
- The loop starts from 1 and goes up to 10.
- Each value of i is checked.
- When i becomes 6, the condition i == 6 becomes True.
- The break statement is executed.
- The loop terminates immediately.
- Numbers after 5 are not printed.
Example:
# Python program to show the working
# of continue keyword
for i in range(1, 11):
if i == 6:
continue
print(i)
Output:
1
2
3
4
5
7
8
9
10
Explanation:
- The loop runs from 1 to 10.
- When i becomes 6, the condition becomes True.
- continue is executed.
- Python skips the print(i) statement for that iteration.
- The loop proceeds with the next value (7).
- Therefore, only 6 is skipped.
Example:
# Python program to show the working
# of pass keyword
for i in range(1, 6):
if i == 3:
pass
print(i)
Output:
1
2
3
4
5
Explanation:
- The loop runs from 1 to 5.
- When i becomes 3, pass is executed.
- Since pass does nothing, execution continues normally.
- All numbers from 1 to 5 are printed.
Logical Keywords
Logical keywords are used to combine or modify conditions. They return either True or False and are commonly used in decision-making statements such as if, elif, and while.
Keywords:
and
or
not
and Keyword: The and operator returns True only when all conditions are true. If any condition is False, the result becomes False.
Syntax:
condition1 and condition2
Example:
# Python program to show the working
# of and keyword
age = 20
citizen = True
if age == 18 and citizen:
print("Eligible to vote")
else:
print("Not Eligible to vote")
Output:
ExplanationNot Eligible to vote
- age == 18 evaluates to False, and citizen is True.
- Since one condition is True and one is False, it evaluates to False.
- The else block executes and prints the message.
| A | B | A and B |
|---|---|---|
| True | True | True |
| True | False | False |
| False | True | False |
| False | False | False |
or Keyword: The or operator returns True if at least one condition is True. It returns False only when all conditions are False.
Syntax:
Examplecondition1 or condition2
# Python program to show the working
# of or keyword
marks = 35
sports_quota = True
if marks == 40 or sports_quota:
print("Admission Granted")
else:
print("Admission is not Granted")
Output:
Admission GrantedExplanation:
- marks == 40 is False.
- sports_quota is True.
- Since one condition is True, or returns True.
- The if block executes.
| A | B | A or B |
|---|---|---|
| True | True | True |
| True | False | True |
| False | True | True |
| False | False | False |
not Keyword: The not keyword reverses the result of a condition.
Syntax:
Examplenot condition
# Python program to show the working
# of not keyword
is_raining = False
if not is_raining:
print("Go for a walk")
Output:
Go for a walkExplanation:
- is_raining is False.
- not False becomes True.
- The if condition becomes True.
- The message is printed.
| A | not A |
|---|---|
| True | False |
| False | True |
Membership Keywords
Membership keywords are used to check whether a value exists in a sequence such as a string, tuple, set, list, or dictionary. Python provides two membership keywords:
- in
- not in
- Returns True if the value exists.
- Returns False if the value does not exist.
Example:value in sequence
#Python Program to show the working # of in keyword numbers = [10, 20, 30, 40] print(20 in numbers) print(50 in numbers)Output:
True
False
Explanation:
- 20 is present in the list, so the result is True.
- 50 is not present in the list, so the result is False.
- Returns True if the value is absent.
- Returns False if the value exists.
Example:value not in sequence
# Python program to show the working # of not in keyword numbers = [10, 20, 30, 40] print(50 not in numbers) print(20 not in numbers)Output:
True
False
Explanation:
- 50 is not present in the list, so the result is True.
- 20 is present in the list, so the result is False.
Identity Keywords
Identity Keywords are used to check whether two variables refer to the same object in memory. Python provides two identity keywords:
- is
- is not
Syntax:
object1 is object2Example:
# Python program to show the working # of is keyword x = [1, 2, 3] y = x print(x is y)Output:
True
Explanation:
- A list is created and assigned to x.
- y = x means y refers to the same list object.
- Both variables point to the same memory location.
- Therefore, x is y returns True.
is not Keyword: The is not operator returns True if two variables refer to different objects in memory.
Syntax:
object1 is not object2
Example:
# Python program to show the working # of is not keyword x = [1, 2, 3] y = [1, 2, 3] print(x is not y)
Output:
True
Explanation:
- x and y are separate list objects.
- They occupy different memory locations.
- Therefore, is not returns True.
Function and Class Definition Keywords
Python provides special keywords for creating functions and classes. These keywords help organize code, improve reusability, and support Object-Oriented Programming (OOP).
The main function and class definition keywords are:
- def
- return
- class
Syntax:
def function_name():
statements
Example 1: Without Parameters
# Python program to show the working def keyword
def greet():
print("Welcome to Python")
greet()
Output:
Welcome to Python
Explanation:
- def greet(): creates a function named greet.
- The statement inside the function prints a message.
- greet() calls the function.
- The function executes and displays the output.
Example 2: With Parameters
# Python program to show the working
# of def keyword
def add(a, b):
print(a + b)
add(10, 20)
Output:
30
Explanation:
- a and b are parameters.
- Values 10 and 20 are passed to the function.
- The function adds them and prints the result.
return Keyword: The return keyword is used to send a value back from a function to the caller. Once return is executed, the function immediately terminates.
Syntax:
def function_name():
return value
Example:
# Python program to show the working
# of return keyword
def square(num):
return num * num
result = square(5)
print(result)
Output:
25
Explanation:
- The function receives 5 as input.
- num * num calculates 25.
- return sends the value back.
- The returned value is stored in result.
- print(result) displays 25.
class keyword: The class keyword is used to create a class. A class is a blueprint for creating objects. It defines properties (variables) and behaviors (methods).
Syntax:
class ClassName:
statements
Example:
# Python program to show the working
# of class keyword
class Student:
name = "Rahul"
obj = Student()
print(obj.name)
Output:
Rahul
Explanation:
- A class named Student is created.
- It contains a class variable name.
- obj = Student() creates an object.
- obj.name accesses the variable.
Exception Handling Keywords
Exception handling is a mechanism used to handle runtime errors gracefully so that the program does not terminate unexpectedly. Python provides the following exception-handling keywords:
- try
- except
- finally
- raise
- assert
try Keyword: The try block contains the code that may generate an exception. If an exception occurs, Python immediately stops executing the remaining statements in the try block and looks for an appropriate except block.
Syntax:
try:
# risky code
Example:
# Python program to show the working
# of try keyword
try:
num = 10 / 0
print(num)
except ZeroDivisionError:
print("Cannot divide by zero")
Output:
Cannot divide by zero
Explanation:
- Python enters the try block.
- 10 / 0 causes a ZeroDivisionError.
- Execution immediately stops in the try block.
- Control transfers to the matching except block.
- The error message is displayed instead of terminating the program.
except Keyword: The except block handles exceptions raised in the try block. It prevents the program from crashing and allows execution to continue.
Syntax:
try:
statements
except ExceptionType:
statements
Example:
# Python program to show the working
# of except keyword
try:
number = int("Hello")
except ValueError:
print("Invalid conversion")
Output:
Invalid conversion
Explanation:
- int("Hello") attempts to convert text to an integer.
- Conversion fails and raises a ValueError.
- The except ValueError block handles the error.
- The program continues normally
finally Keyword: The finally block executes whether an exception occurs or not. It is commonly used for cleanup tasks such as closing files, database connections, or releasing resources.
Syntax:
try:
statements
except:
statements
finally:
statements
Example:
# Python program to show the working
# of finally keyword
try:
print(10 / 0)
except ZeroDivisionError:
print("Error occurred")
finally:
print("Execution completed")
Output:
Error occurred
Execution completed
Explanation:
- Division by zero raises an exception.
- The except block handles the exception.
- The finally block executes afterward.
- It runs regardless of whether an error occurred.
raise Keyword: The raise keyword is used to manually generate an exception. Programmers use it when they want to enforce specific conditions.
Syntax:
raise ExceptionType("Message")
Example:
# Python program to show the working
# of raise keyword
age = -5
if age == 0:
raise ValueError("Age cannot be negative")
Output:
ValueError: Age cannot be negative
Explanation:
- The condition age = 0 becomes True.
- raise explicitly generates a ValueError.
- Python stops execution and displays the error message.
assert Keyword: The assert statement is used for debugging and testing assumptions. It checks whether a condition is True.
- If True: Program continues.
- If False: Raises AssertionError.
Syntax:
assert condition, "Error Message"
Example:
# Python program to show the working # of assert keyword x = -5 assert x 0, "Number must be positive"
Output:
AssertionError: Number must be positive
Explanation:
- Python evaluates x 0.
- The condition is False.
- AssertionError is raised.
- The custom error message is displayed.
Import Keywords
Import keywords are used to bring modules, functions, classes, or variables from other Python files or libraries into the current program.
Python provides the following import-related keywords:
- import
- from
- as
What is a Module?
A module is a Python file containing functions, classes, and variables that can be reused in other programs.
Examples of built-in modules:
- math
- random
- datetime
- os
- sys
import Keyword: The import keyword is used to import an entire module into a program.
Syntax:
import module_name
Example:
# Python program to show the working # of import keyword import math print(math.sqrt(25))
Output:
5.0
Explanation:
- The math module is imported.
- math.sqrt() accesses the square root function.
- The square root of 25 is calculated.
- The result is displayed.
from Keyword: The from keyword is used to import specific functions, classes, or variables from a module.
Syntax:
from module_name import item
Example:
# Python program to show the working # of from keyword from math import sqrt print(sqrt(36))
Output:
6.0
Explanation:
- Only the sqrt function is imported.
- There is no need to write math.sqrt().
- The function can be called directly.
as Keyword: The as keyword is used to create an alias (short name) for a module or imported item.
Syntax:
import module_name as alias
or
from module_name import item as alias
Example 1: Alias for Module
# Python program to show the working # of as keyword import math as m print(m.sqrt(64))
Output:
8.0
Explanation:
- math module is imported
- math is renamed to m.
- The shorter name improves readability.
- m.sqrt(64) calculates square root.
Variable Scope Keywords
Variable scope determines where a variable can be accessed in a program. Python provides two special keywords for working with variables outside the current scope:
- global
- nonlocal
Understanding Variable Scope
Python follows the LEGB rule for variable lookup:
| Scope | Meaning |
|---|---|
| L | Local Scope |
| E | Enclosing Scope |
| G | Global Scope |
| B | Built-in Scope |
Example:
# Python program to show the working
# of global and local vbariable
# Global variable
x = 100
# Local variable
def display():
y = 50
print(y)
display()
print(x)
Output:
Explanation:50
100
- x is accessible throughout the program.
- y is accessible only inside display().
global Keyword: The global keyword is used to modify a global variable from inside a function. Without global, assigning a value inside a function creates a new local variable.
Syntax:
global variable_name
Example: Without global
# Python program without global keyword
count = 10
def update():
count = 20
print("Inside Function:", count)
update()
print("Outside Function:", count)
Output:
Inside Function: 20
Outside Function: 10
Explanation:
- count = 20 creates a new local variable.
- The global variable remains unchanged.
- Therefore, the outside value is still 10.
Example: With global
# Python program with global keyword
count = 10
def update():
global count
count = 20
print("Inside Function:", count)
update()
print("Outside Function:", count)
Output:
Inside Function: 20
Outside Function: 20
Explanation:
- global count tells Python to use the global variable.
- The value is updated globally.
- The change is reflected outside the function.
nonlocal Keyword: The nonlocal keyword is used to modify a variable in the enclosing (outer) function scope. It works only with nested functions.
Syntax:
nonlocal variable_name
Example Without nonlocal
# Python program without nonlocal keyword
def outer():
x = 10
def inner():
x = 20
print("Inner:", x)
inner()
print("Outer:", x)
outer()
Output:
Inner: 20
Outer: 10
Explanation:
- x = 20 reates a new local variable inside inner().
- The outer variable remains unchanged.
Example With nonlocal
# Python program with nonlocal keyword
def outer():
x = 10
def inner():
nonlocal x
x = 20
print("Inner:", x)
inner()
print("Outer:", x)
outer()
Output:
Inner: 20
Outer: 20
Explanation:
- nonlocal x refers to the variable in the enclosing function.
- The assignment changes the outer variable.
- The updated value 20 is printed.
Boolean and Null Keywords
Python provides special keywords to represent Boolean values and the absence of a value. The Boolean and Null keywords are:
- True
- False
- None
True Keyword: True is a Boolean keyword that represents a logical truth value. It is commonly used in conditions, comparisons, loops, and logical operations.
Syntax:
value = True
Example:
# Python program to show the working
# of True keyword
logged_in = True
if logged_in:
print("Welcome User")
Output:
Welcome User
Explanation:
Since logged_in is True, the condition is satisfied, and the message is displayed.
False Keyword: False is a Boolean keyword that represents a logical false value. It is used when a condition is not satisfied.
Syntax:
value = False
Example:
# Python program to show the working
# of False keyword
is_raining = False
if is_raining:
print("Take an umbrella")
else:
print("Enjoy your day")
Output:
Enjoy your day
Explanation:
- The condition is_raining evaluates to False.
- The else block executes.
None Keyword: None is a special keyword that represents the absence of a value or a null value. It is not the same as:
- 0
- False
- Empty string ""
- Empty list [ ]
None means "no value assigned".
Syntax:
variable = None
Example:
# Python program to show the working
# of None keyword
name = None
if name is None:
print("No value available")
Output:
No value available
Explanation:
- is None is the recommended way to check for None.
- The condition becomes True because name contains None.
Note:
Python internally treats True as 1 and False as 0.
Asynchronous Programming Keywords
Asynchronous programming allows a program to perform multiple tasks efficiently without waiting for one task to finish before starting another. Python provides two special keywords for asynchronous programming:
- async
- await
These keywords are commonly used with the built-in asyncio library.
async Keyword: The async keyword is used to define an asynchronous function (coroutine).
An asynchronous function can pause execution and allow other tasks to run.
Syntax:
async def function_name():
statements
Example:
# Python program to show the working
# of async keyword
import asyncio
async def greet():
print("Hello Python")
asyncio.run(greet())
Output:
Hello Python
Explanation:
- async def greet() defines an asynchronous function.
- asyncio.run starts the event loop.
- The coroutine executes and prints the message.
await Keyword: The await keyword pauses the execution of an async function until another asynchronous operation completes. It can only be used inside an async function.
Syntax:
await expression
Example:
# Python program to show the working
# of await keyword
import asyncio
async def task1():
print("Task 1 Started")
await asyncio.sleep(2)
print("Task 1 Finished")
async def task2():
print("Task 2 Started")
await asyncio.sleep(1)
print("Task 2 Finished")
async def main():
await asyncio.gather(
task1(),
task2()
)
asyncio.run(main()) # Runs multiple tasks concurrently
Output:
Task 1 Started
Task 2 Started
Task 2 Finished
Task 1 Finished
Explanation:
- Both tasks start almost simultaneously.
- Task 2 finishes first because it waits for less time.
- Total execution time is reduced.
Conclusion
Python keywords are reserved words that form the backbone of Python programming. They define the language's syntax, control program flow, manage functions and classes, handle exceptions, and support advanced concepts such as asynchronous programming. Since keywords have predefined meanings, they cannot be used as identifiers. A solid understanding of Python keywords helps programmers write accurate, readable, and efficient code while avoiding syntax errors.
Frequently Asked Questions
1. How many keywords are there in Python?
The exact number depends on the version of Python you are using. For example, Python 3.10+ typically features around 35 keywords. Because Python is constantly evolving, keywords are occasionally added to support new programming paradigms (like match and case for structural pattern matching).
2. Can I use a keyword as a variable name if I change its capitalization?
Technically, yes, because Python is case-sensitive. For example, if is a keyword, but If or IF are not. However, this is highly discouraged. It makes your code incredibly confusing to read and violates Python's best practices (PEP 8 guide).
3. What is the difference between Python keywords and built-in functions?
Keywords (like if, def, while) are built directly into the language's grammar and syntax; you cannot overwrite them. Built-in functions (like print(), len(), input()) are pre-written functions provided by Python. While you can technically overwrite built-in functions by naming a variable after them, doing so is bad practice because it hides the original function functionality.
4. Will using keywords incorrectly cause a runtime error or a syntax error?
It will cause a SyntaxError. Because Python checks the structure of your code before actually running it, it will flag illegal uses of keywords (such as pass = 5) during the parsing phase, preventing the code from executing at all.
5. Are Python keywords case-sensitive?
Yes. Python keywords are case-sensitive. For example, True is a keyword, but true is not.
6. What is the difference between is and ==?
- == compares values.
- is compares object identities (memory locations).
0 Comments