When you start learning Python, you will come across words such as if, else, for, while, True, and False.
These words have special meanings in Python. They are called keywords.
Keywords are an important part of Python programming because they help us write instructions, make decisions, repeat tasks, define functions, and control how a program works.
In this article, we will learn what Python keywords are, see examples of commonly used keywords, understand why they are reserved, and discover how keywords differ from variable names.
1. What Are Keywords in Python?
Keywords are reserved words in Python that have predefined meanings and special purposes in the language.
We use them to write the structure and logic of a program.
For example:
age = 18
if age >= 18:
print("You are eligible to vote.")
In this program, if is a keyword. It checks whether a condition is true before executing the indented statement.
Here:
ifis a keyword.ageis a variable.18is an integer literal.printis a built-in function.
Python keywords cannot be used as ordinary variable names because they already have special meanings in the language.
2. Why Are Keywords Important?
Keywords help Python understand what you want your program to do.
For example, consider these keywords:
ifhelps make decisions.elseprovides an alternative when anifcondition is false.foris used to create a loop.whilerepeats statements while a condition remains true.defis used to define a function.returnsends a result back from a function.importallows you to bring a module into your program.classis used to define a class.
Without these special words, it would be difficult to express program logic in a clear and consistent way.
3. Common Python Keywords
Let's look at some commonly used Python keywords and their purposes.
| Keyword | Purpose |
|---|---|
if | Checks a condition |
else | Provides an alternative branch |
elif | Checks another condition |
for | Creates a loop |
while | Repeats statements while a condition is true |
break | Terminates the nearest enclosing loop |
continue | Skips to the next iteration of a loop |
pass | Acts as a placeholder statement |
def | Defines a function |
return | Returns a value from a function |
class | Defines a class |
import | Imports a module |
from | Imports specified names from a module |
as | Creates an alias in supported statements |
try | Begins a block for exception handling |
except | Handles specified exceptions |
finally | Defines code that runs during the cleanup phase of exception handling |
raise | Raises an exception |
in | Tests membership or appears in certain loop statements |
is | Tests object identity |
and | Performs logical AND |
or | Performs logical OR |
not | Performs logical negation |
True | Represents the Boolean value true |
False | Represents the Boolean value false |
None | Represents the absence of a value |
global | Declares that a name refers to a global variable |
nonlocal | Refers to a variable in an enclosing, non-global scope |
with | Manages a context, such as working with a file |
assert | Checks a condition and raises an error if it fails |
del | Deletes a name or removes an item or attribute |
lambda | Creates a small anonymous function |
yield | Produces a value from a generator function |
async | Defines asynchronous code in supported contexts |
await | Waits for an awaitable result in asynchronous code |
Note: Python's keyword list can vary between versions. Some words, such as match and case, have special roles in structural pattern matching, while certain other words are treated as soft keywords rather than reserved keywords in every context.
You do not need to memorize every keyword on your first day. Learn them gradually as you study each topic.
4. Understanding Keywords with Examples
The easiest way to understand keywords is to see how they work in programs.
Example 1: The if Keyword
The if keyword allows a program to make a decision.
age = 20
if age >= 18:
print("Adult")
Output:
Adult
The condition age >= 18 is true, so Python executes the indented statement.
Example 2: The if, elif, and else Keywords
These keywords allow a program to choose between different possibilities.
marks = 75
if marks >= 90:
print("Grade A")
elif marks >= 60:
print("Grade B")
else:
print("Grade C")
Output:
Grade B
Python checks the conditions in order. The first condition is false, but the second is true, so it displays Grade B.
Example 3: The for Keyword
The for keyword is used to repeat a block of code.
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
Here, for creates the loop, while in is used to iterate through the values produced by range(1, 6).
Example 4: The while Keyword
The while keyword repeats a block of code while its condition is true.
count = 1
while count <= 3:
print(count)
count += 1
Output:
1
2
3
The loop stops when count <= 3 becomes false.
Example 5: The def Keyword
The def keyword is used to define a function.
def greet():
print("Welcome to Python!")
greet()
Output:
Welcome to Python!
Here, def defines the function named greet.
Example 6: The return Keyword
The return keyword sends a result back from a function.
def add(a, b):
return a + b
result = add(10, 20)
print(result)
Output:
30
The function returns the sum of the two numbers.
Example 7: The import Keyword
The import keyword allows us to use functionality from a module.
import math
print(math.sqrt(25))
Output:
5.0
Here, import makes the math module available to the program.
5. Can We Use Keywords as Variable Names?
No. Python keywords cannot be used as ordinary variable names.
For example, this code is invalid:
if = 10
Python will report a syntax error because if is a reserved keyword.
Another invalid example is:
for = 20
The word for already has a special purpose in Python.
How Can We Fix This?
Choose a different variable name.
Instead of:
if = 10
Write:
number = 10
Similarly, instead of:
for = 20
Write:
count = 20
Remember: A variable name should describe the value it represents and must not be a reserved keyword.
6. Keywords vs Identifiers
Keywords and identifiers are two different concepts.
An identifier is a name given to a variable, function, class, or another named object in Python.
Consider this program:
student_name = "Rahul"
if student_name:
print(student_name)
Let's identify the different parts:
ifis a keyword.student_nameis an identifier."Rahul"is a string literal.print()is a built-in function.
Here is a quick comparison:
| Keywords | Identifiers |
|---|---|
| Reserved words with special meanings | Names created for program elements |
| Have predefined purposes | Are chosen by the programmer, subject to naming rules |
| Cannot be used as ordinary variable names | Can be used as variable or function names when valid |
Examples: if, for, while | Examples: age, student_name, calculate_sum |
For example:
age = 20
Here, age is an identifier, while 20 is a literal.
7. Are Python Keywords Case-Sensitive?
Yes. Python is case-sensitive.
For example:
if age >= 18:
print("Eligible")
The keyword must be written as if, using lowercase letters.
Writing IF instead of if does not create the same keyword.
Similarly, Python's Boolean literals are written as True and False, with the first letter capitalized.
Example:
is_student = True
print(is_student)
Output:
True
Writing true instead of True will not refer to Python's Boolean literal.
8. How to Check Python Keywords
Python provides a module named keyword that can help you examine the keywords recognized by your Python interpreter.
Example:
import keyword
print(keyword.kwlist)
This displays the list of hard keywords for the Python version you are using.
You can also check whether a word is a keyword:
import keyword
word = "while"
print(keyword.iskeyword(word))
Output:
True
Try changing the value of word:
word = "student"
The result will be:
False
The word student is not a Python keyword.
Important: The exact list of keywords depends on the Python version installed on your computer.
9. Common Mistakes Beginners Should Avoid
Mistake 1: Using a keyword as a variable name
Incorrect:
while = 10
Correct:
count = 10
Mistake 2: Using the wrong capitalization
Incorrect:
IF age >= 18:
print("Eligible")
Correct:
if age >= 18:
print("Eligible")
Mistake 3: Trying to memorize every keyword immediately
You do not need to memorize the entire keyword list before writing your first Python program.
Start with the keywords you use frequently, such as if, else, for, while, and def. Learn the remaining ones as you progress through the course.
Mistake 4: Confusing keywords with built-in functions
Consider:
print("Hello")
Here, print is a built-in function, not a keyword.
Similarly, input(), len(), and type() are built-in functions.
This distinction is useful when learning Python fundamentals.
10. Practice Questions
Test your understanding with the following questions.
Question 1: What is a keyword in Python?
Question 2: Why can we not use if as an ordinary variable name?
Question 3: Identify the keyword in this program:
age = 21
if age >= 18:
print("Eligible")
Question 4: Are Python keywords case-sensitive?
Question 5: What is the difference between a keyword and an identifier?
Question 6: Which keyword is used to define a function?
Question 7: Which keyword is used to import a module?
Question 8: What is the purpose of the break keyword?
Question 9: Is print a keyword or a built-in function?
Question 10: Write a Python program using if and else to check whether a number is positive or not.
Practice Program: Check a Number
Try this example after answering the questions:
number = int(input("Enter a number: "))
if number > 0:
print("The number is positive.")
else:
print("The number is zero or negative.")
Example output:
Enter a number: 5
The number is positive.
This simple program demonstrates how keywords help control the flow of a Python program.
Final Thoughts
Python keywords are the reserved words that give structure and meaning to your programs. They help you make decisions, repeat tasks, define functions, import modules, and perform many other programming operations.
As a beginner, focus on understanding how keywords work rather than memorizing their entire list. With regular practice, you will become familiar with them naturally.
Keep experimenting with small programs, read the error messages Python provides, and try changing the examples to see what happens.
Comments
Post a Comment