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 Tokens: Complete Guide with Examples

Python Tokens - Complete Guide

Understanding Python tokens — the building blocks of every Python program

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:
  • What are Python Tokens?
  • Keywords in Python
  • Identifiers in Python
  • Literals in Python
  • Operators in Python
  • Delimiters in Python
  • 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
  • What are Python tokens and why they matter in your code
  • Keywords — Python's reserved words and what they do
  • Identifiers — How to name variables, functions, and classes
  • Literals — Constants and fixed values in Python
  • Operators — Symbols that perform operations on data
  • Delimiters — Punctuation that structures your code
  • Write and run Python code with tokens in the browser
  • Test your knowledge with interactive quizzes

So, What Exactly Are Python Tokens?

Think of tokens as the building blocks of Python code — the smallest units that the Python interpreter understands. When you write a program, Python breaks it down into these tokens to figure out what you want it to do.

Here's a simple way to think about it: just like how English sentences are made up of words and punctuation, Python programs are made up of tokens. Each token has a specific meaning to the interpreter.

Python has five main types of tokens:

  • Keywords: Reserved words with special meanings
  • Identifiers: Names for variables, functions, and classes
  • Literals: Fixed values like numbers and strings
  • Operators: Symbols that perform operations
  • Delimiters: Punctuation that structures your code

💡 Fun fact: When the Python interpreter reads your code, it first breaks it down into tokens — this process is called "lexical analysis." Once it has all the tokens, it figures out what to do with them!

1. Keywords — Python's Reserved Words

Keywords are reserved words that have a special meaning in Python. You cannot use them as variable names, function names, or identifiers.

Think of keywords as Python's built-in vocabulary — they're the words that Python understands without any explanation. Here are some common keywords:

Keywords in Python (36 in total):

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

Here's how you can list all the keywords yourself:

# Python script to list all keywords
import keyword
print(keyword.kwlist)

📝 Important: There are 36 keywords in Python 3.11. They're all in lowercase except True, False, and None.

2. Identifiers — Naming Your Code

Identifiers are names you give to variables, functions, classes, and other objects. They help you refer to things in your code.

Here are the rules for naming identifiers in Python:

  • Start with a letter or underscore: Must begin with a letter (a-z, A-Z) or underscore (_)
  • Can contain numbers: After the first character, you can use numbers (0-9)
  • Case-sensitive: myVar and myvar are different
  • Can't use keywords: You can't use if, while, class, etc.
  • No special characters: Only letters, numbers, and underscores are allowed

✅ Valid Identifiers

my_var
_private
name123
userName

❌ Invalid Identifiers

123name (starts with number)
my-var (has hyphen)
if (is a keyword)

💡 Pro tip: Use descriptive names like user_age instead of u or age_of_user. It makes your code much easier to read!

3. Literals — Fixed Values

Literals are fixed values that you write directly in your code. They represent constant values that don't change.

Python has several types of literals:

Type Example Description
String Literals "Hello" or 'World' Text values in quotes
Integer Literals 42, 100, -5 Whole numbers
Float Literals 3.14, 2.5, -1.0 Decimal numbers
Boolean Literals True, False True/False values
None Literal None Represents "no value"
# Examples of different literals
name = "Python"           # String literal
age = 30                  # Integer literal
price = 19.99             # Float literal
is_popular = True         # Boolean literal
nothing = None            # None literal

4. Operators — Performing Operations

Operators are symbols that tell Python to perform specific operations on values and variables.

Python has several types of operators:

Common Operators in Python:

Arithmetic:  +   -   *   /   //   %   **
Comparison:  ==  !=  >   <   >=   <=
Logical:     and  or  not
Assignment:   =   +=  -=  *=  /=
Membership:   in  not in
Identity:     is  is not
# Examples of operators
a = 10
b = 3

print(a + b)   # 13 (addition)
print(a - b)   # 7 (subtraction)
print(a * b)   # 30 (multiplication)
print(a / b)   # 3.33 (division)
print(a % b)   # 1 (modulus - remainder)
print(a ** b)  # 1000 (power)

# Comparison
print(a > b)   # True
print(a == b)  # False

5. Delimiters — Structuring Your Code

Delimiters are punctuation marks that help organize your code. They define where blocks start and end, and they separate elements.

Common Delimiters in Python:

( )   Parentheses    - Used for function calls and grouping
[ ]   Square brackets - Used for lists and indexing
{ }   Curly braces   - Used for dictionaries and sets
;     Semicolon      - Separates statements (rarely used)
:     Colon          - Indicates start of a block
,     Comma          - Separates items
.     Period         - Access object attributes
# Examples of delimiters
my_list = [1, 2, 3]        # [ ] and ,
my_dict = {"name": "Python"} # { } and :
print(my_dict["name"])     # ( ) and [ ]

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

My name is Python Learner
I am 25 years old

Name: Sankalan
Score: 95
Pi: 3.14159
Awesome? True

10 + 3 = 13
10 - 3 = 7
10 * 3 = 30
10 / 3 = 3.3333333333333335
10 % 3 = 1

List: [1, 2, 3, 4, 5]
Dictionary: {'name': 'Python', 'age': 30}

🎯 Challenge Yourself!
• Add a new variable with your name and print it
• Try using the multiplication operator with two numbers
• Create a list of your favorite colors

🏆

🎉 You've Mastered Python Tokens!

You now understand the building blocks of Python — keywords, identifiers, literals, operators, and delimiters. These are the foundation of every Python program you'll ever write!

Quick Quiz - Test Your Knowledge

Let's see what you've learned about Python tokens:

1. What are the five main types of Python tokens?
2. How many keywords are there in Python 3.11?
3. Which of these is a valid identifier 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 purposes — like if, while, and class. You cannot use them as names for variables or functions. Identifiers are names you create for your own variables, functions, and classes. They can be anything as long as they follow Python's naming rules.

💡 Why do we need delimiters in Python? ▼

Delimiters help Python understand the structure of your code. They separate different elements and mark the beginning and end of code blocks. For example, parentheses () are used for function calls and grouping expressions, while colons : indicate the start of a block like an if statement or loop.

🎯 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 while as a variable name, Python will give you a syntax error. This is why you should always check if a word is a keyword before using it as a name.

📚 Why are tokens important to understand? ▼

Tokens are the building blocks of Python. Understanding them helps you write correct code, avoid errors, and understand how Python interprets your programs. It's like learning the alphabet before you start writing sentences — once you know the basics, everything else becomes much easier!

📚 Where to Go From Here

Now that you understand Python tokens, here are some related topics to explore:

🔤 Character Set

Learn about Python's character set and encoding

📊 Data Types

Explore Python's built-in data types

🔧 Operators

Deep dive into Python operators

📖 Related Tutorials
  • What is Python
  • Character Set in Python
  • Data Types in Python
  • Applications of Python
Previous: Character Set Next: Python Execution Mode →