Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • šŸ“ Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • šŸ“ Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • šŸ“ Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • šŸ“ Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • šŸ“ While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • šŸ“ For Each Assignments
    • šŸ“ All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • šŸ“ Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • šŸ“ Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • šŸ“ Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • šŸ“ Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • šŸ“ Assignments
  • Exception
    • Error vs Exception
    • Exception Handling
    • Types of Exception
    • User Defined Exception
    • Logging Exception
    • šŸ“ Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • šŸ“ Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • šŸ“ Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • šŸ“ Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • šŸ“ Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • šŸ“ Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • šŸ“ Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • šŸ“ Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • šŸ“ Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • šŸ“ Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • šŸ“ Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • šŸ“ Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • šŸ“ Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • šŸ“ Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

šŸ Python Keywords, Identifiers & Variables

Python Keywords, Identifiers & Variables - Complete Guide

Understanding Python keywords, identifiers and variables — the building blocks of Python code

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
We are a team of Python developers, data engineers and data scientists with years of real-world experience. We have built production applications. We have tackled complex problems. We have helped teams ship better code. What drives us? Teaching — especially that moment when things finally click. Our tutorials focus on practical examples and honest guidance. Whether you are just starting out or leveling up we are here to make Python genuinely useful.
šŸ“‘ On this page:
  • Python Keywords
  • Python Identifiers
  • Python Variables
  • Rules for Naming Variables
  • Variables vs Identifiers
  • Try It Yourself
  • Test Your Knowledge
  • FAQ
  • Learning Resources
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
šŸ“š What You'll Learn Here
  • Python Keywords — Reserved words and their purpose
  • Python Identifiers — Naming rules and conventions
  • Python Variables — How to store and manage data
  • Rules for Naming — What's valid and what's not
  • Variables vs Identifiers — Understanding the difference
  • Hands-on Practice — Write and run Python code
  • Interactive Quiz — Test your knowledge

1. Python Keywords — The Reserved Words

Keywords are unique reserved words in Python that cannot be used as variable names, function names, or other identifiers. They are the building blocks of the Python language — the vocabulary that Python understands.

Each keyword serves a specific purpose, and together they form the syntax of Python programs. As of Python 3.11.2, there are 35 keywords that Python supports.

šŸ’” Important: All keywords in Python are case-sensitive. So IF is not the same as if. Be careful when using them!

List of Python Keywords:

All 35 Python Keywords:

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

How to List All Keywords:

# Python script to list all keywords
import keyword
print(keyword.kwlist)
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']

Using help() to View Keywords:

>>> help("keywords")

Here is a list of the Python keywords. Enter any keyword to get more help.

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

šŸ“ Note: The list of Python keywords may change in future releases. New keywords may be added, and old ones may be discontinued.

2. Python Identifiers — Naming Your Code

Identifiers are the names given to entities like variables, functions, classes, and labels in a program. When you assign a name to a programmable entity in Python, it's technically called an identifier.

Identifiers must be different from keywords. Keywords cannot be used as identifiers. Python has a set of rules for creating meaningful identifiers.

Rules for Naming Identifiers:

  • Use letters, digits, or underscores: Combination of alphabets (a-z, A-Z), digits (0-9), or underscore (_)
  • Cannot start with a digit: Digits cannot be used as the first character
  • Cannot use keywords: Keywords are reserved and cannot be used as identifiers
  • No special symbols: Symbols like !, @, #, $, %, etc. are not allowed
  • Case-sensitive: myVar and myvar are different

āœ… Valid Identifiers

shapeClass
shape_1
upload_shape_to_db
_private
myVar123

āŒ Invalid Identifiers

1shape (starts with digit)
shape class (has space)
class (is a keyword)
my-var (has hyphen)
@name (has special symbol)

# Valid identifiers
>>> shapeClass = 1
āœ… Works fine!

# Invalid identifiers (will raise errors)
>>> shape Class = 1
SyntaxError: invalid syntax

>>> 1shape = 1
SyntaxError: invalid decimal literal

3. Python Variables — Storing Your Data

Variables are names that refer to memory locations where data is stored. They are the most fundamental concept in programming — they allow you to store, retrieve, and manipulate data.

Key Facts About Python Variables:

šŸ“Œ No Declaration Needed

Variables don't require explicit declaration. You just assign a value and the variable is created.

šŸ”„ Dynamic Typing

Variables can hold different types of objects at different times. They are references to objects, not the objects themselves.

🧠 Object-Oriented

Every variable points to an object that has a type, value, and reference count.

Understanding Python Variables:

# Variable assignment and type checking
>>> age = 20
>>> type(age)
<class 'int'>

>>> name = 'Python'
>>> type(name)
<class 'str'>

>>> name = {'Python', 'C', 'C++'}
>>> type(name)
<class 'set'>

How Variables Work in Python:

  • Creation: When you assign a value, Python creates an object in memory
  • Reference: The variable name becomes a reference to that object
  • Rebinding: When the value changes, Python creates a new object and updates the reference
  • Garbage Collection: Old objects are automatically cleaned up when no longer referenced
# Memory address changes when value changes
>>> age = 20
>>> id(age)
1716585200

>>> age = 11
>>> id(age)
1716585232
# Different memory address = new object!

4. Rules for Naming Python Variables

āœ… Legal Variable Names

myname = "Python"
my_name = "Python"
_my_name = "Python"
myName = "Python"
MYNAME = "Python"
myname2 = "Python"

āŒ Illegal Variable Names

2myname = "Python" (starts with digit)
my-name = "Python" (has hyphen)
my var = "Python" (has space)

# āœ… Valid variable names
myname = "Python"
my_name = "Python"
_my_name = "Python"
myName = "Python"
MYNAME = "Python"
myname2 = "Python"

# āŒ Invalid variable names (will raise errors)
2myname = "Python"    # SyntaxError
my-name = "Python"    # SyntaxError
my var = "Python"     # SyntaxError

5. Variables vs Identifiers — What's the Difference?

Variables Identifiers
A variable is a unique name given to a memory location A unique name given to any entity is called an identifier
Variable names are called identifiers The range of identifiers is higher than variables
A variable is a name given to a memory location that holds some kind of value An identifier is a name given to variables, constants, lists, tuples, classes, etc.

šŸ’” Simple way to remember: All variables are identifiers, but not all identifiers are variables! Identifiers are the general term for any named entity in Python.

Try It Yourself!

Now it's your turn! Write and run Python code directly in your browser:

Loading Pyodide... 0%
Python Code Editor
šŸ”‘ Python Keywords:
['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']

Name: Python Learner
Age: 25
Private: This is private

Language: Python
Version: 3.11
Is Popular? True
Numbers: [1, 2, 3, 4]

x is 10 (type: int)
x is Hello (type: str)
x is 3.14 (type: float)

age = 20, id: 1716585200
age = 21, id: 1716585232

āœ… Experiment with your own variables!

šŸŽÆ Challenge Yourself!
• Create a variable with your favorite programming language
• Try creating an invalid identifier and see the error
• Check the type of different variables using type()

šŸ†

šŸŽ‰ You've Mastered Python Keywords, Identifiers & Variables!

You now understand the naming rules of Python — keywords, identifiers, and variables. These are fundamental to writing clean, correct Python code!

Quick Quiz - Test Your Knowledge

Let's see what you've learned:

1. How many keywords does Python 3.11 have?
2. Which of these is a valid identifier in Python?
3. What happens when you reassign a variable to a different value in Python?

Frequently Asked Questions

šŸ¤” What is the difference between a keyword and an identifier? ā–¼

Keywords are reserved words that Python uses for its own syntax — like if, while, and def. You cannot use them as names. Identifiers are names you create for variables, functions, and classes. They follow specific naming rules and cannot be keywords.

šŸ’» Can I use a keyword as a variable name? ā–¼

No! Keywords are reserved by Python and cannot be used as identifiers. If you try to use a keyword like if or class as a variable name, Python will raise a syntax error. This is why you should always check if a word is a keyword before using it as a name.

šŸŽÆ Why are identifiers case-sensitive in Python? ā–¼

Python treats uppercase and lowercase letters as different characters. So myVar and myvar are two different identifiers. This allows you to create more precise and meaningful names, following the Python convention of using lowercase with underscores for variables (snake_case).

šŸ“š What is the difference between variables and identifiers? ā–¼

While often used interchangeably, there is a subtle difference. An identifier is the name you give to any entity (variable, function, class, etc.). A variable is a specific type of identifier that refers to a memory location storing data. All variables are identifiers, but not all identifiers are variables (e.g., function names are identifiers but not variables).

šŸ“š Where to Go From Here

Now that you understand Python keywords, identifiers, and variables, here are some related topics to explore:

šŸ”£ Python Tokens

Learn about keywords, identifiers, and operators

šŸ“Š Data Types

Explore Python's built-in data types

šŸ”§ Operators

Deep dive into Python operators

šŸ“– Related Tutorials
  • What is Python
  • Tokens in Python
  • Character Set in Python
  • Applications of Python
Previous: Python Execution Mode Next: Data Types in Python →