0% found this document useful (0 votes)
5 views

Class-11-Preview of Python Notes

The document provides an overview of computational thinking and programming concepts for Class XI Computer Science, including problem-solving steps, algorithm representation, and an introduction to Python programming. It covers topics such as debugging, coding, data types, operators, and execution modes in Python. Additionally, it explains the importance of comments, mutable and immutable data types, and various operators used in Python.

Uploaded by

prafulla gouda
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Class-11-Preview of Python Notes

The document provides an overview of computational thinking and programming concepts for Class XI Computer Science, including problem-solving steps, algorithm representation, and an introduction to Python programming. It covers topics such as debugging, coding, data types, operators, and execution modes in Python. Additionally, it explains the importance of comments, mutable and immutable data types, and various operators used in Python.

Uploaded by

prafulla gouda
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

CLASS-XI

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

variable operator= value 3. Multiplication (*=)


x = 4
x *= 2 # Same as x = x * 2
Types of Augmented Assignment print(x) # Output: 8
Operators with Examples
Equivalent 4. Division (/=)
Operator Description Example x = 10
To
x /= 2 # Same as x = x / 2
x += 3 print(x) # Output: 5.0
Add and x = x +
+= →x =
assign y
x + 3 5. Floor Division (//=)
x -= 3 x = 15
Subtract and x = x - x //= 4 # Same as x = x // 4
-= →x =
assign y print(x) # Output: 3
x - 3
x *= 3
Multiply and x = x * 6. Modulus (%=)
*= →x =
assign y x = 10
x * 3 x %= 3 # Same as x = x % 3
x /= 3 print(x) # Output: 1
Divide and x = x /
/= →x =
assign y
x / 3 7. Exponentiation (**=)
x //= x = 2
Floor divide x = x // x **= 3 # Same as x = x ** 3
//= 3→x =
and assign y print(x) # Output: 8
x // 3
x %= 3 8. Bitwise AND (&=)
Modulus and x = x %
%= →x = x = 5 # Binary: 101
assign y
x % 3 x &= 3 # Binary: 011
x **= print(x) # Output: 1
Exponentiate x = x **
**= 3→x =
and assign y 9. Left Shift (<<=)
x ** 3
x = 3 # Binary: 0011
x &= 3 x <<= 2 # Shift left by 2 places
Bitwise AND x = x &
&= →x = print(x) # Output: 12 (Binary:
and assign y
x & 3 1100)
Bitwise OR
` =` `x = x Expressions, Statements, Type
and assign
x ^= 3 Conversion, and Input/Output in
Bitwise XOR x = x ^ Python
^= →x =
and assign y
x ^ 3
x <<= 1. Precedence of Operators
Left shift and x = x << Operator precedence determines the order
<<= 2→x =
assign y
x << 2 in which operations are performed in an
x >>= expression. Operators with higher
Right shift x = x >>
>>= 2→x = precedence are evaluated first.
and assign y
x >> 2
Precedence
Operator Description
(High to Low)
Examples
1. Addition (+=) () Parentheses Highest
x = 5 ** Exponentiation
x += 3 # Same as x = x + 3
print(x) # Output: 8 Multiplication,
*, /, //, %
Division, etc.
2. Subtraction (-=)
x = 10 Addition,
+, -
x -= 4 # Same as x = x - 4 Subtraction

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)

1. Syntax Errors 3. Run-time Errors


 What Are They?  What Are They?
These occur when Python's syntax These occur during program
rules are violated. The interpreter execution and cause the program to
cannot parse the code and stops crash. They are often caused by
execution. invalid operations, such as dividing
 Common Causes: by zero or accessing an undefined
o Missing colons (:) after variable.
control structures.  Common Causes:
o Improper indentation. o Invalid input or operations.
o Mismatched parentheses, o File not found or other
brackets, or quotes. input/output errors.
o Misspelled keywords. o Resource-related issues
Example: (e.g., memory errors).
# Syntax error: Missing colon Example:
if x > 5 # Run-time error: Division by zero
print("x is greater than 5") num = 10
Fix: Ensure the code adheres to Python's denom = 0
syntax rules. result = num / denom # Raises
if x > 5: ZeroDivisionError
print("x is greater than 5") Fix: Handle run-time errors using
exception handling (try-except).
2. Logical Errors try:
 What Are They? num = 10
These occur when the program denom = 0
runs without crashing but produces result = num / denom
incorrect results. Logical errors are except ZeroDivisionError:
mistakes in the program's logic or print("Error: Cannot divide by zero.")
algorithm.
 Common Causes: Key Differences Between Errors
o Using incorrect formulas or Error When It
conditions. Result Detection
Type Occurs
o Off-by-one errors in loops.
o Wrong assumptions in code
Before Detected
Program
logic. Syntax program by Python
does not
Example: Error execution interpreter
run.
# Logical error: Incorrect calculation . .
def calculate_area(length, width):

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.

Example: 1. for Loop


for num in range(5): The for loop is used when the number of
if num == 3: iterations is known or predetermined. It
continue # Skip the current iteration iterates over a sequence (like a list, tuple,
when num is 3 string, or range) and executes the block of
print(num) code for each item in the sequence.
Output: Syntax:
0 for variable in sequence:
1 # Code to execute for each item in
2 sequence
4
Example:
Summary Table: for i in range(5):

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]

Lists in Python c. Membership


A list in Python is a collection of ordered, You can check if an item exists in a list
mutable, and indexed items. Lists are using the in and not in operators.
enclosed in square brackets ([ ]) and can
contain elements of different data types, Example:
such as integers, strings, and even other list1 = [1, 2, 3, 4, 5]
lists. print(3 in list1) # Output: True
print(6 not in list1) # Output: True
1. Introduction to Lists

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

5. Built-in Functions/Methods for Lists g. index()


a. len() Returns the index of the first occurrence of
Returns the number of elements in the list. an element.
Example: Example:
list1 = [10, 20, 30, 40]
list1 = [1, 2, 3, 4] print(list1.index(30)) # Output: 2
print(len(list1)) # Output: 4
h. remove()
b. list() Removes the first occurrence of a specified
Converts other iterables (like tuples or element.
strings) into a list.
Example: Example:
tuple1 = (1, 2, 3) list1 = [1, 2, 3, 4]
list1 = list(tuple1) list1.remove(3)
print(list1) # Output: [1, 2, 3] print(list1) # Output: [1, 2, 4]

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

Example: Tuples in Python


Introduction:
list1 = [1, 2, 3, 4] A tuple is an ordered collection of
list1.reverse() elements, similar to a list, but with one key
print(list1) # Output: [4, 3, 2, 1] difference: tuples are immutable. This
means once a tuple is created, its elements
k. sort() cannot be changed, added, or removed.
Sorts the list in ascending order (can be Tuples are defined by enclosing elements in
reversed with the reverse=True argument). parentheses ().
Indexing:
Example: Tuples allow access to their elements
list1 = [3, 1, 4, 2] through indexing, starting from index 0.
list1.sort() Example:
print(list1) # Output: [1, 2, 3, 4] t = (10, 20, 30)
print(t[0]) # Output: 10
l. sorted() print(t[2]) # Output: 30
Returns a new sorted list, leaving the
original list unchanged. Tuple Operations:
1. Concatenation:
Example: o Concatenating two or more
list1 = [3, 1, 4, 2] tuples combines them into a
new_list = sorted(list1) single tuple.
print(new_list) # Output: [1, 2, 3, 4] t1 = (1, 2, 3)
t2 = (4, 5)
m. min() result = t1 + t2 # Concatenates t1
Returns the smallest element in the list. and t2
print(result) # Output: (1, 2, 3, 4,
Example: 5)
list1 = [10, 20, 30]
print(min(list1)) # Output: 10 2. Repetition:
o Repeating a tuple multiple
n. max() times.
Returns the largest element in the list. t = (1, 2)
Example: result = t * 3 # Repeats the tuple 3
list1 = [10, 20, 30] times
print(max(list1)) # Output: 30 print(result) # Output: (1, 2, 1, 2,
o. sum() 1, 2)
Returns the sum of all elements in the list.
3. Membership:
Example:
o Check if an element is
list1 = [1, 2, 3, 4]
present in the tuple.
print(sum(list1)) # Output: 10
t = (1, 2, 3, 4)
print(3 in t) # Output: True
6. Nested Lists

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

print(student) # Output: {'name': 'John', Removing Items


'age': 20, 'course': 'Computer Science'} You can remove a key-value pair using the
del statement or the pop() method.
Accessing Items in a Dictionary Using
Keys Example using del:
You can access the values in a dictionary # Removing an item
using their respective keys. The value is del student["grade"]
retrieved by referring to the key inside print(student) # Output: {'name': 'John',
square brackets [] or by using the get() 'age': 21, 'course': 'Computer Science'}
method.
Example using pop():
Example: # Removing an item using pop()
# Accessing items using keys removed_item = student.pop("course")
print(student["name"]) # Output: John print(student) # Output: {'name': 'John',
print(student["age"]) # Output: 20 'age': 21}

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.

Traversing a Dictionary Built-in Functions/Methods for


To traverse (or iterate) through a Dictionaries
dictionary, you can use various methods, Python provides several built-in functions
such as looping through keys, values, or and methods for working with dictionaries.
both key-value pairs. Below is a detailed explanation of some
Looping through keys commonly used methods and functions:
You can loop through the dictionary’s
keys by using for loop directly on the
dictionary or using the keys() method.
1. len()
Example: The len() function returns the number of
# Looping through keys items (key-value pairs) in the dictionary.
for key in student:
print(key) Example:
Output: student = {"name": "John", "age": 20,
name "course": "Computer Science"}
age print(len(student)) # Output: 3

Alternatively, using keys(): 2. dict()


# Looping through keys using keys() The dict() function creates a new
for key in student.keys(): dictionary. It can take a sequence of key-
print(key) value pairs or keyword arguments.

Looping through values Example:


You can loop through the dictionary’s # Using sequence of key-value pairs
values using the values() method. student = dict(name="John", age=20,
course="Computer Science")
Example: print(student) # Output: {'name': 'John',
# Looping through values 'age': 20, 'course': 'Computer Science'}
for value in student.values():
print(value) 3. keys()
Output: The keys() method returns a view object
John that displays all the keys in the dictionary.
21
Example:
Looping through key-value pairs student = {"name": "John", "age": 20,
You can loop through both keys and "course": "Computer Science"}
values using the items() method. print(student.keys()) # Output:
dict_keys(['name', 'age', 'course'])
Example:
# Looping through key-value pairs 4. values()
for key, value in student.items(): The values() method returns a view object
print(f"{key}: {value}") that displays all the values in the
Output: dictionary.
name: John
age: 21 Example:

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

9. clear() 14. setdefault()


The clear() method removes all items from The setdefault() method returns the value of
the dictionary. the specified key if the key is in the
Example: dictionary. If the key is not in the
student.clear() dictionary, it inserts the key with a specified
print(student) # Output: {} default value.

10. fromkeys() Example:


python

23 | P a g e
course = student.setdefault("course",
"Computer Science") Syntax:
print(course) # Output: Computer Science from <module> import
<function/variable>

15. max(), min(), sorted() Example:


The max() and min() functions return the from math import sqrt, pi
highest and lowest values in the dictionary, print(sqrt(16)) # Using the sqrt()
respectively, based on keys. function from the math module
print(pi) # Using the 'pi'
Example: constant
student_ages = {"John": 20, "Alice": 22,
"Bob": 19} 3. Importing a Module with an
print(max(student_ages)) # Output: 'John' Alias
(based on lexicographical order of keys) You can assign an alias to a
print(min(student_ages)) # Output: 'Alice' module to make it easier to use.
print(sorted(student_ages)) # Output:
['Alice', 'Bob', 'John'] Syntax:
import <module> as <alias>
Introduction to Python Modules
In Python, a module is a file containing Example:
Python code that can define functions, import math as m
classes, and variables, or include runnable print(m.sqrt(25)) # Using the math
code. Modules allow you to organize and module with alias 'm'
reuse code efficiently. Python has a rich
standard library of modules that provide Common Python Modules
built-in functionality for various tasks, such 1. math Module
as mathematical operations, random The math module provides mathematical
number generation, and statistical analysis. functions and constants.
To use the functionality provided by a  math.pi: The mathematical
module, you need to import the module constant π (pi).
into your program.  math.e: The mathematical constant
Importing Modules in Python e.
There are several ways to import modules  math.sqrt(): Returns the square
in Python: root of a number.
1. Importing an Entire Module  math.ceil(): Returns the smallest
You can import an entire module integer greater than or equal to a
using the import statement. number.
Syntax:  math.floor(): Returns the largest
import <module> integer less than or equal to a
number.
Example:  math.pow(): Returns the value of
import math the first number raised to the power
print(math.pi) # Accessing the 'pi' of the second number.
constant from the math module  math.fabs(): Returns the absolute
value of a number.
2. Importing Specific Functions or  math.sin(), math.cos(),
Variables from a Module math.tan(): Trigonometric
You can use the from keyword to functions that return the sine,
import specific functions, cosine, and tangent of a number.
variables, or classes from a Example:
module. import math

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

data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


print(statistics.mean(data)) # Output: 5.5
(average)
print(statistics.median(data)) # Output:
5.5 (middle value)
print(statistics.mode([1, 2, 2, 3, 3, 3])) #
Output: 3 (most common value)

25 | P a g e

You might also like