Thursday, October 2, 2025

Python Notes for Standard XII

 Introduction to Problem-Solving

Problem-solving in computer science means using logical steps to design and implement a solution to a given problem.

 

What are the steps of Problem Solving?

Ans. Steps in Problem-Solving

·         Analysing the problem – Understand the problem, inputs, and outputs.

·         Developing an algorithm – Step-by-step procedure (can use flowcharts/pseudocode).

·         Coding – Writing the program in Python.

·         Testing – Checking program correctness with sample data.

·         Debugging – Identifying and removing errors.

 

What do you understand by Analysing the Problem?

Ans. Analysing the Problem means

·         Understand the problem statement clearly.

·         Identify the inputs (what data is given), the processing (what needs to be done), and the outputs (what result is expected).

Example: Find the sum of two numbers.

Input: two numbers.

Process: add them.

Output: their sum.

 

What do you understand by Developing an Algorithm?

Ans. Developing an Algorithm means

·         Write a step-by-step procedure to solve the problem.

·         Can be represented using pseudo code (English-like steps) or a flowchart (diagram).

Example (Algorithm for sum of two numbers):

Step 1: Start

Step 2: Read two numbers, A and B

Step 3: Compute SUM = A + B

Step 4: Display SUM

Step 5: Stop

 

What do you understand by Coding?

Ans. Coding means

  • Translate the algorithm into a program using a programming language (Python).

Python Example:

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
sum = a + b
print("Sum =", sum)
 
What do you understand by Testing?
Testing means
  • Run the program with sample inputs and check if the output is correct.

Example:

Input → a = 5, b = 3,

Output → Sum = 8

 

What do you understand by Debugging?

Ans. Debugging is the process of identifying, analyzing, and correcting errors (bugs) in a program so that it works as intended.

Types of Errors

·         Syntax Error → Wrong code structure (caught before execution).

·         Logical Error → Wrong output (hardest to detect).

·         Runtime Error → Occurs during execution (depends on input/operation).

 

What do you understand by Syntax Errors?

Ans. Syntax Errors means

Mistakes in the way the code is written, such as missing punctuation, incorrect indentation, or misspelled keywords, which prevent Python from understanding the code.

·         Incorrect Use of Punctuation: Missing or misplaced colons, parentheses, commas, or quotes that lead to syntax errors.

·         Indentation Errors: Improper indentation levels that violate Python’s rules for code blocks, causing errors.

·         Misspelled Keywords or Functions: Using incorrect spelling for Python keywords or built-in functions, leading to syntax errors.

·         Misplaced or Missing Statements: Placing statements in the wrong order or omitting necessary parts of the code structure.

·         Incorrect Use of Operators: Using operators incorrectly or in the wrong context, which can cause syntax errors.

·         Invalid Variable Names: Using variable names that start with numbers or contain special characters not allowed in Python identifiers.

·         Unclosed String Literals or Parentheses: Forgetting to close quotes or parentheses, which disrupts the code parsing.

Example:

# Missing colon in if statement

x = 5

if x > 0

    print("Positive")

Error: SyntaxError: expected ':'

 

What do you understand by Logical Errors?

Ans. Logical Errors mean

·         Incorrect Algorithm: Using the wrong approach or steps to solve a problem, leading to incorrect results.

·         Wrong Conditions: Mistakes in if, while, or for conditions that cause incorrect flow or decision-making.

·         Improper Loop Logic: Loops that run too many times, too few times, or not at all due to faulty conditions.

·         Data Handling Errors: Processing data incorrectly, such as mixing up data types or misusing data structures.

·         Incorrect Function Calls: Using functions with wrong arguments or expecting wrong outputs.

·         Misinterpretation of Data: Making wrong assumptions about data inputs or outputs, leading to faulty logic.

·         Boundary and Off-by-One Errors: Mistakes in indexing or loop limits that cause missing or extra iterations.

·         Flow Control Mistakes: Logic that causes code to behave unexpectedly, such as missing certain conditions or executing unintended code blocks.

Example:

# Program to find average of two numbers

a = 10

b = 20

average = a + b / 2   # Wrong logic (operator precedence)

print("Average =", average)

Output: 20.0 instead of correct average 15.0.

 

What do you understand by Runtime Errors?

Ans. Runtime Errors means

Errors that occur while the program is running. These usually happen due to

·         Division by Zero: Attempting to divide a number by zero, this is mathematically undefined and causes an error.

·         Null Reference Errors: Using an object or variable that has not been initialized or is set to null, leading to exceptions.

·         File Not Found: Trying to open or access a file that doesn't exist or the path is incorrect.

·         Type Errors: Performing operations on incompatible data types, such as adding a string and an integer.

·         Index Out of Range: Accessing an array or list element with an invalid index outside its valid range.

·         Memory Overflow/Leak: Excessive memory usage causing the program to crash or slow down significantly.

·         Invalid Input/Data: Receiving data that the program cannot process due to format or type issues.

·         Infinite Loop or Hang: Running a loop that never terminates, causing the program to become unresponsive.

Example:

a = 10

b = 0

print(a / b)   # Division by zero

Error: ZeroDivisionError: division by zero

 

What do you understand by Algorithm Representation?

Ans. When solving a problem, the algorithm can be represented in different ways to make it easier to understand and implement.

·         Flowchart: A flowchart is a graphical representation of an algorithm using standard symbols.

·         Pseudo code: Pseudo code is a way of writing an algorithm in simple English-like structured steps (not actual code). Helps bridge the gap between human thinking and coding.

·         Decomposition: Decomposition means breaking a complex problem into smaller sub-problems.

·         Each sub-problem can be solved individually, and then combined to solve the main problem.

 

What do you understand by Flowchart?

Ans. A flowchart is a graphical representation of an algorithm using standard symbols.

Symbols used:

Oval → Start/End

Parallelogram → Input/Output

Rectangle → Process/Calculation

Diamond → Decision/Condition

Example: Flowchart for finding the sum of two numbers

 

What do you understand by Pseudo code?

Ans. Pseudo code is a way of writing an algorithm in simple English-like structured steps (not actual code). Helps bridge the gap between human thinking and coding.

Example (Sum of two numbers):

Step 1: Start

Step 2: Read A, B

Step 3: SUM = A + B

Step 4: Display SUM

Step 5: Stop

 

What do you understand by Decomposition?

Ans. Decomposition means breaking a complex problem into smaller sub-problems. Each sub-problem can be solved individually, and then combined to solve the main problem.

Example: Making Tea (Problem)

Sub-problems:

Boil water

Add tea leaves

Add milk and sugar

Serve tea

 

Introduction to Python

Define the Python Language?

Ans. Python is a high-level, interpreted programming language known for its readability and ease of use. It supports interactive programming, allowing you to write and test code quickly. Python is also object-oriented, enabling the creation of reusable and modular code components.

 

What are the Features of Python? 

Ans. The Features of Python

·         Simple Syntax: Python's syntax is clear and concise, making it easy to learn and read.

·         Portable: Python code can run on different operating systems like Windows, Linux, and macOS without modification.

·         Large Libraries: Python offers extensive standard libraries and third-party modules for various tasks like data analysis, web development, machine learning, and more.

·         Dynamically Typed: You don't need to declare variable types explicitly; Python determines types at runtime, offering flexibility in coding.

 

What are the Execution Modes in Python?

Ans. The Execution Modes in Python are:

·         Interactive Mode – Run line by line in Python shell/IDLE.

·         Script Mode – Write a .py file and run it.

 

Define the Interactive Mode?

Ans. In Interactive Mode:

·         Run Python directly in the command line or Python shell/IDLE.

·         You can execute one line or command at a time, making it useful for testing and quick calculations.

Example:

>>> print("Hello, World!")

Hello, World!

 

Define Script Mode?

Ans. In Script Mode:

·         Write your Python code in a file with a .py extension (e.g., script.py).

·         Run the script by executing the file in the command line or using an IDE.

·         Suitable for larger programs and projects.

Example: Create a file hello.py with:

print("Hello from script mode!")

 

Define Character Set in Python.

Ans. In Python, a character set refers to the collection of characters that can be used in strings, regular expressions, or encoding schemes. Python strings are Unicode by default.

 

What is Unicode character set?

Ans. Python natively supports Unicode, which means it can handle a vast range of characters from different languages and symbols. This is essential for internationalization and processing multilingual text.

 

What do you understand by Case Sensitivity?

Ans. In Python, case sensitivity means that the language treats uppercase and lowercase letters as distinct and different characters. This applies to identifiers such as variable names, method names, class names, and keywords.

For example, Variable, variable, and VARIABLE are considered three different identifiers.

 

Define Python Tokens.

Ans. Tokens are the basic building blocks of Python code. When Python code is parsed, it is broken down into tokens which are then analyzed for execution.

·         Keywords: reserved words (if, else, for, while, etc.).

·         Identifiers: names for variables/functions (marks, student1).

·         Literals: fixed values (10, "Hello", 3.14).

·         Operators: +, -, *, /, //, %.

·         Punctuators: (), [], {}, :, ,, ;.

 

Define Keywords (Reserved Words)

Ans. Special words that are reserved by Python for syntax and cannot be used as identifiers (variable names, function names, etc.).

Examples:

if, else, elif, for, while, def, return, import, break, continue, pass, class, try, except, finally, with, lambda, True, False, None

Example

if x > 0:

    print("Positive")

 

Define Identifier in Python.

Ans. In Python, an Identifier is a name used to identify variables, functions, classes, modules, and other user-defined objects. It serves as a label that allows you to refer to these objects in your code.

 

What are the rules of naming an Identifier?

Ans. Rules of naming an Identifier in Python are:

·         Must start with a letter (a-z, A-Z) or an underscore (_).

·         Can contain letters, digits (0-9), and underscores (_) after the first character.

·         Cannot be a Python keyword (reserved words like if, else, while, etc.).

·         Case-sensitive, meaning Variable, variable, and VARIABLE are considered different identifiers.

Examples: marks, student1, total_score, _temp, myFunction

 

Define variable?

Ans. In Python, a variable is a name that references or points to a value stored in the computer's memory. Variables are used to store data that can be used and manipulated throughout a program.

 

What are the Key points about variables in Python?

Ans. Key points about variables in Python:

·         You do not need to declare a variable's type explicitly; Python determines it dynamically based on the assigned value.

·         Variable names must start with a letter (a-z, A-Z) or an underscore (_) and can contain letters, digits, and underscores.

·         Variable names are case-sensitive (myVar and myvar are different).

Example:

x = 10                                     # x is a variable holding an integer value

name = "Alice"                  # name is a variable holding a string

pi = 3.14                               # pi is a variable holding a float value

is_active = True                # is_active is a boolean variable

 

Define L-value and R-value.

·         L-value (Left-value): The location or storage in memory where data is stored. It appears on the left side of an assignment and refers to a variable or memory location.

·         R-value (Right-value): The actual data or value that is assigned to the variable. It appears on the right side of an assignment.

Example:

x = 10

x is the l-value (the variable's memory location).

10 is the r-value (the data being stored).

 

Define Dynamic initialization.

Ans. Dynamic initialization in Python refers to the process of assigning values to variables at runtime, often based on user input, calculations, or other runtime conditions. It means initializing variables with values that are determined during the execution of the program, rather than hardcoded at the time of writing the code.

Example:

name = input("Enter your name: ")   # value assigned at runtime based on user input

age = int(input("Enter your age: ")) # value assigned dynamically during execution

 

Define Comment in Python?

Ans. In Python, a comment is a piece of text in your code that is ignored by the interpreter and used to explain, annotate, or clarify the code for human readers. It’s a vital tool for writing readable and maintainable programs.

 

What are the different types of Comments in Python?

Ans. Types of Comments in Python

1. Single-Line Comment

Starts with a # symbol. Everything after # on that line is ignored.

# This is a single-line comment

x = 5  # Assign 5 to x

2. Multi-Line Comment (Docstring Style)

Python doesn’t have a true multi-line comment syntax, but you can use triple quotes (''' or """) to simulate them. These are often used for documentation.

'''

This is a multi-line comment.

Useful for longer explanations.

'''

print("Hello, world!")

 

Define Data types in Python.

Ans. In Python, every value has a data type which defines what kind of data it is and what operations can be performed on it.

·         Numbers

·         Boolean (bool)

·         Sequence Types

·         None

·         Mapping Type

 

What is Number Data type in Python?

Numbers Data Type

Python supports three types of numbers:

(a) Integer (int): Whole numbers (positive or negative) without decimals.

Example: x = 10, y = -25

(b) Floating Point (float): Numbers with decimal points.

Example: pi = 3.14, marks = 95.5

(c) Complex Numbers (complex): Written as a + bj where a is real part, b is imaginary part.

Example: z = 3 + 4j

Access real and imaginary parts:

z = 3 + 4j

print(z.real)   # 3.0

print(z.imag)   # 4.0

 

What is Boolean (bool) Data type in Python?

Ans. Boolean (bool) Data Type

·         Represents truth values: True (1) or False (0).

·         Used in conditions and logical operations.

Example:

a = 5

b = 10

print(a < b)   # True

print(a > b)   # False

 

What is Sequence Data type in Python?

Ans. A sequence is an ordered collection of elements.

String (str):

·         Sequence of characters enclosed in ' ' or " ".

·         Immutable (cannot be changed after creation).

Example:

s = "Python"

print(s[0])      # P

print(s[1:4])    # yth

(b) List (list):

·         Ordered, mutable collection.

·         Elements can be of different data types.

·         Enclosed in square brackets [ ].

Example:

fruits = ["apple", "banana", "cherry"]

fruits.append("mango")

print(fruits)   # ['apple', 'banana', 'cherry', 'mango']

(c) Tuple (tuple):

·         Ordered, immutable collection.

·         Enclosed in parentheses ( ).

Example:

coordinates = (10, 20, 30)

print(coordinates[1])   # 20

 

What is None Data type in Python?

None Data type

Represents the absence of value or “nothing”.

Example:

x = None

print(x)     # None

Often used as a default value for variables or function return types.

 

What is Mapping Data type in Python?

Mapping Type: Dictionary (dict)

·         Collection of key–value pairs.

·         Keys are unique and immutable (string, number, tuple).

·         Values can be any data type.

·         Enclosed in curly braces { }.

Example:

student = {"name": "Rahul", "age": 16, "marks": 85}

print(student["name"])   # Rahul

student["marks"] = 90    # modify value

print(student)

 

Define Mutable Data Types in Python

 

Mutable Data Types : Objects whose values can be modified after creation without changing their identity (memory address).

Examples: list, dict, set

Example (List – Mutable):

fruits = ["apple", "banana", "cherry"]

print(fruits)            # ['apple', 'banana', 'cherry']

fruits[1] = "mango"      # modifying list

print(fruits)            # ['apple', 'mango', 'cherry']

Here, the list content changes, but the list itself remains the same object in memory.

 

Define Immutable Data Types in Python

Immutable Data Types: Objects whose values cannot be modified after creation. Any modification creates a new object.

Examples: int, float, str, tuple, bool

Example (String – Immutable):

name = "Python"

print(name)              # Python

# Trying to change one character

# name[0] = "J"   (Error: 'str' object does not support item assignment)

# Instead, a new string is created

name = "Jython"

print(name)              # Jython

Here, changing the string creates a new object instead of modifying the old one.

 

Define id() and type() two fundamental built-in functions in Python

id() — Identity of an Object: Returns the unique identifier (memory address) of an object during its lifetime.

id(object)

Example:

x = 42

print(id(x))  # e.g., 9788736

Even if two variables have the same value, their id() may differ if they refer to different objects — unless Python optimizes and reuses immutable objects.

type() — Type of an Object: Returns the class/type of the object. Useful for checking data types dynamically.

type(object)

Example:

x = "Hello"

print(type(x))  # <class 'str'>

y = [1, 2, 3]

print(type(y))  # <class 'list'>

 

Define Literals in Python.

Ans. In Python, Literals are fixed values that are directly represented in the source code. They are the actual data values assigned to variables or used in expressions.

Examples of Literals in Python:

x = 42             # Integer literal

pi = 3.14159       # Floating-point literal

name = "Alice"     # String literal

is_valid = True    # Boolean literal

nothing = None     # None literal

complex_num = 2 + 3j  # Complex number literal

 

What are the Types of Literals in Python?

Ans. Types of Literals in Python:

Numeric Literals

·         Integer literals: Whole numbers without a decimal point.

Example: 10, -3, 0

·         Floating-point literals: Numbers with a decimal point.

Example: 3.14, -0.001, 2.0

·         Complex literals: Numbers with imaginary parts, denoted by j or J.

Example: 2+3j, -5j

String Literals

Enclosed in single ' ' or double " " quotes.

Example: 'Hello', "Python", '123'

Multi-line strings can be written using triple quotes (''' ''' or """ """).

Boolean Literals

Represent truth values.

True and False (Note: They are case-sensitive and start with uppercase).

Special Literal

None — Represents the absence of a value or null.

 

Define Operators in Python

Ans. Operators are symbols that perform operations on variables and values, enabling you to perform calculations, comparisons, and logical operations.

·         Arithmetic Operators: + (addition), - (subtraction), * (multiplication), / (division), // (floor division), % (modulus), ** (exponentiation)

·         Comparison Operators: == (equal), != (not equal), > (greater than), < (less than), >= (greater or equal), <= (less or equal)

·         Logical Operators: and, or, not

·         Assignment Operators: =, +=, -=, *=, /=, etc.

·         Bitwise Operators: &, |, ^, ~, <<, >>

·         Membership Operators: in, not in

·         Identity Operators: is, is not

 

Define Arithmetic Operators in Python

Arithmetic Operators: Perform basic mathematical operations:

+ : Addition

- : Subtraction

* : Multiplication

/ : Division (float division)

// : Floor division (quotient without remainder)

% : Modulus (remainder)

** : Exponentiation (power)

Examples:

a = 10

b = 3

print(a + b)  # 13

print(a - b)  # 7

print(a * b)  # 30

print(a / b)  # 3.333...

print(a // b) # 3

print(a % b)  # 1

print(a ** b) # 1000

 

Define Comparison (Relational) Operators

Comparison (Relational) Operators: Compare values:

== : Equal to

!= : Not equal to

> : Greater than

< : Less than

>= : Greater than or equal to

<= : Less than or equal to

Example:

x = 5

print(x == 5)  # True

print(x != 3)  # True

print(x > 2)   # True

 

Define Logical Operators

Logical Operators:  Combine multiple conditions:

and : True if both conditions are True

or : True if at least one condition is True

not : Negates the condition

Example:

a = True

b = False

print(a and b)  # False

print(a or b)   # True

print(not a)    # False

 

Define Assignment Operators.

Assignment Operators: Assign values to variables:

= : Assign

+= : Add and assign

-= : Subtract and assign

*= : Multiply and assign

/= : Divide and assign

Example:

x = 5

x += 3  # x = x + 3

print(x)  # 8

 

Define Bitwise Operators.

Bitwise Operators: Perform operations at the binary level:

& : AND

| : OR

^ : XOR

~ : NOT

<< : Left shift

>> : Right shift

Example:

a = 5  # 0101

b = 3  # 0011

print(a & b)  # 1 (0001)

print(a | b)  # 7 (0111)

 

Define Membership Operators.

Membership Operators: Check if a value is part of a sequence (like list, string, etc.):

in : True if value exists in sequence

not in : True if value does not exist

Example:

list_items = [1, 2, 3]

print(2 in list_items)     # True

print(4 not in list_items) # True

 

Define Identity Operators.

Identity Operators: Compare whether two variables point to the same object:

is : True if both refer to the same object

is not : True if they refer to different objects

Example:

a = [1, 2, 3]

b = a

c = [1, 2, 3]

print(a is b)  # True

print(a is c)  # False

 

Define Separators or Punctuators (Delimiters).

Punctuators (Delimiters): Symbols used to structure code.

Examples:

Parentheses: ()

Brackets: []

Braces: {}

Colon: : (used in function definitions, slices, dictionaries, etc.)

Comma: , (to separate items)

Semicolon: ; (can be used to separate multiple statements on the same line, but discouraged)

Dot: . (access attributes or methods)

Ellipsis: ... (used in advanced scenarios)

 

Define Precedence of operators in Python

Precedence of Operators in Python

Precedence of operators refers to the order in which operators are evaluated in an expression. When an expression contains multiple operators, Python follows specific rules to decide which part to evaluate first.

 

Operator Precedence Table (from highest to lowest)

Precedence Level            Operators           Description

1 (Highest)                          ()                             Parentheses (used for grouping)

2                                              **                           Exponentiation

3                                              +x, -x, ~x              Unary plus, minus, bitwise NOT

4                                              *, /, //, %             Multiplication, division, floor division, modulo

5                                              +, -                          Addition, subtraction

6                                              <<, >>                    Bitwise shift operators

7                                              &                             Bitwise AND

8                                              ^                              Bitwise XOR

9                                              ==, !=, >, <, >=, <=, is, is not, in, not in      Comparison and identity operators

10                                           not                         Logical NOT

11                                           and                        Logical AND

12                                           or                            Logical OR

13 (Lowest)                        =, +=, -=, *=, etc.               Assignment operators

 

Example:

result = 10 + 2 * 3

print(result)

Here, * has higher precedence than +, so the multiplication is performed first:

2 * 3 = 6

10 + 6 = 16

 

Using Parentheses to Change Precedence:

result = (10 + 2) * 3

print(result)  # Outputs 36

Parentheses override the default precedence.

 

Define Input and Output Statements in Python

In Python, input and output statements are used to interact with the user or display information.

Input Statement

Used to take data from the user during program execution.

Syntax:

input("Prompt message")

Example:

name = input("Enter your name: ")

print("Hello,", name)

 

input() always returns a string. You may need to convert it using int(), float(), etc., if numeric input is required.

Example with conversion:

age = int(input("Enter your age: "))

print("You are", age, "years old.")

 

Output Statement

Used to display data or results to the user.

Syntax:

print(data1, data2, ..., sep=' ', end='\n')

Example:

print("Welcome to Python!")

Example with variables:

name = "Alice"

print("Hello", name)

 

What is the Use of print statement with sep and end in Python?

The print() function in Python has optional parameters like sep and end that help control the formatting of the output.

1. sep – Separator

Used to define the separator between multiple values in a print statement.

Default: ' ' (a space)

Syntax:

print(value1, value2, ..., sep='separator')

Example:

print("Python", "is", "fun", sep="-")

Output:

Python-is-fun

 

2. end – End Character

Used to define what is printed at the end of the print statement.

Default: '\n' (newline)

Syntax:

print(value1, value2, ..., end='ending')

Example:

print("Hello", end=", ")

print("world!")

Output:

Hello, world!

 

Combined Example with sep and end:

print("2025", "09", "30", sep="-", end=" <-- Today's Date\n")

Output:

2025-09-30 <-- Today's Date

 

What is the Escape Characters in Strings in Python?

Backslash is used to introduce escape sequences — special characters that can’t be typed directly or need special formatting.

Common Escape Sequences:

Escape  Meaning

\n           Newline

\t            Tab

\\            Backslash (\)

\'             Single quote

\"            Double quote

\r            Carriage return

\b           Backspace

\f            Form feed

\a            Bell (alert)

\v            Vertical tab

Example:

print("Hello\nWorld")  # Prints on two lines

print("She said: \"Hi!\"")  # Escaped quotes

 

What do you understand by eval() in Python?

Think of it like a calculator that understands Python!

The eval() function is used to run a Python expression written inside a string and get the answer.

If you give eval() a math expression written in quotes, it will solve it for you.

Basic Example:

print(eval("2 + 3"))

Output:

5

Why 5? Because eval("2 + 3") tells Python to solve "2 + 3" like math.

Another Example with a Variable:

x = 10

print(eval("x + 5"))

Output:

15

 

What do you understand by Expressions in Python?

An expression is a combination of variables, constants, operators, and functions that are evaluated to produce a value.

Example:

a = 10

b = 20

c = a + b  # Expression: a + b

print(c)   # Output: 30

 

How does Evaluation of an Expression take place?

Evaluation involves computing the value of an expression by following the rules of operator precedence, associativity, and data types. Python interprets and processes the components of an expression step-by-step to produce a final result.

Example:

x = 10

y = 5

z = 2

# Expression involving multiple operators

result = x + y * z / (x - y)

# Step-by-step:

# y * z → 5 * 2 = 10

# x - y → 10 - 5 = 5

# 10 / 5 → 2.0

# 10 + 2.0 → 12.0

print(result)  # Output: 12.0

 

What do you understand by Statement in Python?

A statement is a line of code that performs an action. Programs are made up of statements.

Example:

x = 5  # Assignment statement

print("Hello, World!")  # Print statement

if x > 0:

    print("Positive number")  # Conditional statement

 

What do you understand by Type Conversion ?

Type conversion involves converting data from one data type to another. This can be:

Implicit Conversion (Type Coercion): Automatically done by the compiler/interpreter.

Explicit Conversion (Type Casting): Manually done by the programmer.

 

What do you understand by Implicit Type Conversion (Type Coercion)

Python automatically converts one data type to another when needed during an operation. This is done without programmer intervention.

When it happens: 

When an operation involves different data types, Python converts the smaller or less precise type to the larger or more precise type.

Example:

Adding an integer and a float:

x = 5       # int

y = 2.5     # float

result = x + y  # Python converts x to float automatically

print(result)   # Output: 7.5

Explanation: 

x (int) is implicitly converted to float.

The result is a float.

 

What do you understand by Explicit Type Conversion (Type Casting)

The programmer explicitly converts data from one type to another using built-in functions.

Common functions:

int(): Converts to integer

float(): Converts to float

str(): Converts to string

bool(): Converts to boolean

 

How can we Convert string to integer?

# Convert string to integer

num_str = "123"

num_int = int(num_str)

print(num_int + 10)   # Output: 133

 

How can we Convert float to integer?

# Convert float to integer

pi = 3.14159

pi_int = int(pi)

print(pi_int)         # Output: 3

 

How can we Convert integer to string?

# Convert integer to string

num = 50

str_num = str(num)

print("The number is " + str_num)   # Output: The number is 50

 

How can we Convert string representing float to float?

# Convert string representing float to float

float_str = "3.14159"

float_num = float(float_str)

print(float_num)      # Output: 3.14159

 

What do you understand by Flow of Control?

Flow of control (or control flow) refers to the order in which individual instructions, statements, or blocks of code are executed in a program. It determines how the program moves from one statement to another based on conditions, loops, or normal sequence.

By default, statements in a program are executed from top to bottom in the order they appear.

However, real-world problems often need decision-making (if/else), repetition (loops), or skipping code.  Control structures help manage this execution order.

What is the Use of Indentation in Python?

Indentation means giving spaces or tabs at the beginning of a line to represent blocks of code.

In Python, indentation is mandatory to define the scope of statements inside conditions, loops, and functions.

Example:

if age >= 18:

    print("You can vote")   # indented, belongs to if

print("End of program")     # not indented, outside if

 

What do you understand by Sequential Flow Statement?

·         The simplest type of flow.

·         Statements execute one after another in the order they are written.

Example:

a = 5

b = 10

c = a + b

print(c)   # Executes in sequence

 

What do you understand by Conditional Flow Statement?

·         Used for decision-making.

·         The program chooses which block of code to execute based on a condition (True/False).

·         Controlled using if, if-else, if-elif-else.

Example:

num = 7

if num % 2 == 0:

    print("Even")

else:

    print("Odd")

 

What do you understand What do you understand by  Iterative Flow Statement?

Used for repetition of a block of code until a condition is met.

Implemented with loops (while, for).

Example:

for i in range(1, 6):

    print(i)    # Prints 1 to 5

 

What do you understand Conditional Statements in Python?

Conditional statements allow a program to make decisions and execute specific blocks of code depending on whether a condition is True or False.

In Python, conditions are expressed using relational operators (==, !=, >, <, >=, <=) and logical operators (and, or, not).

 

Define if Statement

·         The simplest conditional statement.

·         Executes a block of code only if the condition is True.

Syntax:

if condition:

    statement(s)

Example:

age = 20

if age >= 18:

    print("You are eligible to vote.")

Output:

You are eligible to vote.

 

Define if-else Statement

·         Provides an alternative path.

·         If the condition is True, one block executes; otherwise, the else block executes.

Syntax:

if condition:

    statement(s)   # executes if True

else:

    statement(s)   # executes if False

Example:

num = 7

if num % 2 == 0:

    print("Even number")

else:

    print("Odd number")

Output:

Odd number

 

Define if-elif-else Statement

·         Used when there are multiple conditions to test.

·         Python checks conditions from top to bottom:

·         First if is checked.

·         If false, next elif is checked.

·         If none are true, the else block executes (optional).

Syntax:

if condition1:

    statement(s)

elif condition2:

    statement(s)

elif condition3:

    statement(s)

else:

    statement(s)

Example:

marks = 76

if marks >= 90:

    print("Grade A")

elif marks >= 75:

    print("Grade B")

elif marks >= 50:

    print("Grade C")

else:

    print("Fail")

Output:

Grade B

 

Define Iterative Statements in Python?

Iteration = repeating execution of code until a condition is met.

Python supports loops with for and while. They can be controlled using break, continue, and else.

 

Define Flow of Loops

for loop:

Start → Initialize variable → Check condition → If True → Execute body → Update variable → Repeat → If False → Exit

while loop:

Start → Check condition → If True → Execute body → Update → Repeat → If False → Exit

 

Define for Loop

Used when we know the number of iterations in advance or when iterating over a sequence (string, list, tuple, dictionary, etc.).

Syntax:

for variable in sequence:

    statement(s)

Example:

for i in [10, 20, 30]:

    print(i)

Output:

10

20

30

 

Define range() Function

Generates a sequence of numbers, commonly used with for.

Different Forms of  Range Command:

range(stop) → 0 to stop-1

range(start, stop) → start to stop-1

range(start, stop, step) → increments by step

Example:

for i in range(1, 10, 3):

    print(i)

Output:

1

4

7

 

Define while Loop

Used when the number of iterations is unknown in advance.

Runs until the condition becomes False.

Syntax:

while condition:

    statement(s)

Example:

n = 1

while n <= 5:

    print(n)

    n += 1

Output:

1

2

3

4

5

 

Define the jump statement break or define break statement.

Immediately exits the loop, skipping remaining iterations.

Example:

for i in range(1, 6):

    if i == 3:

        break

    print(i)

Output:

1

2

 

Define the jump statement continue or define continue statement.

Skips the current iteration and moves to the next.

Example:

for i in range(1, 6):

    if i == 3:

        continue

    print(i)

Output:

1

2

4

5

 

Define Nested Loops

A loop inside another loop.

Example:

for i in range(1, 4):

    for j in range(1, 4):

        print(i, j)

Output:

1 1

1 2

1 3

2 1

2 2

2 3

3 1

3 2

3 3

 

Define else with Loops

Python allows an else block with both for and while loops.

The else block executes only if the loop completes normally (without break).

Example with for:

for i in range(5):

    print(i)

else:

    print("Loop finished successfully")

Output:

0

1

2

3

4

Loop finished successfully

Example with break:

for i in range(5):

    if i == 3:

        break

    print(i)

else:

    print("Loop finished successfully")

Output:

0

1

2

Here, the else block did not run because the loop was terminated using break.

Example with while:

x = 1

while x <= 3:

    print(x)

    x += 1

else:

    print("No more numbers")

Output:

1

2

3

No more numbers

 

Strings in Python

Define String in Python

A string is a sequence of characters enclosed in single quotes (' '), double quotes (" "), or triple quotes (''' ''' or """ """).

Strings are immutable (cannot be changed after creation).

Examples:

s1 = 'Hello'

s2 = "World"

s3 = '''This is

a multiline string'''

 

What are the String Operations possible in Python?

A string is a sequence of characters enclosed in single ('), double (") or triple quotes (''' / """).

Python provides many operations to manipulate strings.

Here we explain Concatenation, Repetition, Membership, and Slicing in detail.

String Operations in Python

(a) Concatenation (+)

Definition:

·         Concatenation means joining two or more strings into one.

·         In Python, the + operator is used for concatenation.

Example:

a = "Hello"

b = "World"

print(a + " " + b)

Output:

Hello World

Explanation:

Here "Hello" and "World" are joined with a space " " in between.

 

(b) Repetition (*)

Definition:

·         Repetition means repeating the same string multiple times.

·         In Python, the * operator is used with a string and an integer.

Example:

print("Hi! " * 3)

Output:

Hi! Hi! Hi!

Explanation:

"Hi! " is repeated 3 times.

 

(c) Membership Operators (in, not in)

Definition:

Membership operators check whether a substring exists inside a string.

in → returns True if substring is found.

not in → returns True if substring is not found.

Example:

s = "Python"

print("Py" in s)        # True

print("Java" not in s)  # True

Output:

True

True

Explanation:

"Py" is present in "Python", but "Java" is not.

 

(d) Slicing

Definition:

·         Slicing means extracting a part (substring) of a string using index positions.

Syntax:

string[start : stop : step]

start → index where slicing begins (default = 0)

stop → index where slicing ends (excluded)

step → interval between characters (default = 1)

Example:

s = "Programming"

print(s[0:6])     # Progra

print(s[:5])      # Progr

print(s[3:])      # gramming

print(s[::-1])    # gnimmargorP (reversed string)

Output:

Progra

Progr

gramming

gnimmargorP

Explanation:

s[0:6] → characters from index 0 to 5 → "Progra"

s[:5] → from start to index 4 → "Progr"

s[3:] → from index 3 to end → "gramming"

s[::-1] → reverses string (step = -1).

 

What do you understand by traversing a String using Loops?

Definition

·         Traversing a string means accessing each character of the string one by one.

·         Since a string is a sequence of characters, we can use loops (for or while) to process every character.

·         This is useful for tasks like counting vowels, reversing a string, checking characters, etc.

1. Traversing using for Loop

The for loop directly iterates over the characters of a string.

Each character is accessed one by one.

Example:

for ch in "Python":

    print(ch)

Output:

P

y

t

h

o

n

Explanation:

Here, ch takes each character of the string "Python" one by one.

2. Traversing using while Loop

The while loop uses an index variable to access characters by position.

We use len(string) to get the total number of characters.

Example:

s = "Hello"

i = 0

while i < len(s):

    print(s[i])

    i += 1

Output:

H

e

l

l

o

Explanation:

·         Here, i starts at 0 and goes up to len(s)-1.

·         s[i] accesses each character using indexing.

 

Built-in Functions / Methods

General Functions

Define len() Function

The len() function in Python is a built-in function used to determine the number of items in an object. When applied to a string, it returns the number of characters in that string, including letters, digits, spaces, and special characters.

Syntax:

len(s)

- s: The object whose length you want to find. It can be a string, list, tuple, dictionary, set, etc.

- Returns: An integer representing the number of elements in the object.

Example with a String

print(len("Python"))

Explanation:

- "Python" is a string with 6 characters: 'P', 'y', 't', 'h', 'o', 'n'

- So, len("Python") returns 6

Output:

6

String with spaces

print(len("Hello World"))

Explanation:

- Includes the space between "Hello" and "World"

- Output: 11

Empty string

print(len(""))

Explanation:

- No characters at all

- Output: 0

String with special characters

print(len("Hi! @2025"))

Explanation:

- Characters: H, i, !,  , @, 2, 0, 2, 5

- Output: 9

 

Case Conversion

Define capitalize()

The capitalize() method returns a copy of the string with the first character converted to uppercase and the rest converted to lowercase.

Syntax:

string.capitalize()

Example:

print("python".capitalize())

Output:

Python

Explanation:

- "python" becomes "Python": the first letter 'p' is capitalized, and the rest are made lowercase.

 

Define title()

The title() method returns a string where the first letter of each word is capitalized and the rest are lowercase.

Syntax:

string.title()

Example:

print("welcome to python".title())

Output:

Welcome To Python

Explanation:

- Each word in the string is treated separately.

- 'welcome', 'to', and 'python' become 'Welcome', 'To', and 'Python'.

 

Define lower()

The lower() method converts all characters in a string to lowercase.

Syntax:

string.lower()

Example:

print("PYTHON".lower())

Output:

python

Explanation:

- All uppercase letters ('P', 'Y', 'T', 'H', 'O', 'N') are converted to lowercase.

 

Define upper()

The upper() method converts all characters in a string to uppercase.

Syntax:

string.upper()

Example:

print("python".upper())

Output:

PYTHON

Explanation:

- All lowercase letters are converted to uppercase.

 

Searching and Counting

Define count(x)

Returns the number of times a specified substring x appears in the string.

Syntax:

string.count(substring)

Example:

print("Bhawani".count("a"))

Output:

2

Explanation:

- The letter 'a' appears two times in "Bhawani".

 

Define find(x)

Returns the index of the first occurrence of the substring x. If not found, it returns -1.

Syntax:

string.find(substring)

Example:

print("banana".find("na"))

Output:

2

Explanation:

- "na" first appears starting at index 2 in "banana".

 

Define index(x)

Returns the index of the first occurrence of the substring x. If not found, it raises an error (ValueError).

Syntax:

string.index(substring)

Example:

print("Bhawani".index("a"))

Output:

2

Explanation:

- Same as find(), but if "a" were not found, this would raise an error (ValueError).

 

Define startswith(x)

Checks if the string starts with the specified substring x. Returns True or False.

Syntax:

string.startswith(substring)

Example:

print("Python".startswith("Py"))

Output:

True

Explanation:

- "Python" starts with "Py", so the result is True.

 

Define endswith(x)

Checks if the string ends with the specified substring x. Returns True or False.

Syntax:

string.endswith(substring)

Example:

print("Python".endswith("on"))

Output:

True

Explanation:

- "Python" ends with "on", so the result is True.

 

Checking String Types

Define isalnum()

Returns True if all characters in the string are alphanumeric (letters and numbers only). No spaces or special characters allowed.

Syntax:

string.isalnum()

Example:

print("Python3".isalnum())

Output:

True

Explanation:

- "Python3" contains only letters and digits.

- If the string had a space or symbol (e.g., "Python 3" or "Python!"), it would return False.

 

Define isalpha()

Returns True if all characters in the string are alphabetic (A–Z or a–z). No digits, spaces, or symbols allowed.

Syntax:

string.isalpha()

Example:

print("Python".isalpha())

Output:

True

Explanation:

- "Python" contains only letters.

- "Python3" would return False because of the digit.

 

Define isdigit()

Returns True if all characters in the string are digits (0–9).

Syntax:

string.isdigit()

Example:

print("12345".isdigit())

Output:

True

Explanation:

- "12345" is all digits.

- "123a" or "12 34" would return False.

 

Define islower()

Returns True if all alphabetic characters in the string are lowercase.

Syntax:

string.islower()

Example:

print("python".islower())

Output:

True

Explanation:

- All letters in "python" are lowercase.

- "Python" would return False because of the capital 'P'.

 

Define isupper()

Returns True if all alphabetic characters in the string are uppercase.

Syntax:

string.isupper()

Example:

print("PYTHON".isupper())

Output:

True

Explanation:

- All letters in "PYTHON" are uppercase.

- "Python" would return False.

 

Define isspace()

Returns True if all characters in the string are whitespace (spaces, tabs, newlines).

Syntax:

string.isspace()

Example:

print("   ".isspace())

Output:

True

Explanation:

- The string contains only spaces.

- " a " or " " with any non-space character would return False.

 

Removing Spaces

Whitespace Removal Methods

Define lstrip()

Removes all leading (left-side) whitespace characters from a string.

Example:

text = "   hello"

print(text.lstrip())  # Output: "hello"

Explanation:

The spaces before "hello" are removed, but any trailing spaces remain.

 

Define rstrip()

Removes all trailing (right-side) whitespace characters from a string.

Example:

text = "hello   "

print(text.rstrip())  # Output: "hello"

Explanation:

The spaces after "hello" are removed, but any leading spaces remain.

 

Define strip()

Removes both leading and trailing whitespace characters from a string.

Example:

text = "   hello   "

print(text.strip())  # Output: "hello"

Explanation:

Both the spaces before and after "hello" are removed.

 

Replacing Substrings

Define replace(old, new)

Returns a copy of the string with all occurrences of the substring old replaced by new.

Example:

text = "I like Java"

print(text.replace("Java", "Python"))  # Output: "I like Python"

Explanation:

The word "Java" is replaced with "Python".

 

Joining Strings

Define join(iterable)

Joins elements of an iterable (like a list or tuple) into a single string, using the string as a separator.

Example:

words = ["I", "love", "Python"]

print(" ".join(words))  # Output: "I love Python"

Explanation:

The list elements are joined with a space between them.

 

Splitting Strings

Define partition(sep)

Splits the string into a tuple of three parts: the part before the separator, the separator itself, and the part after.

Example:

text = "apple-mango"

print(text.partition("-"))  # Output: ('apple', '-', 'mango')

Explanation:

The string is split at the first occurrence of -.

 

Define split(sep)

Splits the string into a list of substrings using the specified separator.

Example:

text = "a,b,c"

print(text.split(","))  # Output: ['a', 'b', 'c']

Explanation:

The string is split at each comma.

 

Lists in Python

What Is a List?

A list in Python is:

·         An ordered collection of items (the order in which items are inserted is preserved).

·         Mutable, meaning you can change, add, or remove elements after the list is created.

·         Defined using square brackets [].

·         Can contain elements of different data types — integers, strings, floats, booleans, even other lists.

Syntax

list_name = [item1, item2, item3, ...]

Examples

1. List of Strings

fruits = ["apple", "banana", "cherry"]

print(fruits)  # Output: ['apple', 'banana', 'cherry']

2. List of Integers

numbers = [10, 20, 30, 40]

print(numbers)  # Output: [10, 20, 30, 40]

3. Mixed Data Types

mixed = [1, "hello", 3.5, True]

print(mixed)  # Output: [1, 'hello', 3.5, True]

4. Nested List (List inside a list)

nested = [1, [2, 3], "Python"]

print(nested)  # Output: [1, [2, 3], 'Python']

 

 

 

 

What Is Indexing?

Indexing is the process of accessing individual elements in a list using their position (index). Python lists are ordered, so each element has a unique index.

 

What are the Types of Indexing used in List?

1. Positive Indexing

- Starts from 0 for the first element.

- Increases by 1 for each subsequent element.

Example:

colors = ["red", "green", "blue"]

print(colors[0])  # Output: red

print(colors[1])  # Output: green

print(colors[2])  # Output: blue

2. Negative Indexing

- Starts from -1 for the last element.

- Moves backward: -2 is the second-last, -3 is the third-last, and so on.

Example:

colors = ["red", "green", "blue"]

print(colors[-1])  # Output: blue

print(colors[-2])  # Output: green

print(colors[-3])  # Output: red

 

Why to Use Indexing in List?

- To retrieve specific items from a list.

- To modify elements at a particular position.

- To iterate through a list using loops.

 

What are the Indexing Rules used in list.

- Index must be within the range of the list.

- Accessing an index outside the range will raise an IndexError.

Example:

colors = ["red", "green", "blue"]

print(colors[3])  #  IndexError: list index out of range

 

List Operations

(a) Concatenation (+)

Combines two or more lists into a single list.

Example:

a = [1, 2]

b = [3, 4]

print(a + b)  # Output: [1, 2, 3, 4]

Explanation:

The + operator merges the contents of both lists into one.

 

(b) Repetition (*)

Repeats the elements of a list a specified number of times.

Example:

print([1, 2] * 3)  # Output: [1, 2, 1, 2, 1, 2]

Explanation:

The list [1, 2] is repeated 3 times.

 

(c) Membership (in, not in)

Checks whether an element exists in a list.

Example:

fruits = ["apple", "banana"]

print("apple" in fruits)        # Output: True

print("mango" not in fruits)    # Output: True

Explanation:

- "apple" in fruits returns True because "apple" is in the list.

- "mango" not in fruits returns True because "mango" is not in the list.

 

(d) Slicing

Extracts a portion of the list using a range of indices.

Syntax: list[start:stop:step]

Examples:

nums = [10, 20, 30, 40, 50]

print(nums[1:4])    # Output: [20, 30, 40]

print(nums[:3])     # Output: [10, 20, 30]

print(nums[::2])    # Output: [10, 30, 50]

Explanation:

- nums[1:4]: Gets elements from index 1 to 3 (excluding index 4).

- nums[:3]: Gets elements from start to index 2.

- nums[::2]: Gets every second element starting from index 0.4. Traversing a List using Loops

 

How to use for Loop in Python List

A for loop is used to iterate over a sequence (like a list, tuple, string, or range). It automatically handles the loop counter and stops when the sequence ends.

Example:

animals = ["cat", "dog", "lion"]

for a in animals:

    print(a)

Explanation:

- animals is a list containing three strings.

- for a in animals: means: for each element in the list animals, assign it to variable a.

- print(a) prints each animal name.

- The loop runs three times, once for each item in the list.

Output:

cat

dog

lion

 

How to use while Loop in Python List

A while loop runs as long as a condition is true. You must manually manage the loop counter and ensure the condition eventually becomes false to avoid infinite loops.

Example:

animals = ["cat", "dog", "lion"]

i = 0

while i < len(animals):

    print(animals[i])

    i += 1

Explanation:

- i = 0 initializes the loop counter.

- while i < len(animals): checks if i is less than the number of items in the list.

- print(animals[i]) prints the item at index i.

- i += 1 increases the counter by 1 after each iteration.

- The loop runs three times, just like the for loop.

Output:

cat

dog

lion

 

List Methods

These are specific to list objects and modify the list directly.

1. append(x)

Adds element x to the end of the list.

Example:

animals = ["cat", "dog"]

animals.append("lion")

print(animals)  # Output: ['cat', 'dog', 'lion']

 

2. extend(seq)

Adds all elements from the sequence seq to the end of the list.

Example:

animals = ["cat"]

animals.extend(["dog", "lion"])

print(animals)  # Output: ['cat', 'dog', 'lion']

 

3. insert(i, x)

Inserts element x at index i.

Example:

animals = ["cat", "lion"]

animals.insert(1, "dog")

print(animals)  # Output: ['cat', 'dog', 'lion']

 

4. count(x)

Returns the number of times x appears in the list.

Example:

animals = ["cat", "dog", "cat"]

print(animals.count("cat"))  # Output: 2

 

5. index(x)

Returns the index of the first occurrence of x.

Example:

animals = ["cat", "dog", "lion"]

print(animals.index("dog"))  # Output: 1

 

6. remove(x)

Removes the first occurrence of x.

Example:

animals = ["cat", "dog", "cat"]

animals.remove("cat")

print(animals)  # Output: ['dog', 'cat']

 

7. pop(i)

Removes and returns the element at index i. If i is not provided, removes the last item.

Example:

animals = ["cat", "dog", "lion"]

print(animals.pop(1))  # Output: 'dog'

print(animals)         # Output: ['cat', 'lion']

 

8. reverse()

Reverses the list in place.

Example:

animals = ["cat", "dog", "lion"]

animals.reverse()

print(animals)  # Output: ['lion', 'dog', 'cat']

 

9. sort()

Sorts the list in ascending order in place.

Example:

numbers = [3, 1, 4, 2]

numbers.sort()

print(numbers)  # Output: [1, 2, 3, 4]

 

Tuples in Python

A tuple is an ordered, immutable collection of elements. That means:

- The order of elements is preserved.

- Once created, the contents of a tuple cannot be changed (no adding, removing, or modifying elements).

Syntax:

Tuples are defined using parentheses ( ), unlike lists which use square brackets [ ].

Examples:

t1 = (10, 20, 30)                     # Tuple of integers

t2 = ("apple", "banana", "cherry")   # Tuple of strings

t3 = (1, "hello", 3.5, True)         # Mixed data types

 

Single-element Tuple:

To define a tuple with one element, you must include a trailing comma:

t = (5,)      # This is a tuple

not_a_tuple = (5)   # This is just an integer

 

Indexing in Tuples

Tuples support indexing, just like lists. You can access elements using positive or negative indices.

1. Positive Indexing:

Starts from 0 and goes forward.

colors = ("red", "green", "blue")

print(colors[0])   # Output: red

print(colors[1])   # Output: green

print(colors[2])   # Output: blue

2. Negative Indexing:

Starts from -1 (last element) and goes backward.

colors = ("red", "green", "blue")

print(colors[-1])  # Output: blue

print(colors[-2])  # Output: green

print(colors[-3])  # Output: red

 

Tuple Operations in Python

 

(a) Concatenation (+)

Combines two or more tuples into one. The result is a new tuple containing elements from all operands.

Example:

a = (1, 2)

b = (3, 4)

print(a + b)  # Output: (1, 2, 3, 4)

Explanation:

- a + b creates a new tuple by joining a and b.

- Original tuples remain unchanged.

 

(b) Repetition (*)

Repeats the elements of a tuple a specified number of times.

Example:

print((1, 2) * 3)  # Output: (1, 2, 1, 2, 1, 2)

Explanation:

- (1, 2) * 3 repeats the tuple three times.

- Useful for initializing repeated patterns.

 

(c) Membership (in, not in)

Checks whether an element exists in a tuple.

Example:

fruits = ("apple", "banana")

print("apple" in fruits)       # Output: True

print("mango" not in fruits)   # Output: True

Explanation:

- "apple" in fruits returns True because "apple" is present.

- "mango" not in fruits returns True because "mango" is absent.

 

(d) Slicing

Extracts a portion of the tuple using index ranges. Syntax: tuple[start:stop:step]

Examples:

nums = (10, 20, 30, 40, 50)

print(nums[1:4])    # Output: (20, 30, 40)

print(nums[:3])     # Output: (10, 20, 30)

print(nums[::-1])   # Output: (50, 40, 30, 20, 10)

Explanation:

- nums[1:4] → elements from index 1 to 3 (excluding 4).

- nums[:3] → first three elements.

- nums[::-1] → reverses the tuple using negative step.

 

Built-in Functions for Tuples

These functions work on tuples and other sequences like lists and strings.

1. len(t)

Returns the number of elements in the tuple.

Example:

t = (10, 20, 30)

print(len(t))  # Output: 3

 

2. tuple(seq)

Converts a sequence (like a list, string, or range) into a tuple.

Example:

lst = [1, 2, 3]

t = tuple(lst)

print(t)  # Output: (1, 2, 3)

 

3. min(t) / max(t)

Returns the smallest (min) or largest (max) element in the tuple.

Example:

t = (5, 2, 9, 1)

print(min(t))  # Output: 1

print(max(t))  # Output: 9

 

4. sum(t)

Returns the sum of all numeric elements in the tuple.

Example:

t = (10, 20, 30)

print(sum(t))  # Output: 60

 

5. sorted(t)

Returns a new sorted list from the tuple without modifying the original.

Example:

t = (3, 1, 4, 2)

print(sorted(t))  # Output: [1, 2, 3, 4]

print(t)          # Original tuple remains unchanged

 

Tuple Methods

These are specific to tuple objects.

1. count(x)

Returns the number of times x appears in the tuple.

Example:

t = (1, 2, 2, 3, 2)

print(t.count(2))  # Output: 3

 

2. index(x)

Returns the index of the first occurrence of x.

Example:

t = ("apple", "banana", "cherry", "banana")

print(t.index("banana"))  # Output: 1

 

Tuple Assignment (Unpacking)

Tuple assignment, also known as tuple unpacking, allows you to assign each element of a tuple to a separate variable in a single line. This is a concise and readable way to extract values from a tuple.

Syntax:

variable1, variable2, ..., variableN = tuple

- The number of variables on the left must match the number of elements in the tuple.

- Each variable receives the value at the corresponding position in the tuple.

Example:

person = ("Alice", 25, "London")

name, age, city = person

print(name, age, city)

Output:

Alice 25 London

Explanation:

- person is a tuple with three elements.

- name, age, city = person unpacks the tuple:

- name gets "Alice"

- age gets 25

- city gets "London"

- This is much cleaner than accessing each element individually using indexing.

 

More Examples

Unpacking a tuple of coordinates:

coordinates = (10.5, 20.3)

x, y = coordinates

print("X:", x)

print("Y:", y)

 

Swapping values using tuple assignment:

a = 5

b = 10

a, b = b, a

print(a, b)  # Output: 10 5

 

Mismatched unpacking (raises error):

t = (1, 2, 3)

x, y = t  # Error: too many values to unpack

 

What Are Nested Tuples?

A nested tuple is simply a tuple that contains other tuples as its elements. Think of it like a grid or a matrix.

Example

matrix = ((1, 2, 3), (4, 5, 6), (7, 8, 9))

print(matrix[1][2])   # Output: 6

Explanation:

- matrix[1] accesses the second tuple: (4, 5, 6)

- matrix[1][2] accesses the third element of that tuple: 6

Visual Representation

matrix =

(

  (1, 2, 3),   # row 0

  (4, 5, 6),   # row 1

  (7, 8, 9)    # row 2

)

So matrix[row][column] works just like a 2D array.

 

Dictionary in Python

·         A dictionary is a collection of key-value pairs.

·         Keys are unique and immutable (string, number, or tuple), while values can be of any type.

·         Dictionaries are unordered, mutable, and dynamic.

Syntax:

dictionary_name = {key1: value1, key2: value2, ...}

 

Example:

student = {"name": "Ananya", "age": 20, "grade": "A"}

print(student)

Output:

{'name': 'Ananya', 'age': 20, 'grade': 'A'}

 

Characteristics of Python Dictionary

- Unordered: Items don’t maintain any specific order (though Python 3.7+ preserves insertion order).

- Mutable: You can add, update, or delete key-value pairs.

- Dynamic: You can change the size and contents at runtime.

- Keys: Must be immutable types (e.g., strings, numbers, tuples).

- Values: Can be any data type (even lists, other dictionaries, etc.).

 

Accessing Items in a Dictionary

1. Using Square Brackets []

You can access the value of a specific key directly using square brackets.

Syntax:

dictionary[key]

Example:

student = {"name": "Ananya", "age": 20, "grade": "A"}

print(student["name"])   # Output: Ananya

Note:

If the key does not exist, this method will raise a KeyError.

 

2. Using .get() Method

This method is safer and returns None (or a default value) if the key is not found.

Syntax:

dictionary.get(key)

dictionary.get(key, default_value)

Example:

print(student.get("grade"))         # Output: A

print(student.get("subject"))       # Output: None

print(student.get("subject", "N/A"))# Output: N/A

 

3. Looping Through Dictionary Items

Accessing Keys:

for key in student:

    print(key)

 

Accessing Values:

for key in student:

    print(student[key])

 

 

Accessing Key-Value Pairs:

for key, value in student.items():

    print(key, ":", value)

 

4. Using .keys() and .values()

These methods return view objects that can be converted to lists if needed.

Example:

print(list(student.keys()))    # ['name', 'age', 'grade']

print(list(student.values()))  # ['Ananya', 20, 'A']

 

Dictionary Mutability in Python

A dictionary in Python is a collection of key-value pairs. Each key is unique, and it maps to a value. Dictionaries are mutable, meaning you can:

- Add new key-value pairs

- Modify existing values

- Delete key-value pairs

Example

# Creating a dictionary

student = {

    "name": "Amit",

    "age": 21,

    "grade": "B"

}

# Modifying a value

student["grade"] = "A"

# Adding a new key-value pair

student["major"] = "Physics"

# Deleting a key-value pair

del student["age"]

# Final dictionary

print(student)

Output:

{'name': 'Amit', 'grade': 'A', 'major': 'Physics'}

 

What Is Dictionary Traversal?

Dictionary traversal means looping through the contents of a dictionary to access its data. Since dictionaries store data as key-value pairs, you can traverse:

- Just the keys

- Just the values

- Both keys and values together

Example

student = {"name": "Ananya", "age": 20, "grade": "A"}

This dictionary stores information about a student.

 

Traversing Methods

1. Traversing Keys

for key in student:

    print(key, ":", student[key])

Explanation:

- By default, looping through a dictionary gives you its keys.

- You can then use each key to access its corresponding value.

Output:

name : Ananya

age : 20

grade : A

 

2. Traversing Values

for value in student.values():

    print(value)

Explanation:

- .values() returns a view of all the values in the dictionary.

- You loop directly through the values without needing the keys.

Output:

Ananya

20

A

 

3. Traversing Key-Value Pairs

for key, value in student.items():

    print(key, "=>", value)

Explanation:

- .items() returns a view of the dictionary’s key-value pairs as tuples.

- You can unpack each tuple into key and value during the loop.

Output:

name => Ananya

age => 20

grade => A

 

 

 

Built-in Functions and Methods for Dictionaries

(a) len()

Returns the number of key-value pairs in the dictionary.

student = {"name": "Ananya", "age": 20, "grade": "A"}

print(len(student))  # Output: 3

Explanation:

The dictionary has 3 items, so len() returns 3.

 

(b) dict()

Creates a dictionary from keyword arguments or other mappings.

d = dict(name="Rahul", age=22)

print(d)  # Output: {'name': 'Rahul', 'age': 22}

Explanation:

This is a constructor method to create a dictionary.

 

(c) keys(), values(), items()

- keys() → returns all keys

- values() → returns all values

- items() → returns all key-value pairs

print(student.keys())    # dict_keys(['name', 'age', 'grade'])

print(student.values())  # dict_values(['Ananya', 20, 'A'])

print(student.items())   # dict_items([('name', 'Ananya'), ('age', 20), ('grade', 'A')])

Explanation:

These methods help in traversing or inspecting dictionary contents.

 

(d) get(key, default)

Returns the value for the given key. If key is missing, returns the default value.

print(student.get("name"))           # Output: Ananya

print(student.get("city", "Not Found"))  # Output: Not Found

Explanation:

Safer than direct access, avoids errors if key is missing.

 

(e) update()

Adds new key-value pairs or updates existing ones.

student.update({"city": "Delhi", "age": 21})

print(student)

# Output: {'name': 'Ananya', 'age': 21, 'grade': 'A', 'city': 'Delhi'}

Explanation:

age is updated, and city is added.

 

(f) del

Deletes a specific key-value pair.

del student["grade"]

print(student)

# Output: {'name': 'Ananya', 'age': 21, 'city': 'Delhi'}

Explanation:

Removes the key "grade" and its value.

 

(g) clear()

Removes all items from the dictionary.

student.clear()

print(student)  # Output: {}

Explanation:

Empties the dictionary completely.

 

(h) fromkeys()

Creates a new dictionary with specified keys and a common default value.

keys = ["a", "b", "c"]

d = dict.fromkeys(keys, 0)

print(d)  # Output: {'a': 0, 'b': 0, 'c': 0}

Explanation:

Useful for initializing dictionaries with default values.

 

(i) copy()

Returns a shallow copy of the dictionary.

d2 = student.copy()

print(d2)

Explanation:

Creates a new dictionary with the same contents.

 

(j) pop(key)

Removes the item with the specified key and returns its value.

age = student.pop("age")

print(age)  # Output: 21

Explanation:

Removes "age" and returns its value.

 

(k) popitem()

Removes and returns the last inserted key-value pair.

pair = student.popitem()

print(pair)  # Output: ('city', 'Delhi')

Explanation:

Useful for stack-like behavior with dictionaries.

 

(l) setdefault()

Returns the value of a key if it exists; otherwise, inserts the key with a default value.

print(student.setdefault("grade", "B"))  # Output: B

print(student)

Explanation:

Adds "grade" with value "B" if it wasn't already present.

 

(m) max(), min(), sorted()

Operate on dictionary keys by default.

marks = {"Math": 90, "Science": 80, "English": 85}

print(max(marks))         # Output: Science

print(min(marks))         # Output: English

print(sorted(marks))      # Output: ['English', 'Math', 'Science']

Explanation:

These functions treat dictionary keys as iterable elements and sort them lexicographically.

 

Introduction to Python Modules

What Is a Module?

A module in Python is a file containing Python code — typically functions, classes, and variables — that you can reuse in other programs.

- It helps organize code into logical parts.

- Promotes code reuse, modularity, and maintainability.

- Modules can be built-in, third-party, or user-defined.

 

Why Use Modules?

- Avoid rewriting the same code.

- Keep your programs clean and organized.

- Share functionality across multiple scripts.

 

Using a Built-in Module

Let's use the built-in math module:

import math

# Using a function from the math module

area = math.pi * math.pow(5, 2)

print("Area of circle:", area)

Explanation:

- import math loads the module.

- math.pi gives the value of π.

- math.pow(5, 2) calculates 5^2.

 

What Is Importing a Module?

Importing a module means bringing in external Python code (functions, constants, classes) so you can use it in your program. Python offers several ways to do this depending on your needs.

 

Methods of Importing Modules

(a) import <module>

Imports the entire module. You must use the module name as a prefix to access its functions or variables.

import math

print(math.sqrt(16))  # Output: 4.0

Explanation:

- math is a built-in module for mathematical operations.

- math.sqrt(16) calls the sqrt() function from the math module.

- You must use math. before any function from the module.

 

(b) from <module> import <name>

Imports specific functions or variables from a module. You can use them directly without the module prefix.

from math import sqrt, pi

print(sqrt(25))  # Output: 5.0

print(pi)        # Output: 3.141592653589793

Explanation:

- Only sqrt and pi are imported from math.

- You can use them directly without writing math. before them.

- This is useful when you only need a few items from a module.

 

(c) import <module> as <alias>

Imports the entire module but assigns it a short alias for convenience.

import math as m

print(m.ceil(4.2))  # Output: 5

Explanation:

- math is imported as m.

- You can now use m.ceil() instead of math.ceil().

- This is helpful when the module name is long or used frequently.

 

What Is a Built-in Module?

A built-in module in Python is a module that comes pre-installed with Python. You don’t need to install it separately — just import and use it. These modules provide ready-to-use functions and constants for common tasks like math, randomization, date/time handling, and more.

 

Common Built-in Modules

1. math

Provides mathematical functions and constants.

Use: Calculations like square roots, trigonometry, logarithms.

import math

print(math.sqrt(25))     # 5.0

print(math.pi)           # 3.141592653589793

 

2. random

Generates random numbers and selections.

Use: Games, simulations, random sampling.

import random

print(random.randint(1, 10))       # Random integer between 1 and 10

print(random.choice(['a', 'b']))   # Randomly selects one item

 

3. datetime

Handles date and time operations.

Use: Timestamping, scheduling, formatting dates.

import datetime

now = datetime.datetime.now()

print(now.strftime("%Y-%m-%d %H:%M:%S"))

 

4. statistics

Performs statistical calculations.

Use: Mean, median, mode, standard deviation.

import statistics

data = [10, 20, 30, 40]

print(statistics.mean(data))   # 25

 

5. os

Interacts with the operating system.

Use: File handling, environment variables, directory navigation.

import os

print(os.getcwd())        # Current working directory

 

6. sys

Provides access to system-specific parameters and functions.

Use: Command-line arguments, interpreter info.

import sys

print(sys.version)        # Python version

 

7. time

Time-related functions.

Use: Delays, timestamps, performance measurement.

import time

time.sleep(2)             # Pauses for 2 seconds

 

8. json

Handles JSON data (JavaScript Object Notation).

Use: Reading/writing JSON files, APIs.

import json

data = '{"name": "Ananya", "age": 20}'

parsed = json.loads(data)

print(parsed["name"])     # Ananya

 

What Is a User-Defined Module?

A user-defined module is a Python file that you create yourself to organize reusable code — such as functions, classes, or variables — that can be imported into other Python programs.

- It helps keep your code modular, clean, and reusable.

- You can split large programs into smaller, manageable files.

 

Step-by-Step: Creating and Using a Module

Step 1: Create the Module File

Create a file named greet.py with the following content:

# greet.py

def hello(name):

    return f"Hello, {name}!"

Explanation:

- This file defines a function hello() that takes a name and returns a greeting.

- This file becomes a module because it contains Python code that can be imported.

Step 2: Use the Module in Another File

Create another Python file (e.g., main.py) and import the module:

# main.py

import greet

print(greet.hello("Ananya"))

Explanation:

- import greet loads the greet.py module.

- greet.hello("Ananya") calls the hello() function from that module.

- Output: Hello, Ananya!

 

Behind the Scenes

- Python looks for greet.py in the current directory or in the system path.

- When you import it, Python compiles it into a .pyc file (cached bytecode) for faster execution next time.

- You can import the same module in multiple programs without rewriting the function.

 

What is the math Module?

The math module in Python provides access to mathematical constants and functions that are useful for performing complex calculations. It includes everything from basic arithmetic to trigonometry and logarithmic operations.

To use it, you must first import it:

import math

 

Mathematical Constants

1. math.pi

Represents the value of π (pi), the ratio of a circle’s circumference to its diameter.

Value: 3.141592653589793

print(math.pi)  # Output: 3.141592653589793

 

2. math.e

Represents Euler’s number, the base of natural logarithms.

Value: 2.718281828459045

print(math.e)  # Output: 2.718281828459045

 

Common Functions in math Module

1. math.sqrt(x)

Returns the square root of x.

Example:

print(math.sqrt(16))  # Output: 4.0

 

2. math.ceil(x)

Rounds x up to the nearest integer.

Example:

print(math.ceil(4.2))  # Output: 5

 

3. math.floor(x)

Rounds x down to the nearest integer.

Example:

print(math.floor(4.9))  # Output: 4

 

4. math.pow(x, y)

Returns x^y (x raised to the power y).

Example:

print(math.pow(2, 3))  # Output: 8.0

 

5. math.fabs(x)

Returns the absolute value of x as a float.

Example:

print(math.fabs(-7))  # Output: 7.0

 

6. Trigonometric Functions

These functions take angles in radians.

math.sin(x)

Returns the sine of angle x (in radians).

print(math.sin(math.pi/2))  # Output: 1.0

math.cos(x)

Returns the cosine of angle x (in radians).

print(math.cos(0))  # Output: 1.0

math.tan(x)

Returns the tangent of angle x (in radians).

print(math.tan(math.pi/4))  # Output: 1.0

 

What is the random Module?

The random module in Python is used to generate pseudo-random numbers — numbers that appear random but are generated by a deterministic process. This module is commonly used in:

- Games and simulations

- Random sampling

- Data shuffling

- Testing and modeling

To use it, you must first import it:

import random

 

Functions in the random Module

1. random.random()

Definition: Returns a floating-point number between 0.0 and 1.0.

print(random.random())  # Example Output: 0.37444887175646646

Explanation:

- Useful for generating probabilities or scaling values.

- The output is always ≥ 0.0 and < 1.0.

 

2. random.randint(a, b)

Definition: Returns a random integer between a and b, inclusive.

print(random.randint(1, 10))  # Example Output: 7

Explanation:

- Includes both endpoints: 1 and 10.

- Great for dice rolls, random IDs, or selecting from a fixed range.

 

3. random.randrange(start, stop, step)

Definition: Returns a random number from the sequence generated by range(start, stop, step).

print(random.randrange(1, 10, 2))  # Example Output: 5

Explanation:

- Picks randomly from values like 1, 3, 5, 7, 9.

- Useful when you want random numbers with a specific pattern or step.

 

What is the statistics Module?

The statistics module is a built-in Python library used for performing mathematical statistical operations on numeric data. It provides functions to calculate measures like mean, median, mode, variance, and more.

To use it, you must first import it:

import statistics

 

Functions in the statistics Module

1. statistics.mean(data)

Returns the average (arithmetic mean) of the data.

Formula:

Mean = Sum of all values / Number of values

Example:

data = [10, 20, 30, 40, 50]

print(statistics.mean(data))  # Output: 30

Explanation:

- Sum = 150

- Count = 5

- Mean = 150 / 5 = 30

 

2. statistics.median(data)

Returns the middle value when the data is sorted.

- If the number of elements is odd, it returns the middle one.

- If even, it returns the average of the two middle values.

Example:

data = [7, 2, 5, 10, 4]

print(statistics.median(data))  # Output: 5

Explanation:

- Sorted data: [2, 4, 5, 7, 10]

- Middle value = 5

 

3. statistics.mode(data)

Returns the most frequent value in the data.

Example:

data = [2, 3, 4, 3, 5, 3, 2]

print(statistics.mode(data))  # Output: 3

Explanation:

- Frequency count: 3 appear three times, more than any other value.

Python Notes for Standard XII

  Introduction to Problem-Solving Problem-solving in computer science means using logical steps to design and implement a solution to a gi...