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

Python Sem- Answer's

The document provides an overview of programming languages, their types, and language translators, including compilers and interpreters. It explains key concepts such as algorithms, flowcharts, and features of Python, along with the role of the Python Virtual Machine (PVM). Additionally, it covers variable definitions, comments, and keywords in Python.

Uploaded by

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

Python Sem- Answer's

The document provides an overview of programming languages, their types, and language translators, including compilers and interpreters. It explains key concepts such as algorithms, flowcharts, and features of Python, along with the role of the Python Virtual Machine (PVM). Additionally, it covers variable definitions, comments, and keywords in Python.

Uploaded by

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

Unit - 1

1. Define Programming Language. Explain different types of


programming languages.

A programming language is a formal system for instructing computers to


perform specific tasks. It is a set of rules and syntax used by programmers to
write programs that control the behavior of a machine.

Types of Programming Languages:

● Low-Level Languages:
○ Machine Language: Consists of binary code directly understood by
the computer.
○ Assembly Language: A step above machine language, uses
human-readable mnemonics.
● High-Level Languages:
○ Procedural Languages (e.g., C, Fortran): Focus on sequences of
operations (functions).
○ Object-Oriented Languages (e.g., Java, Python): Organize code into
objects and classes.
○ Functional Languages (e.g., Haskell, Lisp): Focus on mathematical
functions and immutability.
○ Scripting Languages (e.g., Python, JavaScript): Often used for
automating tasks or web development.

2. Define Language Translator. Explain different types of language


translators.

A language translator is a tool that converts code written in a high-level


programming language into a machine-readable form (binary code or
intermediate code).

Types of Language Translators:

● Compiler: Translates the entire program into machine code in one go,
which is then executed. Example: GCC for C.
● Interpreter: Translates the code line by line and executes it immediately,
without generating a separate machine code file. Example: Python
interpreter.
● Assembler: Translates assembly language into machine code.

3. Differentiate Compiler and Interpreter.

Feature Compiler Interpreter

Translation Translates the entire source Translates and executes line


Process code at once. by line.

Execution Execution happens after the Execution happens


entire code is compiled. immediately after
translation.

Speed Faster execution after Slower execution due to


compilation. line-by-line translation.

Error Reports errors after Reports errors line by line


Detection compilation. during execution.

4. A. With an example explain Problem Analysis Chart (PAC)?

A Problem Analysis Chart (PAC) is a visual representation of a problem broken


down into its components, identifying inputs, processes, and outputs.

Example of PAC for summing two numbers:

● Input: Two numbers (e.g., 5, 10)


● Process: Add the numbers.
● Output: Sum (e.g., 15)

B. Define an algorithm. Design an algorithm that finds the sum of n natural


numbers.

An algorithm is a step-by-step procedure for solving a problem.

Algorithm to find the sum of n natural numbers:

1. Start
2. Input the value of n.
3. Initialize sum = 0.
4. For i = 1 to n, do:
○ sum = sum + i
5. Output sum.
6. End.

5. A. Define Flowchart. Explain different symbols used in flowchart.

A flowchart is a diagram that visually represents the steps in a process or


algorithm. It helps in understanding the flow of control in the program.

Symbols used in flowchart:

● Oval (Terminator): Represents the start or end of a process.


● Rectangle (Process): Represents a process or operation.
● Diamond (Decision): Represents a decision point (if-else).
● Parallelogram (Input/Output): Represents input or output.

B. Design algorithm and flowchart that finds Area and Circumference of a


Circle.

Algorithm:

1. Start
2. Input radius r.
3. Calculate area: area = π * r^2.
4. Calculate circumference: circumference = 2 * π * r.
5. Output area and circumference.
6. End.

Flowchart:

● Start → Input r → Calculate area = π * r^2 → Calculate


circumference = 2 * π * r → Output → End.

6. List and explain features of Python.

● Simple Syntax: Python is easy to read and write, making it a great choice
for beginners.
● Interpreted Language: Python code is executed line by line by the Python
interpreter.
● Object-Oriented: Python supports classes and objects for creating
reusable code.
● Dynamic Typing: Python automatically detects the type of variable, so
explicit type declarations are not needed.
● Extensive Standard Library: Python includes many built-in modules that
simplify complex tasks.
● Cross-platform: Python is available on various platforms like Windows,
Linux, and MacOS.

7. A. Define the role of PVM.

The Python Virtual Machine (PVM) is responsible for executing Python


bytecode. After Python code is compiled into bytecode by the Python compiler,
the PVM runs the bytecode on the target system, ensuring that Python is
platform-independent.

B. With a neat sketch explain steps involved in PVM.

1. Source Code: Write Python code.


2. Python Compiler: Converts the source code into bytecode.
3. Python Virtual Machine (PVM): Executes the bytecode.

8. A. Define a variable. With an example, explain the rules to define


variables.

A variable is a name used to store data values.

Rules for defining variables:

● A variable must start with a letter (A-Z or a-z) or an underscore (_).


● The rest of the variable name can contain letters, digits (0-9), and
underscores.
● Variable names are case-sensitive.

Example:

age = 25
name = "John"

B. Explain variable declaration & assignment and chained assignment with


example.
● Variable Declaration & Assignment: Assigning a value to a variable.
Example: x = 10
● Chained Assignment: Assigning the same value to multiple variables.
Example: a = b = c = 100

9. Explain about comments and docstrings in Python.

● Comments: Used to add explanatory notes to the code. It is ignored by


the interpreter. They are written using #. Example: # This is a
comment

Docstrings: Used to describe the functionality of a class, method, or function.


Enclosed in triple quotes. Example:
def add(x, y):
"""This function adds two numbers."""
return x + y

10. A. Explain about multiple assignment of variables in Python.

In Python, you can assign values to multiple variables in a single line. This is
called multiple assignment.

Example:

x, y, z = 10, 20, 30

Here, x is assigned 10, y is assigned 20, and z is assigned 30.

B. Define keyword. List different keywords in Python.

A keyword is a reserved word that cannot be used as an identifier (like variable


names) in Python. These are predefined in Python and have a special meaning.

Examples of Python keywords:

● if, else, elif


● for, while
● def, class
● True, False
● try, except
● import, from

1. Programming Language and Types:

● Definition: A programming language is a formal language designed to


communicate instructions to a computer. These instructions can create
programs that control the behavior of a computer or express algorithms.
● Types:
○ Low-Level Languages: Close to the machine's hardware.
■ Machine Language: Binary code (0s and 1s) directly
understood by the CPU.
■ Assembly Language: Uses mnemonics (short codes) to
represent machine instructions. Requires an assembler to
translate to machine code.
○ High-Level Languages: More abstract and easier for humans to
read and write. Require translators (compilers or interpreters).
■ Procedural Languages (e.g., C, Pascal): Focus on
step-by-step instructions (procedures or functions).
■ Object-Oriented Languages (e.g., Java, Python, C++):
Organize code around objects, which combine data and
methods.
■ Scripting Languages (e.g., Python, JavaScript, Perl): Often
interpreted, used for automating tasks, web development,
etc.
■ Declarative Languages (e.g., SQL, Prolog): Focus on what
result is desired rather than how to achieve it.

2. Language Translator and Types:

● Definition: A language translator converts code written in one


programming language into another language (often machine code) that a
computer can understand.
● Types:
○ Assembler: Translates assembly language into machine code.
○ Compiler: Translates an entire high-level program into machine
code at once, creating an executable file.
○ Interpreter: Translates and executes a high-level program line by
line.

3. Compiler vs. Interpreter:

Feature Compiler Interpreter

Translation Translates the entire Translates and executes line by


program at once line

Execution Creates an executable file Executes directly without


that runs later creating an executable

Error Errors are reported after Errors are reported line by line
Checking compilation during execution

Speed Generally faster execution Generally slower execution

Example C, C++, Java Python, JavaScript, Ruby

Export to Sheets

4. Problem Analysis Chart (PAC) and Algorithm:

● A. PAC Example (Finding the largest of two numbers):

Input Process Output

Number 1 1. Input a and b Largest


(a) Number
Number 2 2. If a > b, then largest
(b) =a

3. Else largest = b

4. Output largest

Export to Sheets

● B. Algorithm Definition: A well-defined, step-by-step procedure for


solving a problem.
● Algorithm for sum of n natural numbers:
1. Input n
2. Initialize sum = 0
3. For i from 1 to n: a. sum = sum + i
4. Output sum

5. Flowchart and Example:

● A. Flowchart Definition: A graphical representation of an algorithm using


symbols.

● Flowchart Symbols:

○ Oval: Start/End
○ Rectangle: Process/Instruction
○ Diamond: Decision/Condition
○ Parallelogram: Input/Output
○ Arrow: Flow of control
● B. Algorithm and Flowchart for Area and Circumference of a circle:

○ Algorithm:

1. Input radius (r)


2. Area = pi * r * r
3. Circumference = 2 * pi * r
4. Output Area and Circumference
○ (Flowchart would be a visual representation of these steps using
the symbols mentioned above. I can't draw a flowchart here, but
imagine ovals for start/end, a parallelogram for input, rectangles
for the calculations, and another parallelogram for output.)

6. Features of Python:

● Easy to learn and read: Simple syntax, resembles English.


● Interpreted: Executes code line by line.
● Dynamically typed: Variable types are checked at runtime.
● High-level: Abstracted from low-level details.
● Object-oriented: Supports object-oriented programming.
● Large standard library: Provides many built-in modules for various tasks.
● Cross-platform: Runs on different operating systems.

7. Python Virtual Machine (PVM):

● A. Role: The PVM is an interpreter that executes Python bytecode


(intermediate code generated after compilation). It provides platform
independence by running the same bytecode on different operating
systems.
● B. Steps in PVM:
1. Compilation: Python source code (.py) is compiled into bytecode
(.pyc or .pyo).
2. Bytecode Execution: The PVM executes the bytecode.

(A neat sketch would show the .py file going into the compiler, producing
.pyc/.pyo, which then goes into the PVM for execution.)

8. Variables:

● A. Definition: A named storage location in memory that holds a value.

● Rules for defining variables:

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


○ Can contain letters, numbers (0-9), and underscores.
○ Case-sensitive (e.g., myVar and myvar are different).
○ Cannot be a Python keyword.
● Example: my_variable = 10

● B. Variable Declaration & Assignment: In Python, declaration and


assignment happen simultaneously. x = 5 creates a variable x and
assigns the value 5 to it.

● Chained Assignment: Assigning the same value to multiple variables in


one line. a = b = c = 10 assigns 10 to a, b, and c.

9. Comments and Docstrings:

● Comments: Used to explain code. Ignored by the interpreter.


○ Single-line: # This is a comment
○ Multi-line: '''This is a multi-line comment''' or """This
is also a multi-line comment"""
● Docstrings: Documentation strings used to document functions, classes,
and modules. Accessed using help() or __doc__.
○ def my_function(): """This is a docstring for
my_function.""" pass

10. Multiple Assignment and Keywords:

● A. Multiple Assignment: Assigning multiple values to multiple variables in


one line. x, y, z = 1, 2, 3 assigns 1 to x, 2 to y, and 3 to z.
● B. Keyword Definition: Reserved words in Python that have special
meanings and cannot be used as variable names.
● Some Python Keywords: and, as, assert, break, class, continue, def,
del, elif, else, except, False, finally, for, from, global, if,
import, in, is, lambda, None, nonlocal, not, or, pass, raise, return,
True, try, while, with, yield.

1. Programming Language

Definition: A programming language is a formal language comprising a set of


instructions that produce various kinds of output. Programmers use these
languages to create programs that control the behavior of machines or to
express algorithms precisely.
Types:

● High-level languages (e.g., Python, Java): These languages are


user-friendly, abstract from the hardware, and closer to human
languages.
● Low-level languages (e.g., Assembly): These languages are closer to
machine code and provide less abstraction from the hardware.

2. Language Translator

Definition: A language translator is a system software that translates a program


written in one programming language into another language.

Types:

● Compiler: Translates the entire program at once, creating an executable


file. Example: C++ compiler.
● Interpreter: Translates and executes the program line-by-line. Example:
Python interpreter.
● Assembler: Converts assembly language code into machine code.

3. Compiler vs Interpreter

Compiler:

● Translates the entire program in one go.


● Generates an executable file.
● Example: C++ compiler.

Interpreter:

● Translates and executes line-by-line.


● Doesn't create an executable file.
● Example: Python interpreter.

4. Problem Analysis Chart (PAC)

Definition: A PAC is a tool used in problem-solving to break down a problem


into four parts: input, output, processing, and additional requirements.

Example:

● Problem: Calculate the sum of two numbers.


● Input: Number1, Number2
● Output: Sum
● Processing: Sum = Number1 + Number2
● Additional Requirements: None

4B. Algorithm for Sum of n Natural Numbers

Algorithm:

1. Initialize sum to 0.
2. For i from 1 to n, add i to sum.
3. Return sum.

5. Flowchart

Definition: A flowchart is a graphical representation of a process or algorithm.

Symbols:

● Oval: Start/End
● Rectangle: Process
● Diamond: Decision
● Parallelogram: Input/Output

5B. Algorithm and Flowchart for Area and Circumference of a Circle

Algorithm:

1. Input radius.
2. Calculate area as π * radius^2.
3. Calculate circumference as 2 * π * radius.
4. Output area and circumference.

Flowchart: (Not able to draw, but imagine a flow with input, process, and output
symbols connected sequentially.)

6. Features of Python

● Easy to read and write.


● Interpreted language.
● Dynamically typed.
● Rich standard library.
● Supports multiple paradigms (e.g., procedural, object-oriented,
functional).

7. Python Virtual Machine (PVM)

Definition: The PVM is the runtime engine of Python that executes the
bytecode.

Steps:

1. Python code is compiled into bytecode.


2. Bytecode is executed by PVM.
3. PVM interacts with the operating system and hardware.

8. Variables in Python

Definition: A variable is a name that refers to a value.

Rules:

● Must start with a letter or underscore (_).


● Can contain letters, numbers, and underscores.
● Case-sensitive.

Example:

python
variable_name = 10

9. Comments and Docstrings in Python

Comments:

● Single line: # This is a comment


● Multi-line: ''' This is a multi-line comment '''

Docstrings:

● Used for documentation within the code.

python
def example():
"""This is a docstring."""
pass

10. Multiple Assignment and Keywords in Python

Multiple Assignment:

python
a, b, c = 1, 2, 3

Keywords:

● Predefined reserved words in Python like if, else, while, for, def.

Unit - 2
Here are detailed explanations and Python program solutions for the questions
provided:

1. List and explain different data types in Python.

Python has several built-in data types used to store data. Below are the primary
data types in Python:

● Numeric Types:

○ int: Represents integers (whole numbers) without a decimal point.


Example: x = 5
○ float: Represents numbers with a decimal point. Example: y =
5.67
○ complex: Represents complex numbers with a real and imaginary
part. Example: z = 3 + 5j
● Sequence Types:
○ str (string): A sequence of characters, enclosed in single or double
quotes. Example: s = "Hello"
○ list: An ordered, mutable collection of items, which can be of any
type. Example: lst = [1, 2, 3]
○ tuple: An ordered, immutable collection of items. Example: tup =
(1, 2, 3)
● Mapping Type:

○ dict (dictionary): An unordered collection of key-value pairs.


Example: d = {"name": "John", "age": 25}
● Set Types:

○ set: An unordered collection of unique elements. Example: s =


{1, 2, 3}
○ frozenset: Similar to a set, but immutable. Example: fs =
frozenset([1, 2, 3])
● Boolean Type:

○ bool: Represents True or False. Example: b = True


● Binary Types:

○ bytes: Immutable sequence of bytes. Example: b = b'hello'


○ bytearray: Mutable sequence of bytes. Example: ba =
bytearray([65, 66, 67])
○ memoryview: Provides shared memory access to other binary data
types.

2. Explain arithmetic, relational, and logical operators in Python with


examples.

Arithmetic Operators:

These operators are used to perform basic mathematical operations.

● + : Addition (e.g., 5 + 3 = 8)
● - : Subtraction (e.g., 5 - 3 = 2)
● * : Multiplication (e.g., 5 * 3 = 15)
● / : Division (e.g., 5 / 3 = 1.666)
● // : Floor Division (e.g., 5 // 3 = 1)
● % : Modulus (remainder of division) (e.g., 5 % 3 = 2)
● ** : Exponentiation (e.g., 5 ** 3 = 125)

Relational Operators:

These operators compare two values and return a boolean result (True or
False).

● == : Equal to (e.g., 5 == 5 → True)


● != : Not equal to (e.g., 5 != 3 → True)
● > : Greater than (e.g., 5 > 3 → True)
● < : Less than (e.g., 5 < 3 → False)
● >= : Greater than or equal to (e.g., 5 >= 5 → True)
● <= : Less than or equal to (e.g., 3 <= 5 → True)

Logical Operators:

These operators are used to combine conditional statements.

● and : Returns True if both conditions are true (e.g., True and False →
False)
● or : Returns True if at least one condition is true (e.g., True or False
→ True)
● not : Returns the opposite of the condition (e.g., not True → False)

3. A. Explain bitwise operators with example.

Bitwise operators perform operations on binary representations of numbers.

● & (AND): Sets each bit to 1 if both bits are 1. Example: 5 & 3 → 101 &
011 = 001 → Result is 1

● | (OR): Sets each bit to 1 if one of the bits is 1. Example: 5 | 3 → 101 |


011 = 111 → Result is 7

● ^ (XOR): Sets each bit to 1 if only one of the bits is 1. Example: 5 ^ 3 →


101 ^ 011 = 110 → Result is 6
● ~ (NOT): Inverts the bits (complement). Example: ~5 → ~0101 = -0110
→ Result is -6

● << (Left Shift): Shifts bits to the left by a specified number of positions.
Example: 5 << 1 → 0101 << 1 = 1010 → Result is 10

● >> (Right Shift): Shifts bits to the right by a specified number of positions.
Example: 5 >> 1 → 0101 >> 1 = 0010 → Result is 2

3. B. Explain identity and membership operators in Python.

Identity Operators:

These operators compare the memory locations of two objects.

is : Returns True if two variables point to the same object in memory. Example:
x = [1, 2]
y=x
print(x is y) # True

is not : Returns True if two variables do not point to the same object.
Example:
x = [1, 2]
y = [1, 2]
print(x is not y) # True

Membership Operators:

These operators test if a value is found within a sequence (e.g., list, tuple,
string).

in : Returns True if the value is present in the sequence. Example:


lst = [1, 2, 3]
print(2 in lst) # True


not in : Returns True if the value is not present in the sequence. Example:
lst = [1, 2, 3]
print(4 not in lst) # True

4. A. Explain about if-else statement.

An if-else statement in Python allows the execution of one block of code if a


condition is True, and a different block if the condition is False.

Syntax:

if condition:
# Code to execute if condition is True
else:
# Code to execute if condition is False

Example:

x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")

4. B. Write a Python program that finds the largest number among 2


numbers.
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))

if num1 > num2:


print(f"{num1} is the largest number.")
else:
print(f"{num2} is the largest number.")
5. A. Explain syntax of else-if ladder statement.

The else-if ladder is used to check multiple conditions. If the first if condition
is False, the elif condition is evaluated, and so on. If none of the conditions
are true, the else block is executed.

Syntax:

if condition1:
# Code if condition1 is true
elif condition2:
# Code if condition2 is true
else:
# Code if none of the above conditions are true

5. B. Write a Python program that finds the largest number among three
numbers.
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
num3 = int(input("Enter the third number: "))

if num1 >= num2 and num1 >= num3:


print(f"{num1} is the largest number.")
elif num2 >= num1 and num2 >= num3:
print(f"{num2} is the largest number.")
else:
print(f"{num3} is the largest number.")

6. A. Explain while statement syntax in Python.

A while loop in Python repeatedly executes a block of code as long as the given
condition is True.

Syntax:
while condition:
# Code to execute while condition is True

Example:

i=1
while i <= 5:
print(i)
i += 1

6. B. Write a Python program that prints factors of a given number.


num = int(input("Enter a number: "))
for i in range(1, num + 1):
if num % i == 0:
print(i)

7. A. Explain for statement syntax in Python.

A for loop in Python is used to iterate over a sequence (such as a list, string, or
range). It executes the block of code for each item in the sequence.

Syntax:

for item in sequence:


# Code to execute for each item

Example:

for i in range(1, 6):


print(i)

7. B. Write a Python program that finds whether the given number is


prime number or not.
num = int(input("Enter a number: "))
if num > 1:
for i in range(2, num):
if num % i == 0:
print(f"{num} is not a prime number.")
break
else:
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")

8. With an example, explain about:

A. break statement

The break statement is used to exit a loop prematurely when a certain


condition is met. It terminates the loop, even if the loop has not finished
iterating through all its elements.

Example:

for i in range(1, 6):

if i == 3:

break # Exits the loop when i equals 3

print(i)

Output:

Explanation: The loop starts at i = 1 and prints each number. When i becomes
3, the break statement is executed, and the loop stops, printing only 1 and 2.
B. continue statement

The continue statement is used to skip the current iteration of the loop and
proceed to the next iteration without executing the remaining code in the loop
for that iteration.

Example:

for i in range(1, 6):

if i == 3:

continue # Skips the iteration when i equals 3

print(i)

Output:

Explanation: The loop starts at i = 1 and prints each number. When i is 3, the
continue statement is executed, skipping the print statement for that
iteration, and the loop continues with i = 4 and i = 5.

9. A. Explain about assertions with example.

Assertions in Python are used for debugging purposes. They are used to check
if a given condition is True. If the condition is False, the program raises an
AssertionError with an optional message. Assertions can help catch bugs in
code early by validating assumptions.
Syntax:

assert condition, "Optional error message"

Example:

x=5

assert x > 0, "x should be greater than 0"

assert x < 0, "x should be less than 0" # This will raise AssertionError

Output:

AssertionError: x should be less than 0

Explanation: The first assertion checks if x is greater than 0 (which is True), so


it passes. The second assertion fails because x is not less than 0, resulting in an
AssertionError.

B. Explain about zip() function with example.

The zip() function in Python is used to combine two or more iterables (like
lists, tuples) element-wise into tuples. The result is an iterator of tuples, where
each tuple contains one element from each of the input iterables.

Syntax:

zip(iterable1, iterable2, ...)

Example:

names = ["John", "Alice", "Bob"]

ages = [25, 30, 22]


zipped = zip(names, ages)

for name, age in zipped:

print(f"{name} is {age} years old.")

Output:

John is 25 years old.

Alice is 30 years old.

Bob is 22 years old.

Explanation: The zip() function pairs the elements of names and ages in
corresponding positions to create tuples, and then the loop prints each pair.

10. A. Write a Python program that swaps 2 numbers using a temporary


variable and without using a temporary variable.

With temporary variable:

# Using a temporary variable

num1 = int(input("Enter the first number: "))

num2 = int(input("Enter the second number: "))

# Swapping using a temporary variable

temp = num1

num1 = num2
num2 = temp

print("After swapping:")

print(f"First number: {num1}")

print(f"Second number: {num2}")

Without temporary variable:

# Without using a temporary variable

num1 = int(input("Enter the first number: "))

num2 = int(input("Enter the second number: "))

# Swapping without using a temporary variable

num1, num2 = num2, num1

print("After swapping:")

print(f"First number: {num1}")

print(f"Second number: {num2}")

Explanation: In the first program, we use a temporary variable temp to hold the
value of num1 while we swap the values. In the second program, Python's
multiple assignment allows swapping without needing a temporary variable.

10. B. Write a Python program to check whether the given year is a leap
year or not.
A leap year occurs every 4 years, except for years that are divisible by 100 but
not divisible by 400.

Python program:

year = int(input("Enter a year: "))

if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):

print(f"{year} is a leap year.")

else:

print(f"{year} is not a leap year.")

Explanation:

● A year is a leap year if it is divisible by 4, but not divisible by 100, unless it


is also divisible by 400.
● The program checks these conditions using the if statement.

Example:

Enter a year: 2024

2024 is a leap year.

1. Data Types in Python:

Python has several built-in data types:

● Numeric:
○ int: Integers (e.g., 10, -5, 0).
○ float: Floating-point numbers (e.g., 3.14, -2.5, 0.0).
○ complex: Complex numbers (e.g., 2 + 3j).
● Sequence:
○ str: Strings (e.g., "hello", 'Python'). Immutable.
○ list: Ordered, mutable sequences (e.g., [1, 2, "apple"]).
○ tuple: Ordered, immutable sequences (e.g., (1, 2, "apple")).
○ range: Generates a sequence of numbers (e.g., range(10)).
● Set: Unordered collections of unique elements (e.g., {1, 2, 3}). Mutable.
● Mapping:
○ dict: Dictionaries (key-value pairs) (e.g., {"name": "Alice", "age": 30}).
Mutable.
● Boolean:
○ bool: True or False.

2. Operators in Python:

● Arithmetic Operators: + (addition), - (subtraction), * (multiplication), /


(division), // (floor division), % (modulus), ** (exponentiation).
○ Example: 10 + 5 = 15, 10 / 3 = 3.333..., 10 // 3 = 3, 10
% 3 = 1, 2 ** 3 = 8.


● Relational Operators (Comparison Operators): == (equal to), != (not equal
to), > (greater than), < (less than), >= (greater than or equal to), <= (less
than or equal to).
○ Example: 5 > 3 (True), 10 == 10 (True), 7 != 9 (True).

● Logical Operators: and (returns True if both operands are True), or
(returns True if at least one operand is True), not (inverts the operand's
boolean value).
○ Example: (5 > 3) and (2 < 4) (True), (5 < 3) or (2 < 4)
(True), not (5 < 3) (True).

3. Bitwise, Identity, and Membership Operators:

● A. Bitwise Operators: Operate on individual bits of integers. & (AND), |


(OR), ^ (XOR), ~ (NOT), << (left shift), >> (right shift).
○ Example: 5 & 3 (0101 & 0011 = 0001 = 1), 5 | 3 (0101 | 0011 = 0111 =
7).
● B. Identity Operators: Check if two operands refer to the same object in
memory. is, is not.
○ Example: x = [1, 2]; y = x; x is y (True), x = [1, 2]; y
= [1, 2]; x is y (False).
● Membership Operators: Check if a value is present in a sequence. in, not
in.
○ Example: 3 in [1, 2, 3] (True), "a" in "apple" (True).

4. if-else Statement:

● A. Explanation: Executes a block of code if a condition is True, and


another block if the condition is False.
● B. Largest of Two Numbers:

Python

num1 = int(input("Enter first number: "))

num2 = int(input("Enter second number: "))

if num1 > num2:

print(num1, "is the largest")

else:

print(num2, "is the largest")

5. elif (else-if) Ladder:

● A. Syntax: Used for multiple conditions.


● B. Largest of Three Numbers:

Python

num1 = int(input("Enter first number: "))

num2 = int(input("Enter second number: "))

num3 = int(input("Enter third number: "))


if num1 >= num2 and num1 >= num3:

largest = num1

elif num2 >= num1 and num2 >= num3:

largest = num2

else:

largest = num3

print("The largest number is", largest)

6. while Loop:

● A. Syntax: Repeats a block of code as long as a condition is True.


● B. Factors of a Number:

Python

num = int(input("Enter a number: "))

i=1

print("Factors of", num, "are:")

while i <= num:

if num % i == 0:

print(i)

i += 1

7. for Loop:

● A. Syntax: Iterates over a sequence.


● B. Prime Number Check:
Python

num = int(input("Enter a number: "))

if num > 1:

for i in range(2, int(num**0.5) + 1):

if num % i == 0:

print(num, "is not a prime number")

break

else: # This 'else' is associated with the 'for' loop

print(num, "is a prime number")

else:

print(num, "is not a prime number")

8. break and continue Statements:

● A. break: Terminates the loop.


● B. continue: Skips the current iteration.

Python

# break example

for i in range(1, 6):

if i == 3:

break

print(i) # Output: 1 2
# continue example

for i in range(1, 6):

if i == 3:

continue

print(i) # Output: 1 2 4 5

9. Assertions and zip():

● A. Assertions: Used for debugging.

Python

def divide(x, y):

assert y != 0, "Cannot divide by zero"

return x / y

result = divide(10, 2) # Works fine

print(result) # Output: 5.0

#result = divide(10, 0) # Raises AssertionError

● B. zip(): Aggregates elements from iterables.

Python

names = ["Alice", "Bob"]

ages = [25, 30]

cities = ["New York", "London"]


for name, age, city in zip(names, ages, cities):

print(f"{name} is {age} years old and lives in {city}")

# Output:

# Alice is 25 years old and lives in New York

# Bob is 30 years old and lives in London

10. Swapping Numbers and Leap Year Check:

● A. Swapping Numbers:

Python

# Using a temporary variable:

a = 10

b = 20

temp = a

a=b

b = temp

print("a =", a, "b =", b)

# Without a temporary variable:

a = 10

b = 20

a, b = b, a # Pythonic swap

print("a =", a, "b =", b)

● B. Leap Year Check:


Python

def is_leap_year(year):

if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:

return True

return False

year = int(input("Enter a year: "))

if is_leap_year(year):

print(year, "is a leap year")

else:

print(year, "is not a leap year")

1. Different Data Types in Python

int: Integer values.


python
a = 10

float: Floating-point numbers.


python
b = 10.5

str: String literals.


python
c = "Hello"


list: Ordered sequence of elements.
python
d = [1, 2, 3]

tuple: Ordered, immutable sequence of elements.


python
e = (1, 2, 3)

dict: Key-value pairs.


python
f = {"name": "Alice", "age": 25}

set: Unordered collection of unique elements.


python
g = {1, 2, 3}

bool: Boolean values.


python
h = True

2. Operators in Python

● Arithmetic Operators:
○ Addition: +
○ Subtraction: -
○ Multiplication: *
○ Division: /

Example:
python
a = 10

b=5
c = a + b # 15


● Relational Operators:
○ Equal to: ==
○ Not equal to: !=
○ Greater than: >
○ Less than: <

Example:
python
a = 10

b=5

result = (a > b) # True


● Logical Operators:
○ And: and
○ Or: or
○ Not: not

Example:
python
a = True

b = False

result = a and b # False

3. Operators

● A. Bitwise Operators:
○ AND: &
○ OR: |
○ XOR: ^
○ NOT: ~
Example:
python
a = 5 # 0101 in binary

b = 3 # 0011 in binary

c = a & b # 0001 (1 in decimal)


● B. Identity and Membership Operators:
○ Identity Operators:
■ is
■ is not

Example:
python
a = [1, 2, 3]

b = [1, 2, 3]

print(a is b) # False


○ Membership Operators:
■ in
■ not in

Example:
python
a = [1, 2, 3]

print(1 in a) # True

4. Control Statements

A. if-else Statement:
python
a = 10

if a > 5:
print("Greater")

else:

print("Lesser")

B. Python Program to Find Largest Number Among 2 Numbers:


python
a = 10

b = 20

if a > b:

largest = a

else:

largest = b

print("Largest:", largest)

5. else-if Ladder

A. Syntax of else-if Ladder:


python
a = 10

if a == 10:

print("Equal to 10")

elif a > 10:

print("Greater than 10")

else:

print("Less than 10")


B. Python Program to Find Largest Number Among 3 Numbers:
python
a = 10

b = 20

c = 15

if a > b and a > c:

largest = a

elif b > a and b > c:

largest = b

else:

largest = c

print("Largest:", largest)

6. while Statement

A. Syntax of while Statement:


python
i=1

while i <= 5:

print(i)

i += 1

B. Python Program to Print Factors of a Given Number:


python
num = 12

for i in range(1, num + 1):

if num % i == 0:
print(i)

7. for Statement

A. Syntax of for Statement:


python
for i in range(5):

print(i)

B. Python Program to Find Whether a Number is Prime or Not:


python
num = 29

is_prime = True

for i in range(2, num):

if num % i == 0:

is_prime = False

break

if is_prime:

print(num, "is a prime number")

else:

print(num, "is not a prime number")

8. break and continue Statements

A. break Statement:
python
for i in range(10):

if i == 5:
break

print(i)

B. continue Statement:
python
for i in range(10):

if i == 5:

continue

print(i)

9. Assertions and zip() Function

A. Assertions:
python
assert 2 + 2 == 4 # This will pass

assert 2 + 2 == 5 # This will raise an AssertionError

B. zip() Function:
python
a = [1, 2, 3]

b = ['a', 'b', 'c']

zipped = zip(a, b)

print(list(zipped)) # [(1, 'a'), (2, 'b'), (3, 'c')]

10. Python Programs

A. Swap 2 Numbers Using and Without Using Temporary Variable:


python
# Using temporary variable
a=5

b = 10

temp = a

a=b

b = temp

# Without using temporary variable

a, b = b, a

print(a, b)

B. Check Whether the Given Year is a Leap Year or Not:


python
year = 2024

if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):

print(year, "is a leap year")

else:

print(year, "is not a leap year")

Here are detailed explanations and examples for each of your requested topics:

1. Explain creating, indexing, and slicing of string with example.

Creating a String: You can create a string by enclosing characters in either


single quotes (') or double quotes (").
Example:

my_string = "Hello, World!"

Indexing: Strings in Python are indexed starting from 0. You can access a
character at a specific index using square brackets.

Example:

my_string = "Hello"

print(my_string[1]) # Output: 'e' (index 1 refers to 'e')

Slicing: You can extract a portion of the string using slicing with the syntax
string[start:end]. The start index is included, but the end index is not.

Example:

my_string = "Hello, World!"

print(my_string[0:5]) # Output: 'Hello'

2. With example, explain the following string methods:

A. replace()

The replace() method replaces a specified substring with another substring


in the given string.

Example:

text = "Hello, World!"

new_text = text.replace("World", "Python")

print(new_text) # Output: "Hello, Python!"


B. upper()

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

Example:

text = "hello"

print(text.upper()) # Output: "HELLO"

D. find()

The find() method returns the index of the first occurrence of the specified
substring. If the substring is not found, it returns -1.

Example:

text = "Hello, World!"

print(text.find("World")) # Output: 7

print(text.find("Python")) # Output: -1

3. With example, explain the following string methods:

A. lower()

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

Example:

text = "HELLO"

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

B. join()
The join() method is used to join a sequence of strings using a specified
delimiter.

Example:

words = ["Hello", "world", "Python"]

result = " ".join(words) # Joins the words with a space in between

print(result) # Output: "Hello world Python"

D. partition()

The partition() method splits the string into a tuple of three parts: the
substring before the separator, the separator itself, and the substring after the
separator.

Example:

text = "Hello, World!"

result = text.partition(",")

print(result) # Output: ('Hello', ',', ' World!')

4. Explain creating, indexing, and slicing of list with example.

Creating a List: A list can be created by placing elements inside square brackets
[].

Example:

my_list = [1, 2, 3, 4, 5]

Indexing: Lists are indexed starting from 0. You can access elements using the
index.
Example:

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

print(my_list[2]) # Output: 30

Slicing: You can slice a list to extract a part of it using the syntax
list[start:end].

Example:

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

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

5. With example, explain the following list methods:

A. insert()

The insert() method is used to add an element at a specific index in the list.

Example:

my_list = [1, 2, 3]

my_list.insert(1, 10) # Inserts 10 at index 1

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

B. clear()

The clear() method removes all items from the list.

Example:

my_list = [1, 2, 3]
my_list.clear()

print(my_list) # Output: []

C. pop()

The pop() method removes and returns the element at a specified index. If no
index is provided, it removes the last element.

Example:

my_list = [1, 2, 3]

popped_item = my_list.pop(1) # Removes and returns the element at index 1

print(popped_item) # Output: 2

print(my_list) # Output: [1, 3]

D. sort()

The sort() method sorts the list in ascending order by default. You can specify
the reverse=True argument to sort in descending order.

Example:

my_list = [3, 1, 2, 4]

my_list.sort()

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

6. Explain creating, indexing, and slicing of tuple with example.

Creating a Tuple: A tuple is created by placing elements inside parentheses ().

Example:
my_tuple = (1, 2, 3)

Indexing: Tuples are indexed starting from 0. You can access tuple elements
using the index.

Example:

my_tuple = (10, 20, 30)

print(my_tuple[1]) # Output: 20

Slicing: You can slice a tuple to extract a portion of it using the syntax
tuple[start:end].

Example:

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

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

7. A. Define Tuple and list the properties of Tuple.

● Tuple: A tuple is an immutable ordered collection of items. It can contain


elements of different types (int, string, float, etc.).

Properties of a Tuple:

● Immutable: Once created, you cannot change the elements of a tuple.


● Ordered: The elements of a tuple are ordered, meaning they have a
specific sequence.
● Allow duplicates: A tuple can have multiple occurrences of the same
element.
● Supports indexing, slicing, and iteration.
B. With example, explain count() and index() methods with tuple.

● count(): Returns the number of occurrences of an element in a tuple.


● index(): Returns the index of the first occurrence of an element in a tuple.

Example:

my_tuple = (10, 20, 30, 20, 40)

# count() example

print(my_tuple.count(20)) # Output: 2

# index() example

print(my_tuple.index(30)) # Output: 2

8. A. Define set and list the properties of set.

● Set: A set is an unordered collection of unique elements. Sets are


mutable, meaning you can add or remove elements, but they do not
maintain any specific order.

Properties of a Set:

● Unordered: Sets do not maintain order.


● Mutable: You can add or remove elements.
● No duplicates: A set does not allow duplicate elements.
● Supports mathematical operations: You can perform union, intersection,
and other set operations.

B. With example, explain add(), remove(), discard() methods with set.

● add(): Adds an element to the set.


● remove(): Removes an element from the set. If the element is not found, it
raises a KeyError.
● discard(): Removes an element from the set, but does not raise an error if
the element is not found.

Example:

my_set = {1, 2, 3}

# add() example

my_set.add(4)

print(my_set) # Output: {1, 2, 3, 4}

# remove() example

my_set.remove(3)

print(my_set) # Output: {1, 2, 4}

# discard() example

my_set.discard(2)

print(my_set) # Output: {1, 4}

9. With example, explain the following set methods:

A. union()

The union() method returns a new set containing all the elements from both
sets, excluding duplicates.

Example:

set1 = {1, 2, 3}
set2 = {3, 4, 5}

result = set1.union(set2)

print(result) # Output: {1, 2, 3, 4, 5}

B. intersection()

The intersection() method returns a new set containing only the common
elements from both sets.

Example:

set1 = {1, 2, 3}

set2 = {3, 4, 5}

result = set1.intersection(set2)

print(result) # Output: {3}

C. difference()

The difference() method returns a new set containing elements in the first
set that are not in the second set.

Example:

set1 = {1, 2, 3}

set2 = {3, 4, 5}

result = set1.difference(set2)

print(result) # Output: {1, 2}

D. isdisjoint()

The isdisjoint() method checks if two sets have no elements in common


and returns True if they do not have any intersection.
Example:

set1 = {1, 2, 3}

set2 = {4, 5, 6}

print(set1.isdisjoint(set2)) # Output: True

10. Differentiate between list and tuple.

Feature List Tuple

Mutability Mutable (can be changed) Immutable (cannot be


changed)

Syntax [] (square brackets) () (parentheses)

Methods Supports many methods like Supports fewer methods like


append(), remove(), etc. count(), index()

Performan Slower due to mutability Faster due to immutability


ce

1. String Creation, Indexing, and Slicing:

● Creation: Strings are created using single quotes ('...'), double quotes
("..."), or triple quotes ('''...''' or """...""" for multi-line
strings).
○ my_string = "Hello, Python!"
● Indexing: Accessing individual characters using their position (index),
starting from 0.
○ my_string[0] (returns 'H')
○ my_string[7] (returns 'P')
○ my_string[-1] (returns '!') (negative indexing starts from the end)
● Slicing: Extracting a substring.
○ my_string[0:5] (returns 'Hello') (from index 0 up to, but not
including, index 5)
○ my_string[7:] (returns 'Python!') (from index 7 to the end)
○ my_string[:5] (returns 'Hello') (from the beginning up to index 5)
○ my_string[::2] (returns 'Hlo Pto!') (every second character)
○ my_string[::-1] (returns '!nohtyP ,olleH') (reverses the string)

2. String Methods (replace(), upper(), find()):

● A. replace(): Replaces occurrences of a substring with another.


○ my_string.replace("Python", "World") (returns "Hello,
World!")
● B. upper(): Converts the string to uppercase.
○ my_string.upper() (returns "HELLO, PYTHON!")
● D. find(): Returns the index of the first occurrence of a substring, or -1
if not found.
○ my_string.find("Python") (returns 7)
○ my_string.find("Java") (returns -1)

3. String Methods (lower(), join(), partition()):

● A. lower(): Converts the string to lowercase.


○ my_string.lower() (returns "hello, python!")
● B. join(): Concatenates a sequence of strings using the string as a
separator.
○ words = ["Hello", "World"]
○ " ".join(words) (returns "Hello World")
○ ", ".join(words) (returns "Hello, World")
● D. partition(): Splits the string at the first occurrence of a separator
and returns a tuple of three parts: (before separator, separator, after
separator).
○ my_string.partition(",") (returns ('Hello', ',', ' Python!'))

4. List Creation, Indexing, and Slicing:

● Creation: Lists are created using square brackets [...].


○ my_list = [1, 2, "apple", 3.14]
● Indexing: Same as strings.
○ my_list[0] (returns 1)
○ my_list[-1] (returns 3.14)
● Slicing: Same as strings.
○ my_list[1:3] (returns [2, "apple"])

5. List Methods (insert(), clear(), pop(), sort()):

● A. insert(): Inserts an element at a given index.


○ my_list.insert(2, "banana") (inserts "banana" at index 2)
● B. clear(): Removes all elements from the list.
○ my_list.clear() (makes the list empty: [])
● C. pop(): Removes and returns the element at a given index (or the last
element if no index is specified).
○ my_list.pop(1) (removes and returns the element at index 1)
● D. sort(): Sorts the list in place (modifies the original list).
○ numbers = [3, 1, 4, 2]
○ numbers.sort() (sorts in ascending order)
○ numbers.sort(reverse=True) (sorts in descending order)

6. Tuple Creation, Indexing, and Slicing:

● Creation: Tuples are created using parentheses (...).


○ my_tuple = (1, 2, "apple")
● Indexing: Same as strings and lists.
● Slicing: Same as strings and lists.

7. Tuple Definition, Properties, count(), and index():

● A. Definition and Properties: A tuple is an ordered, immutable sequence.


This means you cannot change its elements after creation.
● B. count(): Returns the number of times a value occurs in the tuple.
○ my_tuple.count(2) (returns 1)
● index(): Returns the index of the first occurrence of a value.
○ my_tuple.index("apple") (returns 2)

8. Set Definition, Properties, add(), remove(), discard():

● A. Definition and Properties: A set is an unordered collection of unique


elements. Sets do not allow duplicate values. They are mutable.
● B. add(): Adds an element to the set.
○ my_set = {1, 2, 3}
○ my_set.add(4)
● remove(): Removes an element from the set. Raises a KeyError if the
element is not found.
○ my_set.remove(3)
● discard(): Removes an element from the set if it is present. Does not
raise an error if the element is not found.
○ my_set.discard(5) (does nothing if 5 is not in the set)

9. Set Methods (union(), intersection(), difference(), isdisjoint()):

● A. union(): Returns a new set containing all elements from both sets.
○ set1 = {1, 2, 3}
○ set2 = {3, 4, 5}
○ set1.union(set2) (returns {1, 2, 3, 4, 5})
● B. intersection(): Returns a new set containing common elements.
○ set1.intersection(set2) (returns {3})
● C. difference(): Returns a new set containing elements in the first set
but not in the second set.
○ set1.difference(set2) (returns {1, 2})
● D. isdisjoint(): Returns True if the sets have no elements in common.
○ set1.isdisjoint({4, 5}) (returns True)
○ set1.isdisjoint(set2) (returns False)

10. List vs. Tuple:

Feature List Tuple

Mutability Mutable (can be changed) Immutable (cannot be changed)

Syntax [...] (...)


Use Case Storing collections of Storing collections of items that
items that may need to be should not be changed (e.g.,
modified coordinates, records)

Performa Slightly slower due to Slightly faster due to immutability


nce mutability

1. Creating, Indexing, and Slicing of Strings

Creating:
python
my_string = "Hello, World!"

Indexing:
python
first_char = my_string[0] # 'H'

Slicing:
python
slice_example = my_string[0:5] # 'Hello'

2. String Methods

A. replace():
python
my_string = "Hello, World!"

new_string = my_string.replace("World", "Python")

print(new_string) # "Hello, Python!"


B. upper():
python
my_string = "Hello, World!"

upper_string = my_string.upper()

print(upper_string) # "HELLO, WORLD!"

D. find():
python
my_string = "Hello, World!"

position = my_string.find("World")

print(position) # 7

3. More String Methods

A. lower():
python
my_string = "HELLO, WORLD!"

lower_string = my_string.lower()

print(lower_string) # "hello, world!"

B. join():
python
my_list = ["Hello", "World"]

joined_string = " ".join(my_list)

print(joined_string) # "Hello World"


D. partition():
python
my_string = "Hello, World!"

partitioned = my_string.partition(", ")

print(partitioned) # ('Hello', ', ', 'World!')

4. Creating, Indexing, and Slicing of Lists

Creating:
python
my_list = [1, 2, 3, 4, 5]

Indexing:
python
first_element = my_list[0] # 1

Slicing:
python
slice_example = my_list[1:4] # [2, 3, 4]

5. List Methods

A. insert():
python
my_list = [1, 2, 4, 5]

my_list.insert(2, 3)

print(my_list) # [1, 2, 3, 4, 5]


B. clear():
python
my_list = [1, 2, 3, 4, 5]

my_list.clear()

print(my_list) # []

C. pop():
python
my_list = [1, 2, 3, 4, 5]

popped_element = my_list.pop()

print(popped_element) # 5

D. sort():
python
my_list = [3, 1, 4, 2, 5]

my_list.sort()

print(my_list) # [1, 2, 3, 4, 5]

6. Creating, Indexing, and Slicing of Tuples

Creating:
python
my_tuple = (1, 2, 3, 4, 5)

Indexing:
python
first_element = my_tuple[0] # 1


Slicing:
python
slice_example = my_tuple[1:4] # (2, 3, 4)

7. Tuple Properties and Methods

● A. Tuple Properties:
○ Immutable: Once created, elements cannot be changed.
○ Ordered: Maintains the order of elements.

B. count() and index() Methods with Tuple:


python
my_tuple = (1, 2, 2, 3, 4, 2)

count_2 = my_tuple.count(2) # 3

index_2 = my_tuple.index(2) # 1

print(count_2, index_2)

8. Set Properties and Methods

● A. Set Properties:
○ Unordered: Does not maintain order of elements.
○ No duplicates: Each element is unique.

B. add(), remove(), and discard() Methods:


python
my_set = {1, 2, 3}

my_set.add(4)

print(my_set) # {1, 2, 3, 4}

my_set.remove(3)

print(my_set) # {1, 2, 4}
my_set.discard(2)

print(my_set) # {1, 4}

9. Set Methods

A. union():
python
set1 = {1, 2, 3}

set2 = {3, 4, 5}

union_set = set1.union(set2)

print(union_set) # {1, 2, 3, 4, 5}

B. intersection():
python
set1 = {1, 2, 3}

set2 = {3, 4, 5}

intersection_set = set1.intersection(set2)

print(intersection_set) # {3}

C. difference():
python
set1 = {1, 2, 3}

set2 = {3, 4, 5}

difference_set = set1.difference(set2)

print(difference_set) # {1, 2}


D. isdisjoint():
python
set1 = {1, 2, 3}

set2 = {4, 5, 6}

is_disjoint = set1.isdisjoint(set2)

print(is_disjoint) # True

10. Differences Between List and Tuple

Feature List Tuple

Mutability Mutable (can be changed) Immutable (cannot be


changed)

Syntax [] ()

Methods More built-in methods Fewer built-in methods

Performan Slower Faster


ce

Usage Suitable for dynamic Suitable for fixed


collections collections

UNIT - 4
1. A. Define Dictionary. Explain about creating dictionary and accessing
elements of dictionary in Python.

● Dictionary: A dictionary in Python is an unordered collection of


key-value pairs. Each key is unique, and values can be of any data type.
Dictionaries are mutable, meaning their content can be changed.

Creating a Dictionary: You can create a dictionary by enclosing key-value pairs


in curly braces {}. Each key is separated from its value by a colon : and
key-value pairs are separated by commas.

Example:

my_dict = {"name": "Alice", "age": 25, "city": "New York"}

Accessing Elements: You can access dictionary elements by using the keys in
square brackets [] or by using the get() method.

Example:

print(my_dict["name"]) # Output: Alice

print(my_dict.get("age")) # Output: 25

1. B. With example, explain about adding, removing, and updating of


dictionary items in Python.

Adding Items: You can add new key-value pairs by assigning a value to a new
key.

Example:

my_dict["profession"] = "Engineer"
print(my_dict) # Output: {'name': 'Alice', 'age': 25, 'city': 'New York', 'profession':
'Engineer'}

Removing Items: You can remove an item using del or the pop() method.

Example:

del my_dict["age"]

print(my_dict) # Output: {'name': 'Alice', 'city': 'New York', 'profession':


'Engineer'}

removed_item = my_dict.pop("city")

print(removed_item) # Output: New York

Updating Items: You can update an existing key's value by assigning a new value
to it.

Example:

my_dict["age"] = 30

print(my_dict) # Output: {'name': 'Alice', 'profession': 'Engineer', 'age': 30}

2. With example, explain the following dictionary methods:

A. keys()

The keys() method returns a view object that displays a list of all the keys in
the dictionary.

Example:
my_dict = {"name": "Alice", "age": 25}

print(my_dict.keys()) # Output: dict_keys(['name', 'age'])

B. values()

The values() method returns a view object that displays all the values in the
dictionary.

Example:

my_dict = {"name": "Alice", "age": 25}

print(my_dict.values()) # Output: dict_values(['Alice', 25])

C. copy()

The copy() method returns a shallow copy of the dictionary.

Example:

my_dict = {"name": "Alice", "age": 25}

new_dict = my_dict.copy()

print(new_dict) # Output: {'name': 'Alice', 'age': 25}

D. fromkeys()

The fromkeys() method creates a new dictionary with the specified keys and
sets the values to a default value (None by default).

Example:

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

new_dict = dict.fromkeys(keys, 0)

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


3. With example, explain the following dictionary methods:

A. get()

The get() method returns the value for a specified key. If the key does not
exist, it returns None (or a specified default value).

Example:

my_dict = {"name": "Alice", "age": 25}

print(my_dict.get("name")) # Output: Alice

print(my_dict.get("gender", "Not specified")) # Output: Not specified

B. popitem()

The popitem() method removes and returns an arbitrary (key, value) pair from
the dictionary.

Example:

my_dict = {"name": "Alice", "age": 25}

item = my_dict.popitem()

print(item) # Output: ('age', 25)

print(my_dict) # Output: {'name': 'Alice'}

C. setdefault()

The setdefault() method returns the value of a key if it exists. If the key does
not exist, it adds the key with the specified default value.

Example:

my_dict = {"name": "Alice"}


print(my_dict.setdefault("age", 25)) # Output: 25 (adds key "age" with value 25)

print(my_dict) # Output: {'name': 'Alice', 'age': 25}

D. update()

The update() method updates the dictionary with elements from another
dictionary or iterable.

Example:

my_dict = {"name": "Alice", "age": 25}

my_dict.update({"city": "New York", "age": 30}) # Updates the 'age' key and adds
a new key 'city'

print(my_dict) # Output: {'name': 'Alice', 'age': 30, 'city': 'New York'}

4. A. Define a function. Explain creating and calling a function with


example in Python.

● Function: A function is a block of code that only runs when it is called.


Functions help to break a program into smaller, modular chunks.

● Creating a Function: A function is created using the def keyword


followed by the function name and parentheses ().

Example:

def greet(name):

print(f"Hello, {name}!")

# Calling the function

greet("Alice") # Output: Hello, Alice!


4. B. Write a Python program to find the sum of n natural numbers using
user-defined functions.

def sum_of_natural_numbers(n):

return sum(range(1, n + 1))

n = int(input("Enter a number: "))

print(f"The sum of first {n} natural numbers is {sum_of_natural_numbers(n)}")

5. Explain about default and keyword arguments in Python with


example.

● Default Arguments: You can define default values for function


parameters. If the user doesn't provide an argument, the default value is
used.

● Keyword Arguments: Keyword arguments allow you to specify


parameters in a function call by their name.

Example:

def greet(name, age=25):

print(f"Hello {name}, you are {age} years old.")

greet("Alice") # Uses default value for age

greet("Bob", 30) # Overrides default value for age


6. Explain about positional, variable length, and variable keyword length
arguments in Python with example.

● Positional Arguments: These are the most common type of arguments


where the values are assigned to parameters based on their position.

● Variable Length Arguments (*args): This allows a function to accept any


number of positional arguments.

● Variable Keyword Arguments (**kwargs): This allows a function to


accept any number of keyword arguments.

Example:

def greet(*names, **ages):

for name in names:

print(f"Hello {name}")

for name, age in ages.items():

print(f"{name} is {age} years old.")

greet("Alice", "Bob", Alice=25, Bob=30)

7. How a function is passed as an argument to another function. Explain


with example.

You can pass a function as an argument to another function. The receiving


function can call the passed function as needed.

Example:
def greet(name):

print(f"Hello {name}")

def call_function(func, name):

func(name)

call_function(greet, "Alice")

8. Define recursion and write a Python program to find the factorial of a


given number using recursion.

● Recursion: A function is said to be recursive if it calls itself in order to


solve a problem.

Example:

def factorial(n):

if n == 1:

return 1

else:

return n * factorial(n - 1)

print(factorial(5)) # Output: 120


9. Write a Python program to display Fibonacci series up to given range
using functions:

A. Without using recursion:

def fibonacci(n):

a, b = 0, 1

for _ in range(n):

print(a, end=" ")

a, b = b, a + b

fibonacci(10) # Output: 0 1 1 2 3 5 8 13 21 34

B. Using recursion:

def fibonacci_recursive(n, a=0, b=1):

if n > 0:

print(a, end=" ")

fibonacci_recursive(n -

1, b, a + b)

fibonacci_recursive(10) # Output: 0 1 1 2 3 5 8 13 21 34

---

### 10. **With an example, explain lambda with filter(), map(), and reduce()
functions.**
- **Lambda:**

A lambda function is a small anonymous function defined with the `lambda`


keyword.

- **filter()**: Filters elements based on a function's result.

- **map()**: Applies a function to all elements in an iterable.

- **reduce()**: Applies a function cumulatively to the items in an iterable.

**Example:**

```python

from functools import reduce

# Using lambda with filter()

numbers = [1, 2, 3, 4, 5, 6]

even_numbers = list(filter(lambda x: x % 2 == 0, numbers))

print(even_numbers) # Output: [2, 4, 6]

# Using lambda with map()

squared_numbers = list(map(lambda x: x ** 2, numbers))

print(squared_numbers) # Output: [1, 4, 9, 16, 25, 36]


# Using lambda with reduce()

product = reduce(lambda x, y: x * y, numbers)

print(product) # Output: 720

1. Dictionaries:

● A. Definition and Creation: A dictionary is an unordered collection of


key-value pairs. Keys must be immutable (e.g., strings, numbers, tuples),
and values can be any data type. Dictionaries are created using curly
braces {}.

Python

my_dict = {"name": "Alice", "age": 30, "city": "New York"}

● Accessing Elements: Elements are accessed using their keys within


square brackets [].

Python

print(my_dict["name"]) # Output: Alice

print(my_dict["age"]) # Output: 30

#print(my_dict["country"]) #Raises KeyError if the key is not present

● B. Adding, Removing, and Updating:

Python

my_dict["country"] = "USA" # Adding a new key-value pair


print(my_dict) #Output: {'name': 'Alice', 'age': 30, 'city': 'New York', 'country':
'USA'}

my_dict["age"] = 31 # Updating the value associated with a key

print(my_dict) #Output: {'name': 'Alice', 'age': 31, 'city': 'New York', 'country':
'USA'}

del my_dict["city"] # Removing a key-value pair using del

print(my_dict) #Output: {'name': 'Alice', 'age': 31, 'country': 'USA'}

my_dict.pop("country") # Removing a key-value pair using pop. Returns the


value

print(my_dict) #Output: {'name': 'Alice', 'age': 31}

2. Dictionary Methods (keys(), values(), copy()):

● A. keys(): Returns a view object that displays a list of all the keys in the
dictionary.

Python

print(my_dict.keys()) # Output: dict_keys(['name', 'age'])

● B. values(): Returns a view object that displays a list of all the values in
the dictionary.

Python

print(my_dict.values()) # Output: dict_values(['Alice', 31])


● C. copy(): Returns a shallow copy of the dictionary.

Python

new_dict = my_dict.copy()

3. Dictionary Methods (get(), popitem(), setdefault()):

● A. get(): Returns the value for a given key. If the key is not present, it
returns a default value (or None if no default is specified).

Python

print(my_dict.get("name")) # Output: Alice

print(my_dict.get("city", "Unknown")) # Output: Unknown

print(my_dict.get("city")) #Output: None

● B. popitem(): Removes and returns a (key, value) pair. Pairs are returned
in LIFO (Last In, First Out) order.

Python

print(my_dict.popitem()) #Output: ('age', 31)

● C. setdefault(): Returns the value of a key if it is in the dictionary. If


not, it inserts the key with a specified value.

Python

print(my_dict.setdefault("city", "London")) #Output: London

print(my_dict) #Output: {'name': 'Alice', 'city': 'London'}

print(my_dict.setdefault("name", "Bob")) #Output: Alice

print(my_dict) #Output: {'name': 'Alice', 'city': 'London'}


4. Dictionary Method (update()):

● D. update(): Updates the dictionary with the elements from another


dictionary or an iterable of key-value pairs.

Python

my_dict.update({"age": 32, "country": "UK"})

print(my_dict) #Output: {'name': 'Alice', 'city': 'London', 'age': 32, 'country': 'UK'}

5. Functions:

● A. Definition, Creation, and Calling: A function is a block of organized,


reusable code.

Python

def greet(name): # Function definition

"""Greets the person passed in as a parameter.""" #Docstring

print(f"Hello, {name}!")

greet("Bob") # Function call #Output: Hello, Bob!

● B. Sum of n Natural Numbers:

Python

def sum_natural_numbers(n):

"""Calculates the sum of the first n natural numbers."""

sum = 0

for i in range(1, n + 1):

sum += i
return sum

num = int(input("Enter a positive integer: "))

if num < 0:

print("Please enter a positive integer.")

else:

result = sum_natural_numbers(num)

print(f"The sum of the first {num} natural numbers is {result}")

6. Default and Keyword Arguments:

● Default Arguments: Assign a default value to a parameter in the function


definition.

Python

def greet(name="Guest"):

print(f"Hello, {name}!")

greet() # Output: Hello, Guest!

greet("Alice") # Output: Hello, Alice!

● Keyword Arguments: Pass arguments using their parameter names.

Python

def describe_person(name, age):

print(f"{name} is {age} years old.")


describe_person(age=30, name="Bob") # Output: Bob is 30 years old.

7. Positional, Variable Length, and Variable Keyword Length Arguments:

● Positional Arguments: Arguments are passed in the order they are


defined in the function. (Covered in previous examples).
● Variable Length Arguments (*args): Allow a function to accept any
number of positional arguments. These arguments are received as a
tuple.

Python

def print_numbers(*args):

for num in args:

print(num)

print_numbers(1, 2, 3, 4, 5)

● Variable Keyword Length Arguments (**kwargs): Allow a function to


accept any number of keyword arguments. These arguments are received
as a dictionary.

Python

def print_info(**kwargs):

for key, value in kwargs.items():

print(f"{key}: {value}")

print_info(name="Alice", age=30, city="New York")

8. Passing Functions as Arguments and return:


● A. Passing Functions as Arguments: Functions can be passed as
arguments to other functions (higher-order functions).

Python

def apply_operation(func, x, y):

return func(x, y)

def add(x, y):

return x + y

result = apply_operation(add, 5, 3) # Passing the add function

print(result) # Output: 8

● B. return Keyword: The return statement exits a function and


optionally returns a value. If no return statement is present the function
will return None.

Python

def get_double(x):

return 2 * x

value = get_double(5)

print(value) #Output: 10

def print_message(message):

print(message)
print(print_message("Hello")) #Output: Hello \n None

9. Recursion and Fibonacci Series:

● Recursion: A function calling itself.

Python

def factorial(n):

if n == 0:

return 1

else:

return n * factorial(n - 1)

print(factorial(5)) #Output: 120

● Fibonacci Series:

○ A) Without Recursion:

Python

def fibonacci_non_recursive(n):

a, b = 0, 1

series = []

for _ in range(n):

series.append(a)

a, b = b, a + b

return series
print(fibonacci_non_recursive(10))

* **B) Using Recursion:**

Python

def fibonacci_recursive(n):

if n <= 1:

return n

else:

return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2)

def fibonacci_series_recursive(n):

series = []

for i in range(n):

series.append(fibonacci_recursive(i))

return series

print(fibonacci_series_recursive(10))

Lambda Functions:

A lambda function is a small, anonymous function defined using the lambda


keyword. It can take any number of arguments but can only have one
expression.
lambda arguments: expression

Examples:

Python

# A lambda function that adds two numbers

add = lambda x, y: x + y

print(add(5, 3)) # Output: 8

# A lambda function that squares a number

square = lambda x: x**2

print(square(4)) # Output: 16

filter():

The filter() function filters a sequence based on a given function (which can
be a lambda function). It returns an iterator containing the elements for which
the function returns True.

filter(function, iterable)

Example:

Python

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

# Filter out even numbers using a lambda function

even_numbers = list(filter(lambda x: x % 2 == 0, numbers))

print(even_numbers) # Output: [2, 4, 6, 8, 10]


# Filter out numbers greater than 5

greater_than_5 = list(filter(lambda x: x > 5, numbers))

print(greater_than_5) # Output: [6, 7, 8, 9, 10]

map():

The map() function applies a given function (which can be a lambda function) to
all items in an input iterable. It returns an iterator that yields the results.

map(function, iterable, ...) (can take multiple iterables)

Example:

Python

numbers = [1, 2, 3, 4, 5]

# Square each number using a lambda function

squared_numbers = list(map(lambda x: x**2, numbers))

print(squared_numbers) # Output: [1, 4, 9, 16, 25]

# Multiply each number by 2

multiplied_numbers = list(map(lambda x: x * 2, numbers))

print(multiplied_numbers) #Output: [2, 4, 6, 8, 10]

numbers1 = [1, 2, 3]

numbers2 = [4, 5, 6]

added_numbers = list(map(lambda x,y: x+y, numbers1,numbers2))

print(added_numbers) #Output: [5, 7, 9]


reduce():

The reduce() function (from the functools module) applies a function of two
arguments cumulatively to the items of a sequence, from left to right, so as to
reduce the sequence to a single value.

reduce(function, iterable[, initializer])

Example:

Python

from functools import reduce

numbers = [1, 2, 3, 4, 5]

# Calculate the product of all numbers using a lambda function

product = reduce(lambda x, y: x * y, numbers)

print(product) # Output: 120

#Calculate sum of all numbers

sum_of_numbers = reduce(lambda x,y: x+y, numbers)

print(sum_of_numbers) #Output: 15

# Find the largest number

largest_number = reduce(lambda x,y: x if x>y else y, numbers)

print(largest_number) #Output: 5
Key Differences and Use Cases:

● filter(): Selects elements based on a condition (returns a subset of the


original iterable).
● map(): Transforms each element (returns a new iterable with the same
number of elements).
● reduce(): Combines all elements into a single value.

Lambda functions are particularly useful when you need a small function for a
short period, often as an argument to higher-order functions like filter(),
map(), and reduce(). They make the code more concise and readable in these
situations.

1. Dictionary in Python

A. Definition and Creation: A dictionary in Python is a collection of key-value


pairs. Each key is unique, and keys are used to access the corresponding values.

Creating a Dictionary:

python

my_dict = {"name": "Alice", "age": 25, "city": "New York"}

Accessing Elements:

python

print(my_dict["name"]) # Output: Alice

B. Adding, Removing, and Updating Dictionary Items:

Adding:
python
my_dict["email"] = "[email protected]"

print(my_dict)

Removing:
python
my_dict.pop("age")

print(my_dict)

Updating:
python
my_dict["city"] = "Los Angeles"

print(my_dict)

2. Dictionary Methods

A. keys():
python
print(my_dict.keys()) # Output: dict_keys(['name', 'city', 'email'])

B. values():
python
print(my_dict.values()) # Output: dict_values(['Alice', 'Los Angeles',
'[email protected]'])

C. copy():
python
new_dict = my_dict.copy()

print(new_dict)

D. fromkeys():
python
keys = ["name", "age", "city"]
new_dict = dict.fromkeys(keys, "Unknown")

print(new_dict) # Output: {'name': 'Unknown', 'age': 'Unknown', 'city':


'Unknown'}

3. More Dictionary Methods

A. get():
python
name = my_dict.get("name")

print(name) # Output: Alice

B. popitem():
python
item = my_dict.popitem()

print(item) # Output: ('email', '[email protected]')

C. setdefault():
python
age = my_dict.setdefault("age", 30)

print(my_dict)

D. update():
python
my_dict.update({"name": "Bob", "country": "USA"})

print(my_dict)

4. Functions in Python
A. Definition and Creation: A function is a block of code that performs a specific
task. Functions help organize code and make it reusable.

Creating and Calling a Function:

python

def greet(name):

return f"Hello, {name}!"

print(greet("Alice")) # Output: Hello, Alice!

B. Sum of n Natural Numbers Using User-Defined Function:

python

def sum_of_n_numbers(n):

return n * (n + 1) // 2

n = 10

print("Sum of first", n, "natural numbers is:", sum_of_n_numbers(n))

5. Default and Keyword Arguments

Default Arguments:

python

def greet(name, message="Hello"):

return f"{message}, {name}!"

print(greet("Alice")) # Output: Hello, Alice!


print(greet("Bob", "Hi")) # Output: Hi, Bob!

Keyword Arguments:

python

def greet(name, message):

return f"{message}, {name}!"

print(greet(name="Alice", message="Hi")) # Output: Hi, Alice!

6. Arguments in Python

Positional, Variable Length, and Keyword Length Arguments:

Positional Arguments:
python
def greet(name, message):

return f"{message}, {name}!"

print(greet("Alice", "Hello")) # Output: Hello, Alice!

Variable Length Arguments:


python
def greet(*names):

for name in names:

print(f"Hello, {name}!")

greet("Alice", "Bob", "Charlie")


Keyword Length Arguments:


python
def greet(**kwargs):

for key, value in kwargs.items():

print(f"{key}: {value}")

greet(name="Alice", age=25, city="New York")

7. Function as an Argument

Example:

python

def add(x, y):

return x + y

def apply_func(func, a, b):

return func(a, b)

result = apply_func(add, 5, 3)

print(result) # Output: 8

8. Recursion

Definition and Factorial Program: Recursion is a process in which a function


calls itself.
Factorial Program:

python

def factorial(n):

if n == 1:

return 1

else:

return n * factorial(n - 1)

print(factorial(5)) # Output: 120

Fibonacci Series:

Without Recursion:
python
def fibonacci(n):

a, b = 0, 1

for _ in range(n):

print(a, end=" ")

a, b = b, a + b

fibonacci(10)

With Recursion:
python
def fibonacci(n):

if n <= 1:
return n

else:

return fibonacci(n - 1) + fibonacci(n - 2)

for i in range(10):

print(fibonacci(i), end=" ")

10. Lambda with filter(), map(), and reduce() Functions

Lambda and filter():

python

numbers = [1, 2, 3, 4, 5]

even_numbers = list(filter(lambda x: x % 2 == 0, numbers))

print(even_numbers) # Output: [2, 4]

Lambda and map():

python

squared_numbers = list(map(lambda x: x ** 2, numbers))

print(squared_numbers) # Output: [1, 4, 9, 16, 25]

Lambda and reduce():

python

from functools import reduce


sum_numbers = reduce(lambda x, y: x + y, numbers)

print(sum_numbers) # Output: 15

UNIT - 5
1. Explain about creating class, object and accessing of class members
with example.

● Class: A class is a blueprint for creating objects. It defines the properties


(attributes) and behaviors (methods) that the objects created from the
class will have.

● Object: An object is an instance of a class. Once a class is defined, you can


create objects based on that class.

● Accessing Class Members: You can access class members (both attributes
and methods) using the dot (.) operator.

Example:

class Car:

# Constructor (__init__ method)

def __init__(self, make, model):

self.make = make

self.model = model

# Method to display car details

def display(self):

print(f"Car Make: {self.make}, Model: {self.model}")


# Creating an object of the Car class

my_car = Car("Toyota", "Corolla")

# Accessing object properties and method

print(my_car.make) # Output: Toyota

my_car.display() # Output: Car Make: Toyota, Model: Corolla

2. Explain about __init__() method with example.

● __init__() Method: The __init__() method is a special method in


Python classes, also called the constructor. It is automatically called
when a new object of the class is created. The primary purpose of
__init__() is to initialize the object's attributes.

Example:

class Person:

def __init__(self, name, age):

self.name = name

self.age = age

# Creating an object

person1 = Person("John", 30)

print(person1.name) # Output: John

print(person1.age) # Output: 30
3. What is inheritance? Explain different types of inheritance with
example.

● Inheritance: Inheritance allows a class (child class) to inherit attributes


and methods from another class (parent class). It helps in code reusability
and establishes a relationship between the parent and child classes.

● Types of Inheritance:

1. Single Inheritance: A child class inherits from one parent class.


2. Multiple Inheritance: A child class inherits from multiple parent
classes.
3. Multilevel Inheritance: A child class inherits from a parent class,
which itself is inherited from another class.
4. Hierarchical Inheritance: Multiple child classes inherit from a
single parent class.

Example:

# Single Inheritance

class Animal:

def speak(self):

print("Animal speaks")

class Dog(Animal):

def bark(self):

print("Dog barks")

# Creating an object of Dog

dog = Dog()

dog.speak() # Inherited from Animal


dog.bark() # Defined in Dog class

4. Explain about abstraction and encapsulation with an example.

● Abstraction: Abstraction is the concept of hiding the implementation


details from the user and only exposing essential features. This is
typically achieved using abstract classes or methods.

● Encapsulation: Encapsulation refers to bundling the data (attributes) and


methods that operate on the data within a single unit or class. It helps in
restricting direct access to some of an object's components, thereby
making the class more secure.

Example of Encapsulation and Abstraction:

from abc import ABC, abstractmethod

# Abstraction (Using Abstract Base Class)

class Shape(ABC):

@abstractmethod

def area(self):

pass

class Circle(Shape):

def __init__(self, radius):

self.__radius = radius # Encapsulation: private variable

def area(self):
return 3.14 * self.__radius * self.__radius

circle = Circle(5)

print(circle.area()) # Output: 78.5

5. What is an error? Explain different types of errors that occur in


programming.

● Error: Errors are issues in the program that cause it to behave


unexpectedly or stop running. They are categorized into two main types:
Syntax Errors and Runtime Errors.

● Types of Errors:

1. Syntax Errors: Occur when the code violates Python's syntax rules.
2. Runtime Errors: Occur during the execution of the program (e.g.,
division by zero).
3. Logical Errors: Occur when the program runs but produces
incorrect results due to faulty logic.

6. With example, explain exception handling in Python.

● Exception Handling: Python provides a mechanism to handle runtime


errors through the use of try, except, else, and finally blocks.

Example:

try:

num = int(input("Enter a number: "))

result = 10 / num

except ZeroDivisionError:
print("Cannot divide by zero!")

except ValueError:

print("Invalid input! Please enter a valid number.")

else:

print(f"The result is {result}")

finally:

print("Execution completed.")

7. Write a Python program illustrating:

A. Handling multiple exceptions at a time

try:

num1 = int(input("Enter the first number: "))

num2 = int(input("Enter the second number: "))

result = num1 / num2

except (ValueError, ZeroDivisionError) as e:

print(f"Error: {e}")

else:

print(f"The result is: {result}")

B. Handling multiple exceptions one after another

try:

num1 = int(input("Enter the first number: "))


num2 = int(input("Enter the second number: "))

result = num1 / num2

except ValueError:

print("Invalid input! Please enter a valid number.")

except ZeroDivisionError:

print("Cannot divide by zero!")

else:

print(f"The result is: {result}")

8. Write a Python program illustrating:

A. Handling unknown exception

try:

# Trying to open a non-existent file

with open("non_existent_file.txt", "r") as file:

content = file.read()

except Exception as e:

print(f"An error occurred: {e}")

B. Demonstrate finally and else block

try:

num1 = int(input("Enter a number: "))

num2 = int(input("Enter another number: "))


result = num1 / num2

except ZeroDivisionError:

print("Cannot divide by zero!")

else:

print(f"The result is: {result}")

finally:

print("Execution completed.")

9. A. Define file and explain different types of files in Python.

● File: A file is a container in a computer system used to store data. In


Python, files can be handled using built-in functions. Files can be
categorized into:

1. Text Files: Contain plain text data.


2. Binary Files: Contain data in binary format (e.g., images, audio).
3. CSV Files: Stores data in a structured format like tables.
4. JSON Files: Stores data in JavaScript Object Notation (JSON)
format.

9. B. Write a Python program to create a new file and add the given text
to the file.

# Open a new file in write mode

with open("example.txt", "w") as file:

file.write("Hello, this is a sample text.")


10. A. Explain in detail about seek() and tell() methods.

● seek(): The seek() method is used to move the file pointer to a specific
position within the file. It takes two arguments: offset (the number of
bytes to move) and whence (where to start from, default is the beginning
of the file).

● tell(): The tell() method returns the current position of the file pointer.

Example:

with open("example.txt", "r") as file:

file.seek(5) # Move the pointer to the 5th byte

print(file.tell()) # Output: 5 (position of the file pointer)

print(file.read()) # Output: the text after the 5th byte

10. B. Write a Python program to add the contents into an existing file
and display the contents of a file from the specified position.

# Adding text to an existing file

with open("example.txt", "a") as file:

file.write("\nAppended text.")

# Display content from a specified position

with open("example.txt", "r") as file:

file.seek(10)

print(file.read()) # Displays content starting from the 10th byte


1. Classes, Objects, and Class Members:

● A. Creating a Class: A class is a blueprint for creating objects. It defines


attributes (data) and methods (actions).

Python

class Dog:

def __init__(self, name, breed): # Constructor (initializer)

self.name = name

self.breed = breed

def bark(self):

print("Woof!")

● Creating an Object (Instance): An object is a specific instance of a class.

Python

my_dog = Dog("Buddy", "Golden Retriever")

● Accessing Class Members: Access attributes and call methods using the
dot operator (.).

Python

print(my_dog.name) # Output: Buddy

print(my_dog.breed) # Output: Golden Retriever

my_dog.bark() # Output: Woof!


2. Methods and __init__():

● Method: A function defined inside a class. It operates on the object's data.


● __init__() (Constructor): A special method that is automatically called
when an object is created. It initializes the object's attributes. The self
parameter refers to the current object.

Python

class Car:

def __init__(self, make, model, year):

self.make = make

self.model = model

self.year = year

self.mileage = 0

def drive(self, miles):

self.mileage += miles

print(f"Driven {miles} miles. Total mileage: {self.mileage}")

my_car = Car("Toyota", "Camry", 2020)

my_car.drive(100) # Output: Driven 100 miles. Total mileage: 100

3. Inheritance:

● Definition: Inheritance allows a class (subclass or derived class) to inherit


attributes and methods from another class (superclass or base class). This
promotes code reuse. 1
● Types of Inheritance:
○ Single Inheritance: A subclass inherits from a single superclass.

Python

class Animal:

def eat(self):

print("Eating...")

class Cat(Animal): # Cat inherits from Animal

def meow(self):

print("Meow!")

my_cat = Cat()

my_cat.eat() # Inherited from Animal #Output: Eating...

my_cat.meow() # Output: Meow!

* **Multiple Inheritance:** A subclass inherits from multiple superclasses.

Python

class Swimmer:

def swim(self):

print("Swimming...")

class Walker:

def walk(self):
print("Walking...")

class Duck(Swimmer, Walker): #Duck inherits from both Swimmer and Walker

pass

my_duck = Duck()

my_duck.swim() #Output: Swimming...

my_duck.walk() #Output: Walking...

* **Multilevel Inheritance:** A subclass inherits from another subclass.

Python

class Grandparent:

def grandparent_method(self):

print("Grandparent method")

class Parent(Grandparent):

def parent_method(self):

print("Parent method")

class Child(Parent):

def child_method(self):

print("Child method")
my_child = Child()

my_child.grandparent_method() #Output: Grandparent method

my_child.parent_method() #Output: Parent method

my_child.child_method() #Output: Child method

4. Abstraction and Encapsulation:

● Abstraction: Hiding complex implementation details and showing only


essential information to the user. Achieved through abstract classes and
interfaces (not directly in base Python, but through abc module).
● Encapsulation: Bundling data (attributes) and methods that operate on
that data within a class. Access to the data is controlled through methods
(getters and setters). Achieved through access modifiers (conventionally
using single _ or double __ underscores for protected and private
members, respectively).

Python

class BankAccount:

def __init__(self, balance):

self.__balance = balance # Encapsulation (private attribute)

def deposit(self, amount):

self.__balance += amount

def get_balance(self): # Getter method

return self.__balance

my_account = BankAccount(1000)
my_account.deposit(500)

print(my_account.get_balance()) # Output: 1500

#print(my_account.__balance) #This will raise AttributeError

5. Errors and Types of Errors:

● Error: An issue that prevents a program from executing correctly.


● Types:
○ Syntax Errors: Violations of the programming language's grammar
(e.g., missing colons, incorrect indentation). Detected by the
interpreter before execution.
○ Runtime Errors (Exceptions): Errors that occur during program
execution (e.g., division by zero, file not found).
○ Logical Errors: Errors in the program's logic that cause it to
produce incorrect results, even if it runs without crashing.

6. Exception Handling:

Using try...except blocks to handle runtime errors.

Python

try:

result = 10 / 0

except ZeroDivisionError:

print("Cannot divide by zero.")

except TypeError:

print("Type mismatch")

7. Handling Multiple Exceptions:

● A. At a Time:

Python
try:

x = int("abc")

result = 10 / 0

except (ValueError, ZeroDivisionError) as e:

print(f"An error occurred: {e}")

● B. One After Another:

Python

try:

x = int("abc")

except ValueError:

print("Invalid input. Please enter a number.")

try:

result = 10/0

except ZeroDivisionError:

print("Cannot divide by zero")

8. Handling Unknown Exceptions, finally and else:

● A. Handling Unknown Exceptions:

Python

try:

# Code that might raise an exception


result = 10/0

except Exception as e: #Catches any type of exception

print(f"An unexpected error occurred: {e}")

● B. finally and else:

Python

try:

f = open("my_file.txt", "r")

content = f.read()

# Process the file content

except FileNotFoundError:

print("File not found.")

else: #Executed if no exception occurred in try block

print("File processed successfully.")

finally: #Always executed whether an exception occurs or not

if 'f' in locals(): #Check if file is opened or not

f.close()

print("File operation completed.")

9. Files and File Handling:

● A. File Definition and Types: A file is a named storage location on a


storage device.
○ Text Files: Contain human-readable text (e.g., .txt, .csv).
○ Binary Files: Contain data in binary format (e.g., images,
executables).
● B. Creating and Writing to a File:
Python

try:

with open("new_file.txt", "w") as f: #Opens file in write mode, if not exists


then create new file

f.write("This is some text.\n")

f.write("This is another line.\n")

print("File created and text added successfully.")

except Exception as e:

print(f"An error occurred: {e}")

10. seek() and tell():

● A. seek(): Changes the file's current position. seek(offset[,


from_what]). Offset is the number of bytes to move. from_what: 0
(beginning), 1 (current position), 2 (end).
● tell(): Returns the file's current position (in bytes).
● B. Adding Content and Displaying from a Position:

Python

try:

with open("existing_file.txt", "a+") as f: #Opens file in append and read mode

f.write("New content added.\n")

f.seek(5) #Moves the file pointer to 5th byte

content_from_position = f.read()

print("Content from specified position:")

print(content_from_position)

except FileNotFoundError:
print("File not found.")

except Exception as e:

print(f"An error occurred: {e}")

1. Creating Class, Object, and Accessing Class Members

Creating a Class and Object:

python

class Dog:

def __init__(self, name, age):

self.name = name

self.age = age

def bark(self):

return f"{self.name} says Woof!"

# Creating an object

my_dog = Dog("Buddy", 3)

print(my_dog.bark()) # Output: Buddy says Woof!

● Class: A blueprint for creating objects.


● Object: An instance of a class.

Accessing Class Members:

● Attributes: my_dog.name
● Methods: my_dog.bark()

2. Method and __init__() Method

Method: A function defined within a class.

__init__() Method:

python

class Dog:

def __init__(self, name, age):

self.name = name

self.age = age

def bark(self):

return f"{self.name} says Woof!"

my_dog = Dog("Buddy", 3)

print(my_dog.bark()) # Output: Buddy says Woof!

The __init__() method initializes the object's attributes.

3. Inheritance

Inheritance: A mechanism where one class inherits attributes and methods


from another class.

Types of Inheritance:

Single Inheritance: One class inherits from one base class.


python
class Animal:
def eat(self):

return "Eating"

class Dog(Animal):

def bark(self):

return "Barking"

my_dog = Dog()

print(my_dog.eat()) # Output: Eating

print(my_dog.bark()) # Output: Barking

Multiple Inheritance: One class inherits from multiple base classes.


python
class Animal:

def eat(self):

return "Eating"

class Pet:

def play(self):

return "Playing"

class Dog(Animal, Pet):

pass
my_dog = Dog()

print(my_dog.eat()) # Output: Eating

print(my_dog.play()) # Output: Playing

Multilevel Inheritance: A class inherits from another derived class.


python
class Animal:

def eat(self):

return "Eating"

class Dog(Animal):

def bark(self):

return "Barking"

class Puppy(Dog):

def play(self):

return "Playing"

my_puppy = Puppy()

print(my_puppy.eat()) # Output: Eating

print(my_puppy.bark()) # Output: Barking

print(my_puppy.play()) # Output: Playing

4. Abstraction and Encapsulation


Abstraction: Hiding complex implementation details and showing only essential
features.

● Example: Using a TV remote without knowing how it works internally.

Encapsulation: Bundling data and methods within a class and restricting access
to some components.

Example:
python
class Person:

def __init__(self, name, age):

self.__name = name

self.__age = age

def get_name(self):

return self.__name

def set_age(self, age):

if age > 0:

self.__age = age

person = Person("Alice", 25)

print(person.get_name()) # Output: Alice

person.set_age(30)

5. Types of Errors

Types of Errors:
● Syntax Errors: Errors in the code structure.
● Runtime Errors: Errors that occur during execution.
● Logical Errors: Errors in the logic that lead to incorrect results.

6. Exception Handling in Python

Example of Exception Handling:

python

try:

result = 10 / 0

except ZeroDivisionError:

print("Cannot divide by zero")

7. Handling Multiple Exceptions

A. Handling Multiple Exceptions at a Time:

python

try:

a = int(input("Enter a number: "))

b = int(input("Enter another number: "))

result = a / b

except (ValueError, ZeroDivisionError) as e:

print("Error:", e)

B. Handling Multiple Exceptions One After Another:

python

try:
a = int(input("Enter a number: "))

b = int(input("Enter another number: "))

result = a / b

except ValueError:

print("Invalid input")

except ZeroDivisionError:

print("Cannot divide by zero")

8. Handling Unknown Exceptions and Demonstrating Finally and Else


Block

A. Handling Unknown Exception:

python

try:

result = 10 / 0

except Exception as e:

print("An error occurred:", e)

B. Demonstrating Finally and Else Block:

python

try:

a = int(input("Enter a number: "))

b = int(input("Enter another number: "))

result = a / b

except ZeroDivisionError:
print("Cannot divide by zero")

else:

print("Result:", result)

finally:

print("Execution completed")

9. Files in Python

A. Definition and Types of Files:

● Text Files: Contain plain text.


● Binary Files: Contain binary data.

B. Creating a New File and Adding Text:

python

with open("example.txt", "w") as file:

file.write("Hello, World!")

10. seek() and tell() Methods

A. Explanation of seek() and tell() Methods:

seek(): Moves the cursor to the specified position.


python
with open("example.txt", "r") as file:

file.seek(5)

print(file.read()) # Reads from position 5


tell(): Returns the current position of the cursor.
python
with open("example.txt", "r") as file:

print(file.tell()) # Output: 0 (initial position)

B. Adding Content to an Existing File and Displaying from Specified Position:

python

# Adding content

with open("example.txt", "a") as file:

file.write(" Additional content")

# Displaying from specified position

with open("example.txt", "r") as file:

file.seek(5)

print(file.read()) # Reads from position 5

RUDRANSH

You might also like