Class-11-Preview of Python Notes
Class-11-Preview of Python Notes
COMPUTER SCIENCE
PRAFULLA SIR
7999552828
1|Page
Computational Thinking and 5. Debugging
Programming - I o Identify and fix errors in the
code.
Introduction to Problem-Solving o Use debugging tools and
1. Steps for Problem-Solving techniques to locate logical
Analysing the Problem or runtime errors.
Developing an Algorithm
Coding Representation of Algorithms
Testing 1. Flowchart
Debugging A flowchart is a graphical
2. Representation of Algorithms representation of an algorithm
Flowchart using standardized symbols:
o Oval: Start/End
Pseudocode
o Rectangle:
Decomposition
Process/Instruction
o Diamond: Decision
Introduction to Problem-Solving
o Arrow: Flow of control
Problem-solving is a fundamental skill in
2. Pseudocode
computer science, involving the application
A pseudocode is a simplified,
of logical thinking to find solutions to
plain-text representation of an
complex issues. It follows a structured
algorithm that uses structured
process to ensure efficiency and accuracy.
language similar to programming
constructs. It focuses on logic
Steps for Problem-Solving
without the constraints of syntax.
1. Analyzing the Problem
Example:
o Clearly understand the
Start
problem statement.
Input: A, B
o Identify inputs, outputs, and
If A > B
constraints.
Print "A is greater"
o Break the problem into
Else
smaller, manageable parts.
Print "B is greater"
2. Developing an Algorithm
End
o Design a step-by-step
procedure to solve the
3. Decomposition
problem.
Decomposition involves breaking a
o Ensure the algorithm is
complex problem into smaller, manageable
clear, efficient, and
sub-problems, each of which can be solved
unambiguous.
independently.
3. Coding
Promotes modularity and
o Translate the algorithm into
reusability.
a programming language.
Makes debugging and testing
o Use proper syntax and
easier.
follow coding standards for
Example: In building a calculator,
readability and
divide tasks into addition,
maintainability.
subtraction, multiplication, and
4. Testing
division modules.
o Verify the code against
multiple test cases to ensure
Basics of Python programming:
it works correctly.
Introduction to Python,
o Include edge cases and
boundary conditions. Features of Python,
executing a simple “hello world"
program,
2|Page
Execution modes: interactive mode python hello.py
and script mode, Output:
Python character set, Hello, World!
Python tokens(keyword, identifier,
literal, operator, punctuator), Execution Modes
variables, 1. Interactive Mode:
concept of l-value and r-value, use of o Code is executed
comments immediately.
o Useful for quick tests or
calculations.
Introduction to Python o Example:
Python was developed by Guido van >>> 2 + 3
Rossum and released in 1991. Its design 5
emphasizes readability and simplicity, 2. Script Mode:
making it an excellent choice for beginners o Write and save multiple
and professionals alike. lines of code in a .py file.
o Execute the file in the
Features of Python terminal or IDE.
1. Simple and Easy to Learn:
Python has a straightforward Python Character Set
syntax similar to English. Python uses the Unicode character set,
2. Interpreted Language: Python which includes:
executes code line by line, Letters (A-Z, a-z)
simplifying debugging. Digits (0-9)
3. Open Source: Python is free and Special symbols (e.g., +, -, @)
has a vibrant community. Whitespaces (e.g., space, tab,
4. Portable: Python code runs on newline)
multiple platforms without
modification. Python Tokens
5. Extensive Libraries: Python Tokens are the smallest building blocks of
provides rich libraries for various Python code. Types include:
tasks like machine learning, web 1. Keywords:
development, and data analysis. o Reserved words with
6. Dynamically Typed: Variable special meanings, e.g., if,
types are determined during else, while, for, def.
runtime. o Example:
if x > 0:
Executing a Simple "Hello, World!" print("Positive")
Program 2. Identifiers:
Interactive Mode: o Names given to variables,
>>> print("Hello, World!") functions, or classes.
Hello, World! o Must begin with a letter or
Executed line by line in the Python underscore, followed by
shell or REPL (Read-Eval-Print letters, digits, or
Loop). underscores.
o Case-sensitive.
o Example:
Script Mode:
1. Write the code in a Python file, variable_name = 10
e.g., hello.py: 3. Literals:
o Fixed values like numbers,
print("Hello, World!")
2. Execute the file: strings, or boolean values.
3|Page
o Examples: Numeric Data types
10 # Integer literal o Integer
3.14 # Float literal o Fluting
"Hello" # String literal o Complex
True, False # Boolean Boolean Data types
literals Sequence dta types
o String
4. Operators: o List
o Symbols used to perform o tuple
operations, e.g., +, -, *, /. Special data types
o Example: o None
result = 10 + 5 o Mapping dictionary)
5. Punctuators: Mutable & Immutable data types
o Special symbols with
specific purposes, e.g., :, (), Define data types.
{}, []. Data types in Python specify the type of
data a variable can hold. Python has a
Variables dynamic type system, meaning variables do
A variable is a named memory location to not need explicit declaration of their type.
store data. Below is a detailed overview of Python's
Example: data types.
x=5
y = "Python" Numeric Data Types
Concept of l-value and r-value: 1. Integer (int):
l-value (left value): Refers to the o Represents whole numbers.
memory location (e.g., the variable o Example:
name on the left of =). x = 10,-150 # Integer
r-value (right value): Refers to the 2. Floating Point (float):
data or value assigned (e.g., the o Represents numbers with
value or expression on the right of decimal points.
=). o Example:
Example: y = 3.14 # Floating-point
x = 10 # x is the l-value, 10 is the r-value number
3. Complex (complex):
Use of Comments o Represents complex
Comments are non-executable lines used numbers with a real and an
to explain code. imaginary part.
1. Single-line Comments: Begin with o Example:
#. z = 2 + 3j # Complex
# This is a single-line comment number
print("Hello, World!")
2. Multi-line Comments: Enclosed Boolean Data Type
within triple quotes (''' or """). Represents two values: True or
""" False.
This is a multi-line comment. Used in logical expressions.
It spans multiple lines. Example:
""" is_valid = True
print("Hello, World!")
Sequence Data Types
Data Types in Python 1. String (str):
Define data types
4|Page
o Immutable sequence of my_list[0] = 10 # Modifying the
characters enclosed in first element
quotes (', ", or '''). 2. Immutable: Cannot be modified
o Example: after creation.
name = "Python" Examples:
o int
2. List (list): o float
o Mutable, ordered collection o str
of items. o tuple
o Can hold mixed data types. Example of immutable behavior:
o Example: my_tuple = (1, 2, 3)
fruits = ["apple", "banana", my_tuple[0] = 10 # This will raise
"cherry"] an error
fruits[1] = "mango" #
Modifying the second Operators in Python
element Define operators
3. Tuple (tuple): Types of operators
o Immutable, ordered o Arithmetic Operators
collection of items. o Relational Operators
o Example: o Logical Operators
coordinates = (10, 20, 30) o Assignment Operators
o Membership Operators
Special Data Types o Identity Operators
1. None: o Bitwise operators
o Represents the absence of o Augmented Assignment
value or a null value. Operators
o Example: Operators are symbols or keywords used to
x = None perform operations on variables and values.
2. Mapping (dict): Python provides a rich set of operators
o Mutable, unordered categorized as follows:
collection of key-value
pairs. 1. Arithmetic Operators
o Keys must be unique and These operators are used for basic
immutable, while values mathematical operations.
can be of any type.
Operator Description Example
o Example:
student = {"name": "John", + Addition 5+3=8
"age": 18} - Subtraction 5-3=2
student["age"] = 19 # * Multiplication 5 * 3 = 15
Updating the value of a key
/ Division 5 / 2 = 2.5
Mutable and Immutable Data Types // Floor Division 5 // 2 = 2
1. Mutable: Can be modified after % Modulus (Remainder) 5 % 2 = 1
creation. ** Exponentiation 2 ** 3 = 8
Examples:
o list
o dict 2. Relational (Comparison)
o set (unordered collection of Operators
unique items). These operators compare two values and
Example of mutable behavior: return a boolean (True or False).
my_list = [1, 2, 3]
5|Page
Operator Description Example Operator Description Example
5 == 5 → Returns True if the 'a' in 'apple'
== Equal to in
True element is found → True
5 != 3 → 'b' not in
!= Not equal to Returns True if the
True not in 'apple' →
element is not found True
> Greater than 5 > 3 → True
< Less than 3 < 5 → True Example:
fruits = ["apple", "banana", "cherry"]
Greater than or equal 5 >= 5 → print("apple" in fruits) # True
>=
to True print("mango" not in fruits) # True
3 <= 5 → 6. Identity Operators
<= Less than or equal to
True These operators compare the memory
location of two objects.
3. Logical Operators Operator Description Example
These operators are used to combine Returns True if objects
is x is y
conditional statements. are the same
Operator Description Example Returns True if objects
is not x is not y
Returns True if both (5 > 3) and (3 are not the same
and
conditions are true > 1) → True Example:
Returns True if at (5 > 3) or (3 < x = [1, 2, 3]
or y=x
least one is true 1) → True
z = [1, 2, 3]
Reverses the not(5 > 3) →
not
boolean value False print(x is y) # True (same object)
print(x is z) # False (different objects)
4. Assignment Operators
These operators are used to assign values 7. Bitwise Operators
to variables. These operators perform bit-level
Operator Description Example operations on binary numbers.
= Assigns value x=5 Operator Description Example
x += 3 (same as Bitwise
+= Add and assign & 5&3=1
x = x + 3) AND
Subtract and ` ` Bitwise OR
-= x -= 3
assign Bitwise
^ 5^3=6
Multiply and XOR
*= x *= 3
assign Bitwise
~ ~5 = -6
/= Divide and assign x /= 3 NOT
Floor divide and << Left shift 5 << 1 = 10
//= x //= 3
assign >> Right shift 5 >> 1 = 2
Modulus and
%= x %= 3
assign 8. Augmented Assignment
Exponentiate and Operators in Python
**= x **= 3
assign Augmented assignment operators combine
an operation with assignment. These
5. Membership Operators operators simplify code by reducing
These operators test if an element is redundancy in performing an operation on
present in a sequence (e.g., list, string). a variable and then reassigning the result to
that variable.
6|Page
Syntax print(x) # Output: 6
7|Page
Precedence (b) Explicit Type Conversion (Type
Operator Description
(High to Low) Casting):
Performed manually by the
==, !=, >, <, Relational programmer using type conversion
>=, <= Operators functions like int(), float(), and
not Logical NOT str().
Example:
and Logical AND
x = "10" # string
or Logical OR Lowest y = int(x) # Converts string to integer
print(y + 5) # Output: 15
2. Expression
An expression is a combination of 5. Input/Output Operations
variables, values, and operators that are Python provides simple functions for
evaluated to produce a result. taking input from the user and displaying
Examples: output.
# Arithmetic expression (a) Input from Console:
result = (5 + 3) * 2 The input() function is used to accept user
input as a string.
# Logical expression
is_valid = (5 > 3) and (3 < 10) Example:
name = input("Enter your name: ")
3. Statement print("Hello, " + name)
A statement is an instruction that Python
can execute. Examples of statements (b) Displaying Output:
include assignments, function calls, and The print() function is used to display data
control flow commands. on the console.
Examples:
# Assignment statement Example:
x = 10 x = 10
y = 20
# Conditional statement print("The sum of", x, "and", y, "is", x + y)
if x > 5:
print("x is greater than 5") (c) Formatting Output:
You can format output using f-strings or
4. Type Conversion the format() method.
Python supports type conversion for
converting data from one type to another. Examples:
(a) Implicit Type Conversion (Type # Using f-strings
Coercion): name = "Alice"
Performed automatically by
age = 25
Python. print(f"My name is {name} and I am
Happens when an operation
{age} years old.")
involves mixed data types.
Example: # Using format()
x = 5 # int print("My name is {} and I am {} years
y = 2.5 # float old.".format(name, age))
z = x + y # Python converts `x` to float
print(z) # Output: 7.5 (float) 6. Evaluation of an Expression
An expression is evaluated according to
the precedence and associativity of its
8|Page
operators. The evaluation produces a return length + width # Should be
value. length * width
result = 5 + 3 * 2 # Multiplication (*) is
performed first print(calculate_area(5, 3)) # Output: 8
print(result) # Output: 11 (wrong)
Fix: Debug and validate the program's
Errors in Python logic.
Errors in Python occur when the def calculate_area(length, width):
interpreter encounters something it cannot return length * width
process. Errors can be categorized into
three main types: Syntax Errors, Logical print(calculate_area(5, 3)) # Output: 15
Errors, and Run-time Errors. (correct)
9|Page
Error When It 3. Sequential Flow
Result Detection Definition:
Type Occurs
In sequential flow, statements are
Harder to executed one after another in the
During Produces
Logica detect; order they appear in the program.
execution incorrect
l Error requires Example:
. output.
testing. print("Start")
Program x=5+3
Detected print("The sum is:", x)
Run- During crashes or
during print("End")
time execution raises an
program Output:
Error . exception
run. Start
. The sum is: 8
End
Flow of Control in Python
Flow of control determines the sequence in 4. Conditional Flow
which statements are executed in a Definition:
program. Python uses indentation to define Conditional flow allows the
blocks of code and provides structures for program to execute statements
sequential, conditional, and iterative based on certain conditions using
flows. decision-making structures.
Types of Conditional Statements
1. Introduction in Python:
Flow of control allows the program to 1. if
make decisions, repeat tasks, or execute 2. if-else
instructions sequentially. Python achieves 3. if-elif-else
this through: Examples:
Sequential Flow Simple if Statement:
Conditional Flow x = 10
Iterative Flow if x > 5:
print("x is greater than 5")
2. Use of Indentation
What is Indentation? if-else Statement:
Python uses indentation (spaces or x = -3
tabs) to group statements into if x >= 0:
blocks. This replaces the use of print("Non-negative")
curly braces {} in other languages. else:
Proper indentation is mandatory in print("Negative")
Python.
if-elif-else Statement:
Example of Indentation: x=0
if x > 0: if x > 0:
print("Positive number") # Indented print("Positive")
block executed if condition is true elif x == 0:
else: print("Zero")
print("Non-positive number") else:
print("Negative")
Incorrect Indentation:
if x > 0: 5. Iterative Flow
print("Positive number") # Raises Definition:
IndentationError Iterative flow allows a block of
code to be executed repeatedly,
10 | P a g e
based on a condition. Python Flow Type Description Examples
provides two types of loops:
1. while Loop Executes
print("Hello
2. for Loop Sequential statements in
World")
while Loop order.
Repeats a block of code while a Executes
condition is True. if, if-else, if-
Conditional based on
Example: elif-else
conditions.
count = 1
while count <= 5:
print(count)
count += 1 Summary of Conditional Statements
Output: Type Description Syntax
1 Executes code if
2 if condition:
if the condition is
3 execute_code
true.
4
5 Executes one
for Loop block if the if condition:
if-
Iterates over a sequence (e.g., list, condition is true, execute_code
else
string, range). otherwise else: code2
Example: another.
for char in "Python": Used for if condition1:
print(char) if-
multiple execute_code elif
Output: elif-
P conditions and cond2: code2
else
y outcomes. else: code3
t
h Iterative Statements in Python
o Iterative statements allow for repeated
n execution of a block of code based on a
Loop Control Statements: condition or a predefined range. In Python,
1. break: Exits the loop prematurely. there are two primary types of iterative
2. continue: Skips the current statements: the for loop and the while
iteration. loop. We also use control statements like
3. pass: Does nothing, acts as a break, continue, and nested loops to
placeholder. enhance the functionality of loops.
11 | P a g e
print(i) 2
Output: 3
0 4
1
2 5. Control Statements in Loops
3 Break Statement
4 Description:
The break statement is used to exit
2. range() Function the loop prematurely when a
The range() function is commonly used condition is met.
with the for loop to define a sequence of Example:
numbers. It generates a sequence of for i in range(10):
numbers, which can be used to iterate over if i == 5:
in a loop. break
Syntax: print(i)
range(start, stop, step) Output:
start: The starting value of the Copy code
sequence. 0
stop: The end value (not included 1
in the sequence). 2
step: The interval between each 3
value in the sequence. 4
Examples: Continue Statement
for i in range(1, 10, 2): Description:
print(i) The continue statement is used to
Output: skip the current iteration and move
Copy code to the next iteration of the loop.
1 Example:
3 for i in range(5):
5 if i == 2:
7 continue
9 print(i)
Output:
3. while Loop 0
The while loop is used when the number 1
of iterations is not known and the loop 3
continues until the condition becomes 4
false.
Syntax: 6. Nested Loops
while condition: A nested loop is a loop inside another
# Code to execute as long as condition loop. The inner loop is executed
is true completely for each iteration of the outer
Example: loop.
i=0 Example:
while i < 5: python
print(i) Copy code
i += 1 for i in range(3):
Output: for j in range(2):
Copy code print(f"i = {i}, j = {j}")
0 Output:
1 css
12 | P a g e
Copy code
i = 0, j = 0 Example:
i = 0, j = 1 csharp
i = 1, j = 0 Copy code
i = 1, j = 1 Enter a positive number: 5
i = 2, j = 0 The factorial of 5 is 120
i = 2, j = 1
Summary of Loops
Suggested Programs Using Loops
1. Program to Generate a Pattern: Loop
Description: Description Syntax
Type
This program generates a simple pattern
using loops. Iterates over a for variable
# Program to generate a pattern for loop sequence (range, in sequence:
n=5 list, etc.). ...
for i in range(1, n+1): Executes as long
for j in range(i): while while
as a condition is
print("*", end=" ") loop condition: ...
true.
print()
Output: Exits the loop
break break
* immediately.
** Skips the current
*** iteration and
**** continue continue
proceeds with the
***** next.
2. Program to Find the Sum of a Series:
Description: Loops inside for/while
This program calculates the sum of the Nested another loop for (nested
first n numbers. loops complex inside each
# Program to find the sum of a series operations. other)
n = int(input("Enter the number of terms:
"))
sum = 0 Strings in Python
for i in range(1, n+1): Strings are sequences of characters
sum += i enclosed in single quotes (' ') or double
print("Sum of the series is:", sum) quotes (" "). In Python, strings are
immutable, meaning once created, they
Example: cannot be modified directly. However, we
Enter the number of terms: 5 can perform various operations on strings,
Sum of the series is: 15 such as concatenation, slicing, and applying
3. Program to Find the Factorial of a built-in functions.
Number:
Description: 1. Introduction to Strings
This program calculates the factorial of a A string is a sequence of characters, and it
positive integer. can be created by enclosing characters in
# Program to find the factorial of a number single, double, or triple quotes (for multi-
n = int(input("Enter a positive number: ")) line strings). For example:
factorial = 1 string1 = "Hello, World!"
for i in range(1, n+1): string2 = 'Python Programming'
factorial *= i
print(f"The factorial of {n} is {factorial}") 2. String Operations
13 | P a g e
a. Concatenation Oper Expla
Concatenation is the process of joining Syntax Example Output
ation nation
two or more strings together using the +
Extract
operator.
s
substri
Example: ng
str1 = "Hello" Basic
Strin startin "Python" "Pyt"
str2 = "World" Slicin g[start:end]
g from [0:3]
result = str1 + " " + str2 g
index
print(result) # Output: Hello World start
b. Repetition to
You can repeat a string multiple times end-1.
using the * operator.
Omit
Return
ting
s the "Hello"[ "Hello"
start string[:]
Example: entire :]
and
str1 = "Python " string.
end
result = str1 * 3
print(result) # Output: Python Python Uses
Python negativ
e
c. Membership indices
The in and not in operators are used to to slice
Nega
check if a substring exists in a string. from
tive string[- "Python"
"ho"
the
Indic start:-end] [-3:-1]
Example: end. -1
es
str1 = "Hello, World!" refers
print("Hello" in str1) # Output: True to the
print("Python" not in str1) # Output: True last
charact
d. Slicing er.
Slicing allows extracting a portion of the Skips
string. The general syntax is charact
string[start:end], where start is the index ers
Using string[start based "abcdefg
"bdf"
where the slice starts, and end is the index step :end:step] "[1:6:2]
where it ends (excluding the character at on the
end). step
size.
Example: Revers
str1 = "Hello, World!" es the
slice1 = str1[0:5] # Extracts "Hello" Reve
string
slice2 = str1[7:] # Extracts "World!" rsing
string[::-1]
by "Python" "nohtyP
print(slice1) # Output: Hello a [::-1] "
using a
print(slice2) # Output: World! Strin
negativ
g
e step
String Slicing in Python - Example size.
in Tabular Format Omits
Slicin
the
g string[start "abcdefg
step "cde"
with :end:] "[2:5:]
parame
Defa
ter
14 | P a g e
Oper Expla Example:
Syntax Example Output
str1 = "Python"
ation nation
print(len(str1)) # Output: 6
ult (defaul
Step ts to 1)
b. capitalize()
and
slices Capitalizes the first letter of a string.
from
start Example:
to str1 = "python"
end-1. print(str1.capitalize()) # Output: Python
When
start c. title()
is Capitalizes the first letter of each word in
Empt greater the string.
y
string[start than "abcdefg
Strin :end] "" Example:
end, "[5:2]
g returns str1 = "python programming"
Slice an print(str1.title()) # Output: Python
empty Programming
string.
d. lower()
Converts all characters of the string to
Key Points on String Slicing:
lowercase.
Start index: The index where
Example:
slicing begins (inclusive).
str1 = "Python"
End index: The index where
print(str1.lower()) # Output: python
slicing ends (exclusive).
Step: How much to increment each
time during slicing (defaults to 1). e. upper()
Converts all characters of the string to
3. Traversing a String Using Loops uppercase.
You can use a loop (like a for loop) to
traverse each character of a string. Example:
str1 = "python"
Example: print(str1.upper()) # Output: PYTHON
str1 = "Python"
for char in str1: f. count()
print(char) Returns the number of occurrences of a
Output: substring in the string.
P
y Example:
t str1 = "Python Programming"
h print(str1.count("P")) # Output: 2
o
n g. find()
4. Built-in Functions/Methods for Returns the index of the first occurrence of
Strings a substring. If the substring is not found, it
returns -1.
a. len()
Returns the length of a string. Example:
str1 = "Python Programming"
15 | P a g e
print(str1.find("Pro")) # Output: 7
print(str1.find("Java")) # Output: -1 m. isdigit()
Returns True if all characters in the string
h. index() are digits.
Similar to find(), but raises a ValueError if
the substring is not found. Example:
str1 = "12345"
Example: print(str1.isdigit()) # Output: True
str1 = "Python Programming" n. islower()
print(str1.index("Pro")) # Output: 7 Returns True if all characters in the string
are lowercase.
i. endswith()
Returns True if the string ends with the Example:
specified substring, otherwise returns str1 = "python"
False. print(str1.islower()) # Output: True
Example: o. isupper()
str1 = "Python Programming" Returns True if all characters in the string
print(str1.endswith("ming")) # Output: are uppercase.
True
Example:
j. startswith() str1 = "PYTHON"
Returns True if the string starts with the print(str1.isupper()) # Output: True
specified substring, otherwise returns
False. p. isspace()
Returns True if all characters in the string
Example: are whitespace.
str1 = "Python Programming"
print(str1.startswith("Py")) # Output: True Example:
str1 = " "
k. isalnum() print(str1.isspace()) # Output: True
Returns True if all characters in the string
are alphanumeric (letters or numbers). q. lstrip()
Removes leading whitespaces (from the
Example: left side of the string).
str1 = "Python3"
print(str1.isalnum()) # Output: True Example:
str1 = " Python"
str2 = "Python 3" print(str1.lstrip()) # Output: Python
print(str2.isalnum()) # Output: False
Zr. rstrip()
l. isalpha()
Removes trailing whitespaces (from the
Returns True if all characters in the string right side of the string).
are alphabetic.
Example:
Example: str1 = "Python "
str1 = "Python" print(str1.rstrip()) # Output: Python
print(str1.isalpha()) # Output: True
s. strip()
Removes leading and trailing whitespaces.
16 | P a g e
Example: Lists are versatile data structures used to
str1 = " Python " store collections of items. You can store
print(str1.strip()) # Output: Python any number of items in a list, and they can
be of any data type, including numbers,
t. replace() strings, or even other lists.
Replaces a specified substring with
another substring. Example:
list1 = [1, 2, 3, 4, 5]
Example: list2 = ["apple", "banana", "cherry"]
str1 = "Python is fun"
print(str1.replace("fun", "awesome")) # 2. Indexing in Lists
Output: Python is awesome Each element in a list has an index,
starting from 0. You can access elements
u. join() of the list using their index.
Joins elements of an iterable (like a list)
into a string, using the string as a
separator. Example:
list1 = [10, 20, 30, 40]
Example: print(list1[0]) # Output: 10 (first element)
str1 = "-" print(list1[-1]) # Output: 40 (last element)
seq = ("a", "b", "c")
print(str1.join(seq)) # Output: a-b-c 3. List Operations
a. Concatenation
v. partition() You can concatenate (combine) two lists
Splits the string into a tuple of three using the + operator.
elements: the part before the separator, the
separator, and the part after the separator. Example:
list1 = [1, 2, 3]
Example: list2 = [4, 5, 6]
str1 = "Python is fun" result = list1 + list2
print(str1.partition("is")) # Output: print(result) # Output: [1, 2, 3, 4, 5, 6]
('Python ', 'is', ' fun')
b. Repetition
w. split() You can repeat the elements of a list using
Splits the string into a list, using the the * operator.
specified delimiter (space by default).
Example: Example:
str1 = "Python is fun" list1 = [1, 2, 3]
print(str1.split()) # Output: ['Python', 'is', result = list1 * 2
'fun'] print(result) # Output: [1, 2, 3, 1, 2, 3]
17 | P a g e
d. Slicing print(list1) # Output: [1, 2, 3, 4]
You can extract a part of the list using
slicing with the syntax list[start:end], where d. extend()
start is the index where the slice begins and Appends all elements of an iterable to the
end is where it ends (but does not include list.
the element at end).
Example:
Example: list1 = [1, 2, 3]
list1 = [10, 20, 30, 40, 50] list2 = [4, 5, 6]
slice1 = list1[1:4] # Extract elements from list1.extend(list2)
index 1 to 3 print(list1) # Output: [1, 2, 3, 4, 5, 6]
print(slice1) # Output: [20, 30, 40]
e. insert()
4 Traversing a List Using Loops. Inserts an element at a specific index.
You can loop through the elements of a list
using a for loop. Example:
list1 = [1, 2, 3]
Example: list1.insert(1, 4) # Insert 4 at index 1
list1 = [1, 2, 3, 4] print(list1) # Output: [1, 4, 2, 3]
for item in list1:
print(item) f. count()
Output: Returns the number of occurrences of an
Copy code element in the list.
1
2 Example:
3 list1 = [1, 2, 2, 3, 2, 4]
4 print(list1.count(2)) # Output: 3
c. append() i. pop()
Adds an element to the end of the list. Removes and returns an element at the
specified index (or the last element if no
Example: index is specified).
list1 = [1, 2, 3]
list1.append(4) Example:
18 | P a g e
list1 = [1, 2, 3] A nested list is a list within another list.
print(list1.pop()) # Output: 3 (removes the You can access nested elements by
last element) chaining indices.
print(list1) # Output: [1, 2] Example:
nested_list = [[1, 2], [3, 4], [5, 6]]
j. reverse() print(nested_list[0]) # Output: [1, 2]
Reverses the order of elements in the list. print(nested_list[1][0]) # Output: 3
19 | P a g e
print(5 in t) # Output: False o Returns the sum of all the
elements in the tuple.
4. Slicing: t = (10, 20, 30)
o Extracting a part of the print(sum(t)) # Output: 60
tuple. Example Usage:
t = (1, 2, 3, 4, 5) t = (1, 2, 3, 4, 5)
print(t[1:4]) # Output: (2, 3, 4)
# Indexing
Built-in Functions/Methods: print(t[1]) # Output: 2
1. len():
o Returns the number of
elements in the tuple. # Concatenation
t = (10, 20, 30) t2 = (6, 7, 8)
print(len(t)) # Output: 3 print(t + t2) # Output: (1, 2, 3, 4, 5, 6, 7,
2. tuple(): 8)
o Converts an iterable (like a
list or a string) to a tuple. # Repetition
print(t * 2) # Output: (1, 2, 3, 4, 5, 1, 2, 3,
t = tuple([1, 2, 3]) 4, 5)
print(t) # Output: (1, 2, 3)
3. count(): # Membership
o Returns the number of print(3 in t) # Output: True
occurrences of a specified print(10 in t) # Output: False
element in the tuple.
t = (10, 20, 30, 20, 20) # Slicing
print(t.count(20)) # Output: 3 print(t[1:4]) # Output: (2, 3, 4)
# Built-in Functions
4. index(): print(len(t)) # Output: 5
o Returns the index of the print(sorted(t)) # Output: [1, 2, 3, 4, 5]
first occurrence of a print(min(t)) # Output: 1
specified element. print(max(t)) # Output: 5
t = (10, 20, 30, 20) print(sum(t)) # Output: 15
print(t.index(20)) # Output: 1
5. sorted():
o Returns a sorted list from Tuple Assignment and Nested Tuples
the tuple (does not modify Tuple Assignment:
the tuple itself). Tuple assignment allows you to unpack a
t = (30, 10, 20) tuple directly into multiple variables. Each
print(sorted(t)) # Output: [10, 20, element in the tuple is assigned to a
30] corresponding variable.
6. min():
o Returns the smallest Example:
element in the tuple. # Tuple assignment
t = (10, 20, 30, 5) person = ("John", 25, "Engineer")
print(min(t)) # Output: 5 name, age, profession = person
7. max():
o Returns the largest element print(name) # Output: John
in the tuple. print(age) # Output: 25
t = (10, 20, 30, 5) print(profession) # Output: Engineer
print(max(t)) # Output: 30
8. sum():
20 | P a g e
# Using get() method
Nested Tuples: print(student.get("course")) # Output:
A nested tuple is a tuple that contains Computer Science
other tuples as elements. Note: If a key doesn't exist, using square
brackets will result in a KeyError, but get()
Example: returns None if the key is not found (or a
# Nested tuple default value if provided).
nested_tuple = ((1, 2), (3, 4), (5, 6))
print(nested_tuple[0]) # Output: (1, 2) Mutability of a Dictionary
print(nested_tuple[1][1]) # Output: 4 Dictionaries are mutable, which means you
can change their contents by adding,
Dictionary in Python modifying, or removing key-value pairs.
A dictionary is an unordered collection of Adding a New Item
key-value pairs, where each key is unique You can add a new key-value pair to the
and is associated with a value. The dictionary by assigning a value to a new
dictionary is defined using curly braces {}, key.
with each item being a pair consisting of a
key and a value. Example:
# Adding a new item
Introduction to Dictionary student["grade"] = "A"
A dictionary in Python is a collection of print(student) # Output: {'name': 'John',
data stored in key-value pairs. The keys are 'age': 20, 'course': 'Computer Science',
unique, and each key points to a specific 'grade': 'A'}
value. Dictionaries are widely used for Modifying an Existing Item
storing data that needs to be accessed by a You can modify the value of an existing
unique identifier. key by simply reassigning a new value to
the key.
Example:
# Creating a dictionary Example:
student = { # Modifying an existing item
"name": "John", student["age"] = 21
"age": 20, print(student) # Output: {'name': 'John',
"course": "Computer Science" 'age': 21, 'course': 'Computer Science',
} 'grade': 'A'}
21 | P a g e
print(f"Removed item: {removed_item}") Traversing: Dictionaries can be traversed
# Output: Removed item: Computer using loops to access keys, values, or key-
Science value pairs.
22 | P a g e
print(student.values()) # Output: The fromkeys() method returns a new
dict_values(['John', 20, 'Computer dictionary with keys from an iterable and
Science']) values set to a default value.
Example:
5. items() keys = ["name", "age", "course"]
The items() method returns a view object default_value = "Not Available"
that displays all the key-value pairs in the student = dict.fromkeys(keys,
dictionary. default_value)
print(student) # Output: {'name': 'Not
Example: Available', 'age': 'Not Available', 'course':
print(student.items()) # Output: 'Not Available'}
dict_items([('name', 'John'), ('age', 20),
('course', 'Computer Science')]) 11. copy()
6. get() The copy() method returns a shallow copy
The get() method returns the value of the dictionary.
associated with the key. If the key is not Example:
found, it returns None (or a specified new_student = student.copy()
default value). print(new_student) # Output: {'name':
'John', 'age': 21, 'course': 'Computer
Example: Science'}
print(student.get("age")) # Output: 20
print(student.get("address", "Not 12. pop()
Available")) # Output: Not Available The pop() method removes the key-value
7. update() pair associated with the given key and
The update() method updates the returns the value.
dictionary with key-value pairs from Example:
another dictionary or from an iterable of age = student.pop("age")
key-value pairs. print(age) # Output: 21
Example: print(student) # Output: {'name': 'John',
student.update({"age": 21, "grade": "A"}) 'course': 'Computer Science'}
print(student) # Output: {'name': 'John',
'age': 21, 'course': 'Computer Science', 13. popitem()
'grade': 'A'} The popitem() method removes and
returns an arbitrary key-value pair from the
8. del dictionary.
The del statement is used to delete a key-
value pair from the dictionary. Example:
Example: item = student.popitem()
del student["grade"] print(item) # Output: ('course', 'Computer
print(student) # Output: {'name': 'John', Science')
'age': 21, 'course': 'Computer Science'} print(student) # Output: {'name': 'John'}
23 | P a g e
course = student.setdefault("course",
"Computer Science") Syntax:
print(course) # Output: Computer Science from <module> import
<function/variable>
24 | P a g e
print(math.pi) # ********************
3.141592653589793
print(math.sqrt(16)) # 4.0
print(math.ceil(4.2)) # 5
print(math.floor(4.7)) # 4
print(math.pow(2, 3)) # 8.0
print(math.fabs(-7)) # 7.0
print(math.sin(math.pi/2)) # 1.0
2. random Module
The random module is used to generate
random numbers.
random.random(): Returns a
random float number between 0
and 1.
random.randint(a, b): Returns a
random integer between a and b
(inclusive).
random.randrange(start, stop,
step): Returns a randomly selected
element from the range start to
stop, with an optional step.
Example:
import random
print(random.random()) # Random float
between 0 and 1
print(random.randint(1, 10)) # Random
integer between 1 and 10
print(random.randrange(0, 100, 5)) #
Random number between 0 and 100, with
a step of 5
3. statistics Module
The statistics module provides functions
for calculating statistical measures.
statistics.mean(): Returns the
mean (average) of a list of
numbers.
statistics.median(): Returns the
median of a list of numbers.
statistics.mode(): Returns the
mode of a list of numbers (most
common value).
Example:
import statistics
25 | P a g e