CBSE Class 11 Computer Science

5. Getting Started with Python

5 sections AI-powered notes
GET THE FULL EXPERIENCE

This is the chapter notes. Students get the interactive version.

  • Ask Aarav Sir anything — instant voice + chat doubts
  • Interactive lessons with audio narration + visual diagrams
  • Study Lab — paste any photo, PDF, or YouTube link to get it explained

Introduction to Python

Introduction to Python

What is Python?

Python is a high-level, interpreted programming language that has become one of the most popular choices for beginners and professionals alike. Created by Guido van Rossum and first released in 1991, Python was designed with a philosophy that emphasizes code readability and simplicity. The name "Python" doesn't come from the snake — it was inspired by the British comedy series Monty Python's Flying Circus, reflecting the language's fun and approachable nature.

Unlike low-level languages such as machine language (binary code of 0s and 1s), Python allows us to write instructions in a form that closely resembles human language. This makes it much easier to learn, understand, and maintain.

{{VISUAL: diagram: comparison showing machine language (binary 0s and 1s) on left, high-level Python code in the middle, and the interpreter translating between them on right}}

{{KEY: type=definition | title=Programming Language | text=A programming language is a formal set of instructions that can be used to produce various kinds of output. It serves as a medium of communication between humans and computers.}}


Why Python? Key Characteristics

Python stands out from other programming languages due to several distinctive features that make it an excellent choice for both learning and professional development.

1. High-Level and Human-Readable

Python's syntax is clean and resembles everyday English. For example, to print "Hello, World!" in Python, we simply write:

print("Hello, World!")

Compare this with languages like C++ or Java, where the same task requires significantly more code and complex syntax.

2. Interpreted Language

Python uses an interpreter rather than a compiler. An interpreter translates and executes the program line by line, stopping immediately when it encounters an error. This makes debugging easier — you know exactly where the problem occurred.

How does this differ from compiled languages?
A compiler translates the entire source code into machine code at once, generating an object file. Only after scanning the whole program does it report errors. Languages like C and C++ use compilers.

{{VISUAL: diagram: side-by-side comparison showing interpreter processing code line-by-line versus compiler translating entire code at once}}

{{KEY: type=concept | title=Interpreter vs Compiler | text=An interpreter executes source code line by line, stopping at the first error. A compiler translates the entire program first, then reports all errors together. Python uses an interpreter for immediate feedback.}}

3. Free and Open Source

Python is completely free to download, install, and use — even for commercial purposes. Its open-source nature means thousands of developers worldwide contribute to improving it, creating a vast ecosystem of libraries and frameworks.

4. Platform Independent and Portable

A Python program written on Windows can run on macOS or Linux without modification. This portability makes Python ideal for cross-platform development.

5. Rich Standard Library

Python comes with a comprehensive standard library — a collection of pre-written code modules that provide ready-to-use functions for common tasks like file handling, mathematical operations, web development, and data processing. This follows the philosophy "batteries included".

6. Case Sensitive

Python distinguishes between uppercase and lowercase letters. For example, NUMBER, Number, and number are three different identifiers in Python. This is crucial to remember when writing variable names or using keywords.

{{KEY: type=points | title=Key Features of Python | text=- High-level, human-readable syntax

  • Interpreted language with immediate feedback
  • Free, open source, and community-driven
  • Platform independent and portable
  • Rich standard library with pre-built functions
  • Case sensitive — 'Name' and 'name' are different
  • Uses indentation to define code blocks}}

Python Shell: Your First Interaction

When you install Python and launch it, you'll see the Python shell (also called the Python interpreter). This is an interactive environment where you can type Python commands and see results immediately.

The shell displays a special symbol called the prompt: >>>

This prompt indicates that the interpreter is ready to accept your instructions. You can type any valid Python statement after this prompt, press Enter, and Python will execute it instantly.

Example: Using the Shell as a Calculator

>>> 5 + 3
8
>>> 10 * 4
40
>>> 2 ** 3
8

The ** operator means "to the power of" — so 2 ** 3 means 2³ = 8.

{{VISUAL: photo: screenshot of Python shell window showing the >>> prompt and simple arithmetic operations being executed}}

{{KEY: type=exam | title=Quick Revision Point | text=The >>> symbol is the Python prompt in interactive mode. It indicates the interpreter is ready for input. This is frequently asked in objective questions about Python environment.}}


Two Ways to Work with Python

Python offers two distinct execution modes, each suited for different purposes.

Interactive Mode

In interactive mode, you type statements directly at the >>> prompt, and Python executes them immediately. This mode is perfect for:

  • Testing small code snippets
  • Experimenting with Python features
  • Using Python as a calculator
  • Learning and exploring

Limitation: You cannot save your code for later use. Once you close the shell, everything is lost.

Script Mode

In script mode, you write your Python program in a text file with a .py extension (for example, hello.py), save it, and then run the entire file through the interpreter.

Steps to work in Script Mode:

  1. Write your Python code in any text editor or Python's built-in IDLE editor
  2. Save the file with a .py extension
  3. Execute the file using the Python interpreter

{{FORMULA: expr=Python Script = Source Code + .py extension | symbols=Source Code:human-readable Python instructions, .py:standard Python file extension}}

Advantages of Script Mode:

  • You can write multiple lines of code
  • Code is saved and can be reused
  • Easy to modify and debug
  • Suitable for building complete programs

{{KEY: type=concept | title=Interactive vs Script Mode | text=Interactive mode executes single statements immediately at the >>> prompt, ideal for testing. Script mode saves multiple statements in a .py file for repeated execution, ideal for building programs.}}


Your First Python Program

Let's write a simple program in script mode that displays a message on the screen.

Program 5-1: A program to print a message

print("Welcome to Python Programming!")

When you run this program, Python executes the print() function, which displays the text between the quotation marks on the screen.

Output:

Welcome to Python Programming!

{{ZOOM: title=Why Quotation Marks? | text=Text in Python must be enclosed in quotes (single ' ' or double " ") to distinguish it from code. Without quotes, Python would think 'Welcome' is a variable name, causing an error. Strings — sequences of characters — always need quotes.}}


Looking Ahead

Now that you understand what Python is and how to interact with it through the shell and scripts, you're ready to dive deeper. In the following sections, we'll explore keywords (reserved words in Python), identifiers (names we create), data types (kinds of values), and how to write meaningful programs that accept input, process data, and produce output.

Remember: Programming is not about memorizing syntax — it's about problem-solving. Python simply gives you the tools; your logic brings programs to life.


Python Keywords, Identifiers, Variables, and Comments

Python Keywords, Identifiers, Variables, and Comments

Before we can write meaningful Python programs, we must understand the fundamental building blocks of Python code. Think of these as the grammar rules and vocabulary of Python — master them, and you'll be able to express any computational idea clearly and correctly.


Python Keywords

Keywords are reserved words in Python that have special meanings defined by the language itself. They form the core vocabulary of Python and cannot be used for any other purpose. Every keyword serves a specific function, and Python's interpreter recognizes them instantly.

{{KEY: type=definition | title=Python Keywords | text=Keywords are reserved words with predefined meanings in Python. Each keyword performs a specific function and cannot be used as an identifier (variable name, function name, etc.). Python is case-sensitive, so keywords must be written exactly as specified.}}

Python 3 has 35 keywords that control program flow, define data structures, handle exceptions, and more. Here's the complete list:

Control FlowData & LogicFunctions & ClassesException Handling
if, elif, elseTrue, False, Nonedef, class, lambdatry, except, finally, raise
for, while, break, continueand, or, not, is, inreturn, yieldassert
passwith, asglobal, nonlocal-
-import, from, del--

{{VISUAL: diagram: color-coded table showing Python keywords organized by category with examples of common usage}}

Case Sensitivity Matters!

Python is strictly case-sensitive. This means True is a keyword, but true or TRUE are not — attempting to use the wrong case will cause errors. For example:

if True:        # Correct - keyword recognized
    print("Valid")

if true:        # Error - 'true' is not defined
    print("Invalid")

{{KEY: type=exam | title=Common Trap | text=In exams, students often write keywords in incorrect case (e.g., TRUE instead of True, While instead of while). Remember: all Python keywords are lowercase except True, False, and None. Even one incorrect character breaks the program.}}


Identifiers: Naming Your Data

While keywords are Python's built-in vocabulary, identifiers are the names you create to label your data and functions. An identifier uniquely identifies a variable, function, class, or any other object in your program.

{{KEY: type=definition | title=Identifiers | text=Identifiers are user-defined names given to variables, functions, classes, or other entities in a Python program. They help make code readable and meaningful by replacing arbitrary labels with descriptive names.}}

Rules for Creating Valid Identifiers

Python enforces strict rules for identifier names. Follow these carefully:

  1. Must start with a letter (a-z, A-Z) or underscore (_) — never a digit
  2. Can contain letters, digits (0-9), and underscores — no special symbols like @, $, %, !, etc.
  3. Cannot be a Python keyword — you can't name a variable for or while
  4. Case-sensitivemarks, Marks, and MARKS are three different identifiers
  5. Can be any length — but keep them short and meaningful

{{VISUAL: diagram: flowchart showing identifier validation rules with examples of valid and invalid identifiers at each decision point}}

Examples: Good vs. Bad Identifiers

Valid Identifiers ✓Invalid Identifiers ✗Reason for Error
student_namestudent-nameHyphen not allowed
marks1, marks21stmarksCannot start with digit
_averageclass'class' is a keyword
totalMarkstotal@marks@ symbol not allowed
PI, pi, Pifor'for' is a keyword

Best Practices for Meaningful Names

While a, b, c are valid identifiers, they tell us nothing about the data they hold. Compare these two approaches:

Poor naming:

a = 85
b = 90
c = 78
d = (a + b + c) / 3

Meaningful naming:

math_marks = 85
science_marks = 90
english_marks = 78
average_marks = (math_marks + science_marks + english_marks) / 3

The second version is self-documenting — anyone reading it instantly understands what the program does.

{{KEY: type=points | title=Identifier Naming Conventions | text=- Use descriptive names that reveal purpose (amount, total_price, student_id)

  • For multi-word names, use underscores (snake_case): student_name, total_marks
  • Constants should be UPPERCASE: PI, MAX_SIZE, TAX_RATE
  • Private variables start with underscore: _internal_value
  • Avoid single-letter names except for counters (i, j, k in loops)}}

Variables: Containers for Data

A variable is a named storage location that holds a value in memory. Unlike some languages where you must declare a variable's type explicitly, Python uses dynamic typing — variables are created automatically when you assign them a value.

{{KEY: type=concept | title=Variables in Python | text=A variable is a named reference to an object in memory. In Python, variables are dynamically typed and implicitly declared — you create them simply by assigning a value. The type of a variable is determined by the value it holds and can change during program execution.}}

Creating and Using Variables

Variables are created using the assignment operator (=). The general syntax is:

variable_name = value

Let's see variables in action:

# Numeric variable
price = 987.9

# String variables (text in quotes)
gender = 'M'
message = "Keep Smiling"

# Variables can be used in expressions
user_no = 101
next_user = user_no + 1

{{VISUAL: diagram: memory representation showing variable names pointing to objects in memory with their values and types}}

Program Example: Variables in Action

# Program 5-2: Display values of variables
message = "Keep Smiling"
print(message)

userNo = 101
print('User Number is', userNo)

Output:

Keep Smiling
User Number is 101

Notice that message holds text (enclosed in quotes), while userNo holds a number (no quotes needed).

{{KEY: type=exam | title=String Values Need Quotes | text=In CBSE exams, a common error is forgetting quotes around string values. Remember: text values must be in single or double quotes (e.g., "Hello"), but numeric values must NOT have quotes (e.g., 42, not "42"). The quote marks tell Python "this is text, not a number or variable name".}}

Variables Must Be Assigned Before Use

Unlike some languages, Python requires that every variable be assigned a value before it's used in an expression. This prevents undefined behavior:

total = marks1 + marks2    # Error if marks1, marks2 not assigned yet

marks1 = 85
marks2 = 90
total = marks1 + marks2    # Now it works - total = 175

Every Variable is an Object

In Python's design philosophy, everything is an object. Each variable refers to an object in memory, and every object has a unique identity (like a memory address). The built-in id() function reveals this identity:

num1 = 20
print(id(num1))    # Output: 1433920576 (example ID)

num2 = 30
print(id(num2))    # Different ID - different object

{{ZOOM: title=Object Identity and Memory | text=When you assign num1 = 20, Python creates an integer object with value 20 in memory and makes num1 point to it. The id() function returns the memory address of that object. Two variables with the same value might point to the same object (Python optimizes small integers this way) or different objects — id() reveals the truth.}}


Comments: Documenting Your Code

Comments are annotations in source code that explain what the code does and why. They are completely ignored by the Python interpreter — they exist purely for human readers.

{{KEY: type=definition | title=Comments | text=Comments are non-executable lines in source code used to document the program's purpose, logic, and usage. In Python, comments begin with the hash symbol (#). Everything after # on that line is ignored by the interpreter.}}

Why Comments Matter

  1. Remember your own code — when you revisit a program months later, comments remind you what you were thinking
  2. Team collaboration — other programmers can understand your logic quickly
  3. Maintenance — when fixing bugs, comments help identify what each section does
  4. Documentation — input/output requirements, assumptions, and limitations

Creating Comments in Python

In Python, single-line comments start with #:

# This is a comment - Python ignores this line
price = 100    # Comments can also follow code on the same line

# Calculate total cost including 18% tax
tax = price * 0.18
total = price + tax

For multi-line explanations, use multiple # symbols:

# This function calculates the area of a rectangle.
# Input: length and breadth as numeric values
# Output: area as a numeric value
# Formula: area = length × breadth

length = 10
breadth = 20
area = length * breadth

{{KEY: type=points | title=Good Commenting Practices | text=- Explain WHY, not just WHAT (code shows what, comments explain why)

  • Keep comments up-to-date when code changes
  • Use comments for complex logic, not obvious statements
  • Document function inputs, outputs, and assumptions
  • Avoid over-commenting — clean code needs fewer explanations}}

Program Example with Comments

# Program 5-4: Find the sum of two numbers
# Purpose: Demonstrate basic arithmetic and variable usage

num1 = 10      # First number
num2 = 20      # Second number
result = num1 + num2    # Add the two numbers
print(result)  # Display the result

Output:

30

Putting It All Together

Let's combine all these concepts in one practical program:

# Program: Calculate rectangle area
# Demonstrates: keywords, identifiers, variables, comments

# Define dimensions (variables with meaningful names)
length = 10
breadth = 20

# Calculate area using arithmetic operator
area = length * breadth    # Formula: area = length × breadth

# Display the result
print(area)

Output:

200

This simple program uses:

  • Keywords: print
  • Identifiers: length, breadth, area (meaningful names, not a, b, c)
  • Variables: created by assignment, holding numeric values
  • Comments: explaining purpose and formula
  • Arithmetic operator: * for multiplication

Master these four fundamentals — keywords, identifiers, variables, and comments — and you've built a solid foundation for all future Python programming.


Everything Is an Object & Numeric Data Types

Page 3: Everything Is an Object & Numeric Data Types

Python's Object-Oriented Nature

In Python, everything is an object. This is a fundamental philosophy that sets Python apart from many other programming languages. Whether you're working with numbers, strings, or even functions — each value you create is treated as an object with its own identity, type, and value.

When you assign a value to a variable, Python creates an object in memory and gives your variable a reference to that object. This object remains in memory with a unique identity that never changes during its lifetime. Think of this identity as the object's "home address" in your computer's memory.

{{KEY: type=concept | title=Everything is an Object | text=In Python, every data item — whether a number, string, list, or function — is treated as an object. Each object has a unique identity (memory address), a type (what kind of data it is), and a value (the actual data stored).}}

Understanding Object Identity

Stuck on something here?
Aarav Sir explains any part — voice or chat — 24/7.

Python provides the id() function to reveal an object's identity. Let's explore this with a practical example:

>>> num1 = 20
>>> id(num1)
1433920576
>>> num2 = 30 - 10
>>> id(num2)
1433920576

Notice something interesting? Both num1 and num2 have the same identity! This is because they both refer to the same object — the integer 20. Python is smart enough to reuse existing objects when possible, saving memory and improving performance.

{{VISUAL: diagram: memory representation showing two variables num1 and num2 pointing to the same object 20 with identity 1433920576}}

When two variables refer to the same object, they share the same identity — a key insight into how Python manages memory efficiently.

{{ZOOM: title=Why Same Object for Same Value? | text=Python maintains a pool of commonly used small integers (typically -5 to 256) to optimize memory usage. When you create these values, Python reuses the existing object rather than creating a new one. This is called "integer interning" and it speeds up your programs significantly.}}


Numeric Data Types in Python

Python provides three primary numeric data types to handle different kinds of mathematical values. Understanding these types is crucial for writing efficient programs and avoiding calculation errors.

The Number Family

{{VISUAL: diagram: hierarchical tree showing Number as parent type with three children: int, float, and complex, each with examples}}

Python's numeric types are organized into a clear hierarchy:

Data TypeClass NameDescriptionExample Values
IntegerintWhole numbers (positive, negative, or zero)-12, 0, 125, 1000
Floating PointfloatReal numbers with decimal points-2.04, 4.0, 14.23, 9.8e2
ComplexcomplexNumbers with real and imaginary parts3+4j, 2-2j, -5j

{{KEY: type=definition | title=Integer (int) | text=An integer is a whole number without any fractional component. It can be positive, negative, or zero. Python integers have unlimited precision — they can be as large as your computer's memory allows.}}

Working with Integers

Integers (int) are the most commonly used numeric type. They represent counting numbers and are perfect for loops, indexing, and counting operations.

>>> num1 = 10
>>> type(num1)
<class 'int'>
>>> num2 = -1210
>>> type(num2)
<class 'int'>

The type() function is your best friend for discovering what kind of data you're working with. It returns the class (type) of any object.

Floating Point Numbers

Floating point numbers (float) represent real numbers — numbers that can have a fractional part. They're essential for scientific calculations, measurements, and any situation requiring decimal precision.

>>> float1 = -1921.9
>>> type(float1)
<class 'float'>
>>> float2 = -9.8 * 10**2
>>> print(float2, type(float2))
-980.0000000000001 <class 'float'>

{{KEY: type=exam | title=Floating Point Precision | text=Notice the output -980.0000000000001 instead of exactly -980.0. This is due to how computers store decimal numbers in binary. CBSE may test your understanding of float precision limitations in case-based questions.}}

Notice the small precision error in float2? This is a characteristic of how computers store decimal numbers. For most applications, this tiny difference is insignificant, but it's important to be aware of it when working with financial calculations or scientific data requiring high precision.

You can also write floats in scientific notation using e or E:

>>> speed_of_light = 3.0e8  # 3.0 × 10^8 m/s
>>> planck_constant = 6.626e-34  # 6.626 × 10^-34 J·s

{{KEY: type=concept | title=Scientific Notation in Python | text=Python uses the letter e or E to represent powers of 10. The notation 3.0e8 means 3.0 × 10^8. This is particularly useful for very large numbers (like astronomical distances) or very small numbers (like atomic measurements).}}

Complex Numbers

Complex numbers (complex) have both a real part and an imaginary part. They're written in the form a+bj, where a is the real part and b is the imaginary part. Python uses j (not i) to represent the imaginary unit √(-1).

>>> var2 = -3 + 7.2j
>>> print(var2, type(var2))
(-3+7.2j) <class 'complex'>
>>> impedance = 5 + 3j  # Electrical impedance
>>> wave = 2 - 2j       # Quantum wave function

Complex numbers are essential in fields like electrical engineering, quantum physics, and signal processing. While you may not use them in everyday programs, they're a powerful tool when you need them.

{{VISUAL: chart: comparison table showing operations supported by int, float, and complex types with checkmarks and crosses}}

Boolean: A Special Numeric Subtype

Here's a surprise: Boolean (bool) is actually a subtype of integer! Python's Boolean type consists of only two values: True and False. These are special integer values where True equals 1 and False equals 0.

>>> var1 = True
>>> type(var1)
<class 'bool'>
>>> True + True
2
>>> False * 5
0

{{KEY: type=points | title=Boolean Characteristics | text=- Boolean is a subtype of integer in Python

  • True represents any non-zero, non-null, non-empty value
  • False represents zero, null, or empty values
  • Booleans can participate in arithmetic operations (True=1, False=0)}}

This design makes Python very flexible — you can use Boolean values in mathematical expressions, which is particularly useful in data analysis and statistical calculations.

Determining Data Types

Always use the type() function when you're unsure about a variable's data type:

>>> mystery_var = 3.14159
>>> type(mystery_var)
<class 'float'>
>>> another_var = 42
>>> type(another_var)
<class 'int'>

Understanding data types prevents errors and helps you write more reliable code. For example, you can't concatenate a string and an integer directly — you need to convert them to compatible types first.


Key Takeaways

The foundation of Python programming rests on understanding that everything is an object and knowing which numeric type to use for each situation. Integers handle whole numbers, floats manage decimals, complex numbers solve advanced mathematical problems, and Booleans represent truth values.

As you progress, you'll develop an intuition for choosing the right type. For now, practice identifying types using type() and id(), and experiment with different numeric operations to see how Python handles each type.


Sequence Data Types

Sequence Data Types

Understanding Sequences in Python

When you need to store multiple related values in a particular order—such as the days of the week, temperatures recorded over a week, or names of students in a class—Python provides sequence data types. A sequence is an ordered collection of items where each item is assigned a unique position, called an index, starting from 0.

Python offers three built-in sequence types: Strings, Lists, and Tuples. Each has unique characteristics that make it suitable for different programming scenarios. Understanding when and how to use each type is fundamental to writing efficient Python programs.

{{VISUAL: diagram: comparison of three sequence types showing String with characters in quotes, List with mixed items in square brackets, and Tuple with mixed items in parentheses, all with index positions labeled 0, 1, 2}}


Strings: Working with Text

A String is a sequence of characters enclosed in either single quotes ('...') or double quotes ("..."). Characters can include alphabets, digits, special symbols, and spaces. Strings are one of the most commonly used data types in Python.

{{KEY: type=definition | title=String | text=A String is an ordered sequence of characters enclosed in single or double quotation marks. The quotes mark the beginning and end of the string for the Python interpreter but are not part of the string itself.}}

Creating and Using Strings

>>> greeting = 'Hello Friend'
>>> city = "New Delhi"
>>> code = "452"
>>> print(greeting)
Hello Friend
>>> print(type(city))
<class 'str'>

Notice that code = "452" creates a string, not a number. Even though the characters are digits, the quotation marks tell Python to treat them as text. You cannot perform arithmetic operations on strings, even when they contain numeric-looking characters.

>>> code = "452"
>>> code + 100  # This will cause an error!
TypeError: can only concatenate str (not "int") to str

{{KEY: type=concept | title=Strings Are Immutable | text=Once a string is created, you cannot change individual characters within it. Any operation that appears to modify a string actually creates a new string object in memory. This property is called immutability.}}

Practical Applications of Strings

Strings are used extensively for:

  • Storing names, addresses, and user input
  • Processing text files and documents
  • Working with file paths and URLs
  • Displaying messages and output

Lists: Flexible Ordered Collections

A List is a sequence of items separated by commas and enclosed in square brackets [ ]. Unlike strings, lists can contain items of different data types—integers, floats, strings, and even other lists.

{{KEY: type=definition | title=List | text=A List is an ordered, mutable sequence of items separated by commas and enclosed in square brackets. Lists can contain elements of different data types and can be modified after creation.}}

Creating and Accessing Lists

>>> list1 = [5, 3.4, "New Delhi", "20C", 45]
>>> print(list1)
[5, 3.4, 'New Delhi', '20C', 45]
>>> print(type(list1))
<class 'list'>

Each element in a list has an index (position number) starting from 0. You can access individual elements using their index:

>>> list1[0]   # First element
5
>>> list1[2]   # Third element
'New Delhi'

{{VISUAL: diagram: visual representation of list indexing showing list1 with five elements and arrows pointing to each index position from 0 to 4}}

Why Lists Are Mutable

Unlike strings, lists are mutable—you can change, add, or remove elements after the list is created. This flexibility makes lists ideal for data that needs frequent updates.

>>> fruits = ["Apple", "Banana", "Cherry"]
>>> fruits[1] = "Mango"  # Replace Banana with Mango
>>> print(fruits)
['Apple', 'Mango', 'Cherry']

{{KEY: type=points | title=When to Use Lists | text=- When you need to store multiple related items in a specific order

  • When the data needs to be modified frequently (adding, removing, or updating elements)
  • When you need a collection that can grow or shrink dynamically
  • Example: Names of students in a class (as students may join or leave)}}

{{ZOOM: title=List Memory Efficiency | text=When you update a list element, Python modifies the existing list object in memory. However, when you update a string, Python creates an entirely new string object. This makes lists more memory-efficient for frequently changing data.}}


Tuples: Immutable Ordered Collections

A Tuple is similar to a list but with one crucial difference: tuples are immutable. Once created, you cannot change, add, or remove elements. Tuples are created using parentheses ( ) instead of square brackets.

{{KEY: type=definition | title=Tuple | text=A Tuple is an ordered, immutable sequence of items separated by commas and enclosed in parentheses. Once a tuple is created, its elements cannot be modified, added, or removed.}}

Creating and Using Tuples

>>> tuple1 = (10, 20, "Apple", 3.4, 'a')
>>> print(tuple1)
(10, 20, 'Apple', 3.4, 'a')
>>> print(type(tuple1))
<class 'tuple'>

You can access tuple elements by index, just like lists:

>>> tuple1[2]
'Apple'

But attempting to modify a tuple raises an error:

>>> tuple1[0] = 15  # Try to change first element
TypeError: 'tuple' object does not support item assignment

Why Use Tuples?

Because tuples are immutable, they offer several advantages:

  • Data integrity: Values are protected from accidental changes
  • Performance: Tuples are slightly faster than lists in Python
  • Dictionary keys: Only immutable types can be used as dictionary keys

{{KEY: type=points | title=When to Use Tuples | text=- When you need to store data that should never change during program execution

  • When you want to ensure data integrity and prevent accidental modifications
  • For fixed collections like coordinates (latitude, longitude), RGB color values, or database records
  • Example: Names of months in a year, days of the week}}

{{VISUAL: diagram: side-by-side comparison table showing List versus Tuple with rows for syntax, mutability, speed, use cases, and example code}}


Comparing Sequences: Making the Right Choice

FeatureStringListTuple
Syntax'...' or "..."[item1, item2, ...](item1, item2, ...)
Data TypesCharacters onlyMixed types allowedMixed types allowed
Mutable?NoYesNo
IndexingYes (by position)Yes (by position)Yes (by position)
Common UseText, messagesDynamic collectionsFixed data, constants

{{KEY: type=exam | title=Frequently Asked in CBSE Exams | text=Questions often ask you to identify whether a given code creates a list or tuple, or to explain why an error occurs when trying to modify an immutable sequence. Practice distinguishing between square brackets and parentheses.}}

The choice between list and tuple comes down to one question: Will this data need to change? If yes, use a list. If no, use a tuple.

Understanding these three sequence types—Strings, Lists, and Tuples—forms the foundation for working with collections in Python. As you progress, you'll learn powerful operations to manipulate, search, and transform sequences efficiently.


Summary & Quick Revision

Summary & Quick Revision

This final page consolidates the foundational concepts you've learned about Python programming. Use this as a rapid reference before exams or when you need to recall key ideas quickly. All content here aligns with the official NCERT Class 11 Computer Science syllabus and CBSE's competency-based examination pattern.


What is Python and Why Learn It?

Python is a high-level, interpreted, general-purpose programming language known for its simplicity and readability. Created by Guido van Rossum in 1991, Python has become one of the most popular languages worldwide for applications ranging from web development to artificial intelligence.

{{KEY: type=definition | title=Python | text=Python is a high-level, interpreted, general-purpose programming language that emphasizes code readability and supports multiple programming paradigms including procedural, object-oriented, and functional programming.}}

Key characteristics that make Python ideal for beginners:

  • Simple syntax that resembles natural English, reducing the learning curve
  • Interpreted execution — no separate compilation step required
  • Cross-platform compatibility — runs on Windows, macOS, Linux, and more
  • Rich standard library providing tools for diverse tasks without external dependencies
  • Free and open-source with a vibrant global community

{{VISUAL: diagram: flowchart showing Python code execution process from source code through interpreter to output}}


Python Programming Environments

To write and execute Python programs, you can use several environments depending on your needs:

ModeDescriptionBest For
Interactive ModeExecutes one statement at a time via Python shell (>>>)Quick testing, calculations, experimentation
Script ModeExecutes complete programs saved in .py filesWriting multi-line programs, projects, assignments
IDLEIntegrated Development and Learning Environment bundled with PythonBeginners, educational settings
Jupyter NotebookWeb-based interactive environment for code, text, and visualizationsData science, documentation-rich projects

{{KEY: type=points | title=Working Modes in Python | text=- Interactive Mode: Direct statement execution in Python shell, results displayed immediately, ideal for quick tests.

  • Script Mode: Complete programs saved as .py files, executed as a whole, better for complex projects.
  • IDLE: Python's default IDE with editor and shell integration, beginner-friendly interface.}}

Remember: In interactive mode, the >>> prompt indicates Python is ready to accept your command. Output appears immediately after you press Enter. In script mode, you write the entire program first, save it, then execute it as a single unit.


Understanding Python Tokens

A token is the smallest individual unit in a Python program. Think of tokens as the "words" of Python's language. The Python interpreter breaks your code into tokens before execution.

The five categories of tokens are:

  1. Keywords — Reserved words with special meaning (e.g., if, for, while, def, class)
  2. Identifiers — Programmer-defined names for variables, functions, classes (e.g., student_name, calculate_area)
  3. Literals — Fixed values written directly in code (e.g., 42, 3.14, "Hello", True)
  4. Operators — Symbols performing operations (e.g., +, -, *, /, ==, and)
  5. Delimiters — Symbols separating code elements (e.g., (), [], {}, :, ,)

{{KEY: type=concept | title=Python Identifiers | text=Identifiers are user-defined names for variables, functions, and other objects. Rules: must start with a letter (a-z, A-Z) or underscore (_), can contain letters, digits, and underscores, cannot be a Python keyword, are case-sensitive (Age and age are different).}}

Naming conventions you must follow:

  • Use snake_case for variables and functions: total_marks, calculate_average()
  • Use PascalCase for class names: StudentRecord, BankAccount
  • Avoid single-character names except for loops (i, j, k) or mathematical formulas (x, y)
  • Choose meaningful, descriptive names that clarify purpose: student_age not sa

{{ZOOM: title=Python is Case-Sensitive | text=Remember that Python treats Age, age, and AGE as three completely different identifiers. This case-sensitivity applies to keywords too — while is a keyword, but While and WHILE are valid identifiers (though using them would confuse readers).}}


Python Data Types: The Building Blocks

Every value in Python has a data type that determines what operations can be performed on it and how it's stored in memory. Python offers several built-in data types organized into categories:

{{VISUAL: diagram: hierarchical tree diagram showing classification of Python data types into numeric, sequence, boolean, None, set, and mapping categories with examples}}

Numeric Types

TypeDescriptionExampleImmutable?
intWhole numbers without decimal42, -17, 0Yes
floatNumbers with decimal point3.14, -0.5, 2.0Yes
complexNumbers with real and imaginary parts3+4j, 2jYes
boolLogical valuesTrue, FalseYes

{{KEY: type=definition | title=Integer (int) | text=An integer is a whole number without a fractional component, which can be positive, negative, or zero. Python integers have unlimited precision — they can grow as large as available memory permits.}}

Sequence Types

Sequences are ordered collections where each element has a position (index):

  • String (str) — Immutable sequence of characters enclosed in quotes: 'Hello' or "World"
  • List (list) — Mutable sequence of items enclosed in square brackets: [10, 20, 'Apple', 3.14]
  • Tuple (tuple) — Immutable sequence of items enclosed in parentheses: (10, 20, 'Apple', 3.14)

Key difference: Lists can be modified after creation (mutable), but tuples and strings cannot (immutable).

Other Important Types

  • Set (set) — Unordered collection of unique items in curly braces: {10, 20, 30}, automatically removes duplicates
  • Dictionary (dict) — Unordered collection of key-value pairs: {'name': 'Raj', 'age': 17, 'class': 11}
  • None (NoneType) — Special type representing absence of value

{{KEY: type=exam | title=Mutable vs Immutable | text=CBSE frequently asks: Which data types are mutable? Remember — Lists, Sets, and Dictionaries are mutable (changeable). Integers, Floats, Booleans, Strings, and Tuples are immutable (unchangeable). Attempting to modify immutable types creates new objects.}}


Mutable vs Immutable: Memory Behaviour

Understanding mutability is crucial for predicting how Python handles variables:

Immutable types (int, float, bool, str, tuple):

  • Once created, their value cannot be changed
  • Any "modification" creates a new object in memory
  • Multiple variables with the same value may share the same memory location (Python optimization)

Mutable types (list, set, dict):

  • Their contents can be modified after creation
  • Changes affect the same object in memory
  • Multiple variables can reference and modify the same object

{{VISUAL: diagram: side-by-side comparison showing memory allocation for immutable (integer) vs mutable (list) when values are updated}}

Example to remember:

# Immutable behavior
x = 100
y = x      # y references same object as x
x = 200    # x now references a NEW object, y unchanged

# Mutable behavior  
list1 = [1, 2, 3]
list2 = list1          # Both reference SAME list
list1.append(4)        # Modifies the shared list
# Now both list1 and list2 are [1, 2, 3, 4]

{{KEY: type=concept | title=Immutability and Memory | text=When you update an immutable variable, Python doesn't change the original object — it creates a new object with the new value and updates the variable reference. The old object is destroyed if no other variable references it. This behaviour ensures data integrity but requires understanding for efficient programming.}}


Choosing the Right Data Type

The appropriate data type depends on your program's requirements:

Use Lists when:

  • You need an ordered collection that may change frequently
  • Elements might be added, removed, or modified
  • Example: Student names in a class (students join/leave)

Use Tuples when:

  • You need an ordered collection that should never change
  • Data integrity is important
  • Example: Days of the week, coordinates (x, y)

Use Sets when:

  • You need uniqueness — no duplicate values allowed
  • Order doesn't matter
  • Example: Unique student ID numbers, set operations

Use Dictionaries when:

  • You need fast lookup based on a custom key
  • Data is naturally paired (key-value relationship)
  • Example: Phone book (name → number), student records (ID → details)

Use Strings when:

  • Working with text data
  • Example: Names, addresses, messages

{{KEY: type=exam | title=Data Type Selection | text=CBSE case-study questions often ask you to justify data type choice for a scenario. Remember the golden rule: List for changing ordered data, Tuple for fixed ordered data, Set for unique unordered data, Dictionary for key-value pairs needing fast lookup.}}


Quick Revision Checklist

Before your exam, ensure you can:

  • Explain what Python is and list three key features
  • Differentiate between interactive and script modes
  • Identify all five types of tokens in a code snippet
  • Apply identifier naming rules and conventions correctly
  • Classify data types as numeric, sequence, mapping, or set
  • Distinguish between mutable and immutable types with examples
  • Choose appropriate data types for given real-world scenarios
  • Use type() function to check data type of any value
  • Create variables following Python syntax and naming rules

Remember: Python's simplicity is its strength. Focus on understanding why each concept exists, not just what it is. This conceptual clarity will help you solve application-based CBSE questions effectively.

All the best for your examination! 🎯

In this chapter

  • 1.Introduction to Python
  • 2.Python Keywords, Identifiers, Variables, and Comments
  • 3.Everything Is an Object & Numeric Data Types
  • 4.Sequence Data Types
  • 5.Summary & Quick Revision

Frequently asked questions

What is Introduction to Python?

Unlike **low-level languages** such as machine language (binary code of 0s and 1s), Python allows us to write instructions in a form that closely resembles human language. This makes it much easier to learn, understand, and maintain.

What is Python Keywords, Identifiers, Variables, and Comments?

Before we can write meaningful Python programs, we must understand the **fundamental building blocks** of Python code. Think of these as the grammar rules and vocabulary of Python — master them, and you'll be able to express any computational idea clearly and correctly.

What is Everything Is an Object & Numeric Data Types?

In Python, **everything is an object**. This is a fundamental philosophy that sets Python apart from many other programming languages. Whether you're working with numbers, strings, or even functions — each value you create is treated as an object with its own identity, type, and value.

What is Sequence Data Types?

When you need to store **multiple related values** in a particular order—such as the days of the week, temperatures recorded over a week, or names of students in a class—Python provides **sequence data types**. A **sequence** is an ordered collection of items where each item is assigned a unique position, called an **i

What is Summary & Quick Revision?

This final page consolidates the **foundational concepts** you've learned about Python programming. Use this as a **rapid reference** before exams or when you need to recall key ideas quickly. All content here aligns with the official **NCERT Class 11 Computer Science** syllabus and CBSE's competency-based examination

More chapters in CBSE Class 11 Computer Science

Want the full CBSE Class 11 Computer Science experience?

Every chapter. Interactive lessons. AI tutor on tap. Study Lab for any photo or PDF. 7-day free trial — no credit card.

1000s of students
100% NCERT-aligned
Powered by AI

Install Learn Skill

Add to home screen for the best experience