0% found this document useful (0 votes)
7 views36 pages

Ge 3151

The document contains a comprehensive question bank for a B.Tech course on Problem Solving and Python Programming, covering topics such as algorithmic problem solving, data types, expressions, and statements. It includes definitions, examples, pseudocode, and Python code for various concepts, ensuring detailed explanations for each question. The content is organized into units, with a systematic approach to answering questions and providing practical examples.

Uploaded by

abiramikayathiri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views36 pages

Ge 3151

The document contains a comprehensive question bank for a B.Tech course on Problem Solving and Python Programming, covering topics such as algorithmic problem solving, data types, expressions, and statements. It includes definitions, examples, pseudocode, and Python code for various concepts, ensuring detailed explanations for each question. The content is organized into units, with a systematic approach to answering questions and providing practical examples.

Uploaded by

abiramikayathiri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

ChatGPT

This is a copy of a conversation between ChatGPT & Anonymous.

GE3151_PSPP_All_unit_question_bank.pdf
PDF

Bittu, you've uploaded a document titled "GE3151 Problem Solving and Python Programming"
containing detailed notes, objectives, and question banks for a B.Tech course. Let me know how you'd
like to utilize this file—whether for explanations, summaries, or project ideas based on the content!

answer the all questions with correct answers.answer should contain syntax program detail answer
with live time example with detail

Bittu, providing detailed answers to all the questions in your document is quite an extensive task. Let
me approach this systematically:

I'll answer questions for Unit I first, providing detailed explanations, syntax, and examples.
We can continue unit by unit, depending on your requirements.

Let me start with Unit I - Algorithmic Problem Solving. Here’s how I’ll proceed:

1. I'll define terms and concepts.


2. Include illustrative examples and programs where applicable.
3. Provide a live example to demonstrate the concept.

Let’s begin:

Unit I - Algorithmic Problem Solving

1) Define Computer.

A computer is an electronic device that processes data, executes instructions, and performs tasks like
calculations, data storage, and communication.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 1/36
2) Define Algorithm.

An algorithm is a finite sequence of well-defined steps or instructions used to solve a problem or


perform a computation.

3) What are the two phases in algorithmic problem solving?

1. Problem Analysis Phase: Understanding and breaking down the problem.


2. Solution Design Phase: Developing a clear algorithm to solve the problem.

4) Why is the algorithmic phase a difficult phase? Justify.

The algorithmic phase requires:

Understanding problem constraints.


Ensuring correctness and efficiency.
Designing edge-case scenarios and managing complex logic.

For example, designing an algorithm to sort data efficiently within limited time and space constraints
can be challenging.

5) What are the steps involved in the algorithm development process?

1. Understand the Problem.


2. Analyze Inputs and Outputs.
3. Define the Algorithm.
4. Validate with Test Cases.
5. Optimize for Efficiency.

6) Compare computer hardware and software.

Hardware Software

Physical components of a computer. Set of instructions or code executed by hardware.


Examples: CPU, RAM, Hard Disk. Examples: Operating System, Python.

7) State some properties of an algorithm.

1. Finiteness: Should end after finite steps.


2. Definiteness: Steps should be clear and unambiguous.
3. Input/Output: Accept input, produce output.
4. Effectiveness: Each step should be computationally feasible.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 2/36
8) What are the three building blocks of an algorithm?

1. Statements: Instructions or actions.


2. Control Flow: The sequence of execution (if, loops).
3. Functions: Subprograms to modularize tasks.

Example for Algorithm, Pseudocode, and Flowchart

Problem: Find the largest of three numbers.

Algorithm:

1. Start.
2. Input three numbers A, B, C.
3. Compare:
If A > B and A > C, A is largest.
Else if B > C, B is largest.
Else, C is largest.
4. Output the largest.
5. Stop.

Pseudocode:

plaintext

START
INPUT A, B, C
IF A > B AND A > C THEN
PRINT A
ELSE IF B > C THEN
PRINT B
ELSE
PRINT C
END
STOP

Python Program:

python

# Program to find the largest of three numbers


A = int(input("Enter first number: "))
B = int(input("Enter second number: "))
C = int(input("Enter third number: "))

if A > B and A > C:


print(f"The largest number is {A}")
elif B > C:
print(f"The largest number is {B}")

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 3/36
else:
print(f"The largest number is {C}")

Flowchart: The flowchart will include:

Input for A, B, C.
Decision blocks for comparisons.
Output for the largest number.

Would you like me to proceed with the remaining questions in this unit or move to Unit II? Let me know!

proceed with remaining question

Let’s continue answering the remaining questions for Unit I - Algorithmic Problem Solving, ensuring
detailed explanations with examples.

9) Define Input, Output, and Assignment statement.

Input Statement: A command that allows the user to provide data to the program during
execution.
Example:

python

name = input("Enter your name: ")

Output Statement: A command that displays data to the user.


Example:

python

print("Hello, World!")

Assignment Statement: A command that assigns a value to a variable.


Example:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 4/36
python

x = 5

10) Describe different notations in algorithms and classify each.

Pseudo Code: Uses plain English to describe steps.


Flowchart: Uses diagrams and symbols to depict the process.
Programming Language: Uses syntax and constructs of specific languages.

Classification:

1. Descriptive Notation: Plain English or Pseudo Code.


2. Graphical Notation: Flowcharts.
3. Formal Notation: Code in programming languages.

11) Define pseudocode.

Pseudocode is a high-level, language-independent description of an algorithm. It is used to represent


the steps of the algorithm in simple terms.

12) Define the rules to be followed on pseudocode.

1. Use simple, clear language.


2. Maintain proper indentation for readability.
3. Use keywords like START, STOP, INPUT, OUTPUT.
4. Avoid language-specific constructs.

13) Define flowchart.

A flowchart is a diagram that represents the flow of a program using symbols like ovals (start/end),
rectangles (processes), and diamonds (decisions).

14) What are the different types of flowcharts?

1. System Flowchart: Represents the overall system.


2. Program Flowchart: Represents individual programs.
3. Data Flow Diagram (DFD): Shows data flow within a system.

15) What are the symbols used in flowcharting?

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 5/36
Symbol Purpose

Oval Start/End
Rectangle Process/Operation
Diamond Decision
Arrow Direction of Flow

16) Describe the Data Processing Symbols in Flowchart.

Symbol Purpose

Rectangle Represents a process or task.


Parallelogram Input/Output operation.

17) List some guidelines for drawing flowcharts.

1. Use standard symbols.


2. Maintain logical flow from top to bottom or left to right.
3. Keep it simple and uncluttered.
4. Label all decision blocks clearly.

18) List the merits of drawing flowcharts.

1. Simplifies problem understanding.


2. Helps in debugging and testing.
3. Provides documentation for the program.

19) List the demerits of drawing flowcharts.

1. Time-consuming to create.
2. Difficult to update for large programs.
3. Limited flexibility compared to pseudocode.

20) Explain some of the qualities of a programming language.

1. Readability: Code should be easy to read.


2. Efficiency: Should execute tasks quickly.
3. Portability: Should run across platforms.
4. Extensibility: Allows adding new features.

21) What is the difference between the algorithm and the program?

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 6/36
Algorithm Program
A step-by-step problem-solving method. A set of instructions in a language executable by a computer.
Language-independent. Language-specific.

22) Give the pseudocode to check the biggest of 2 numbers.

plaintext

START
INPUT A, B
IF A > B THEN
PRINT "A is bigger"
ELSE
PRINT "B is bigger"
END
STOP

Python Code:

python

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


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

if A > B:
print("A is bigger")
else:
print("B is bigger")

23) State the differences between Iteration and Recursion.

Iteration Recursion
Repeats using loops (for/while). Function calls itself.
Explicit termination condition. Implicit termination via base case.
Uses less memory. May use more memory (stack).

Example of Recursion:

python

def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 7/36
print(factorial(5)) # Output: 120

Example of Iteration:

python

def factorial_iterative(n):
result = 1
for i in range(1, n + 1):
result *= i
return result

print(factorial_iterative(5)) # Output: 120

This concludes the detailed answers for Unit I. Let me know if you'd like me to proceed with Unit II or if
you want further clarification on any specific topic.

proceed with unit 2

Let's proceed with Unit II – Data Types, Expressions, and Statements, answering each question with
detailed explanations, examples, and Python code.

Unit II – Data Types, Expressions, and Statements

1) What is a program?

A program is a set of instructions written in a programming language to perform a specific task. It takes
input, processes it, and produces output.

Example:
A program to find the sum of two numbers:

python

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


b = int(input("Enter second number: "))
print(f"The sum is {a + b}")

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 8/36
2) Define computer languages.

Computer languages are formal languages comprising a set of instructions that can be used to
produce various outputs. Examples include Python, C, and Java.

3) How are computer languages classified?

1. Machine Language: Binary instructions directly understood by the computer.


2. Assembly Language: Low-level language using mnemonics.
3. High-Level Language: Human-readable languages like Python, Java.
4. Scripting Languages: Used for automating tasks, e.g., Python, JavaScript.

4) Define assignment statement.

An assignment statement is used to assign a value to a variable.

Syntax:

python

variable_name = value

Example:

python

x = 10
name = "Bittu"

5) List the statements in Python.

1. Assignment Statements: Assign values to variables.


2. Conditional Statements: `if`, `if-else`, `if-elif-else`.
3. Looping Statements: `for`, `while`.
4. Function Calls: `print()`, `input()`.
5. Import Statements: `import math`.

6) Given the strings `x = 'alpha'` and `y = 'beta'`, print the following string operations.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 9/36
python

x = "alpha"
y = "beta"

# Concatenation
print(x + y) # Output: alphabeta

# Repetition
print(x * 3) # Output: alphaalphaalpha

# Slicing
print(x[1:4]) # Output: lph

7) List some of the keywords in Python.

Keywords Purpose
`if`, `else`, `elif` Conditional statements.
`for`, `while` Looping statements.
`def`, `return` Define and return from a function.
`import`, `from` Import modules.

8) Define Identifiers in Python.

An identifier is the name used to identify variables, functions, classes, etc.

Rules:

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


2. Cannot be a keyword.
3. Case-sensitive.

9) What is the comment statement in Python?

A comment is used to explain code and is ignored during execution.

Syntax:

python

# This is a comment

Example:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 10/36
python

# This program prints Hello, World!


print("Hello, World!")

10) Define variables in Python.

A variable is a named memory location used to store data.


Example:

python

x = 5 # x is an integer variable
y = "Bittu" # y is a string variable

11) Explain input and output statements in Python.

Input Statement: Allows the user to enter data.


Example:

python

name = input("Enter your name: ")

Output Statement: Displays data to the user.


Example:

python

print("Hello, World!")

12) List the data types in Python.

Data Type Example


`int` 10

`float` 10.5
`str` "Hello"

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 11/36
Data Type Example
`bool` True, False
`list` [1, 2, 3]

13) What are the operators in Python?

Operator Type Example


Arithmetic `+`, `-`, `*`, `/`
Relational `>`, `<`, `==`

Logical `and`, `or`, `not`


Assignment `=`, `+=`, `-=`
Membership `in`, `not in`

14) Solve the mathematical expression 73 ​ × 1.2 + 32 .


python

result = (7 / 3) * 1.2 + (3 / 2)
print(result) # Output: 4.3

15) Define functions in Python.

A function is a block of reusable code that performs a specific task.

Syntax:

python

def function_name(parameters):
# Body of the function
return value

Example:

python

def greet(name):
return f"Hello, {name}!"

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

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 12/36
16) Explain the precedence of operators in Python.

Operator Precedence
`**` (Exponentiation) Highest
`*`, `/`, `%` Higher
`+`, `-` Low
`and`, `or`, `not` Lowest

Example:

python

result = 3 + 5 * 2 ** 2
print(result) # Output: 23

17) What are the function arguments used in Python?

1. Positional Arguments: Values are matched by position.


2. Keyword Arguments: Values are matched by name.
3. Default Arguments: Assign default values if none provided.
4. Variable-length Arguments: Use `*args` or `**kwargs`.

18) List the types of functions.

1. Built-in Functions: `len()`, `print()`.


2. User-defined Functions: Functions created by the programmer.

19) What is the anonymous function in Python?

An anonymous function is defined using the `lambda` keyword.

Example:

python

square = lambda x: x ** 2
print(square(5)) # Output: 25

20) Define modules in Python.

A module is a file containing Python code (functions, variables) that can be reused.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 13/36
Example:

python

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

21) How are modules incorporated in a Python program?

Modules are incorporated using the `import` keyword.

Example:

python

import random
print(random.randint(1, 10))

22) List some of the built-in modules in Python.

Module Purpose
`math` Mathematical operations.
`os` File and directory operations.
`random` Random number generation.

23) Write a simple program to add two numbers in Python.

python

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


b = int(input("Enter second number: "))
print(f"The sum is {a + b}")

24) Write a simple program to convert KMPH to MPH.

python

kmph = float(input("Enter speed in KMPH: "))


mph = kmph * 0.621371

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 14/36
print(f"Speed in MPH is {mph}")

25) Write a program to convert a decimal number into binary, octal, and hexadecimal.

python

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

print(f"Binary: {bin(number)}")
print(f"Octal: {oct(number)}")
print(f"Hexadecimal: {hex(number)}")

This concludes Unit II. Let me know if you'd like to proceed with Unit III or need clarification on any of
these topics!

proceed with unit 3

Let's continue with Unit III – Control Flow, Functions, and Strings, answering each question in detail
with examples and Python code.

Unit III – Control Flow, Functions, and Strings

1) Define Boolean datatype.

The Boolean datatype represents two values: `True` or `False`. It is used in logical operations and
decision-making.

Example:

python

x = 10
y = 20
print(x > y) # Output: False
print(x < y) # Output: True

2) What are the conditional statements used in Python?

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 15/36
1. `if` statement
2. `if-else` statement
3. `if-elif-else` statement

Example:

python

age = 18

if age >= 18:


print("Eligible to vote")
else:
print("Not eligible to vote")

3) Define `if-else` statements in Python.

An `if-else` statement checks a condition and executes one block of code if the condition is true and
another block if it is false.

Syntax:

python

if condition:
# Code when condition is true
else:
# Code when condition is false

Example:

python

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


if number % 2 == 0:
print("Even")
else:
print("Odd")

4) Write the syntax for the ternary operator in Python.

Syntax:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 16/36
python

result = value_if_true if condition else value_if_false

Example:

python

x, y = 10, 20
max_value = x if x > y else y
print(f"The maximum value is {max_value}") # Output: 20

5) Define chained conditionals.

Chained conditionals allow multiple conditions to be checked sequentially using `if-elif-else`.

Example:

python

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

if score >= 90:


print("Grade: A")
elif score >= 75:
print("Grade: B")
elif score >= 50:
print("Grade: C")
else:
print("Grade: F")

6) Write the syntax for `if-elif-else` conditionals.

Syntax:

python

if condition1:
# Code for condition1
elif condition2:
# Code for condition2
else:
# Code when all conditions are false

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 17/36
7) Define Iteration.

Iteration refers to repeating a block of code multiple times using loops like `for` or `while`.

Example:

python

for i in range(5):
print(i) # Output: 0 1 2 3 4

8) What are the different iterative statements?

1. `for` Loop: Iterates over a sequence.


2. `while` Loop: Executes as long as a condition is true.

9) Define `range()` function and its syntax.

The `range()` function generates a sequence of numbers.

Syntax:

python

range(start, stop, step)

Example:

python

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


print(i) # Output: 1 3 5 7 9

10) Define `while` loop.

The `while` loop repeatedly executes a block of code as long as a condition is true.

Syntax:

python

while condition:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 18/36
# Code block

Example:

python

n = 5
while n > 0:
print(n)
n -= 1 # Decrement

11) Write the syntax for nested `for` loops and `while` loops.

Nested `for` loop:

python

for i in range(3):
for j in range(2):
print(f"i={i}, j={j}")

Nested `while` loop:

python

i = 1
while i <= 3:
j = 1
while j <= 2:
print(f"i={i}, j={j}")
j += 1
i += 1

12) What is the Python `break` statement?

The `break` statement exits the current loop immediately.

Example:

python

for i in range(5):
if i == 3:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 19/36
break
print(i) # Output: 0 1 2

13) What is the Python `continue` statement?

The `continue` statement skips the rest of the code in the current iteration and moves to the next
iteration.

Example:

python

for i in range(5):
if i == 3:
continue
print(i) # Output: 0 1 2 4

14) Define fruitful functions in Python.

A fruitful function returns a value using the `return` statement.

Example:

python

def square(x):
return x * x

print(square(4)) # Output: 16

15) What are the types of parameters in functions?

1. Positional Parameters
2. Keyword Parameters
3. Default Parameters
4. Variable-length Parameters (`*args`, `**kwargs`)

16) What are the various parameter-passing techniques?

1. Call by Value: Modifications don’t affect the original variable.


2. Call by Reference: Modifications affect the original variable.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 20/36
17) Write the scope of a variable.

Local Scope: Variable inside a function.


Global Scope: Variable declared outside any function.

Example:

python

x = 10 # Global scope

def func():
y = 5 # Local scope
print(y)

func()
print(x)

18) What is a recursive function and its limitations?

A recursive function is a function that calls itself.

Limitations:

Requires a base case to avoid infinite recursion.


May cause stack overflow for deep recursion.

Example:

python

def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)

print(factorial(5)) # Output: 120

19) Write the merits of using functions in a program.

1. Code Reusability.
2. Improved Readability.
3. Simplifies Debugging.
4. Encourages Modularity.

20) Write the syntax for composition.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 21/36
Composition: Combining functions for complex operations.

Example:

python

def add(a, b):


return a + b

def square(x):
return x * x

result = square(add(2, 3))


print(result) # Output: 25

21) Define strings and name some methods.

A string is a sequence of characters enclosed in quotes.

Common methods:

`len()`, `lower()`, `upper()`, `split()`, `replace()`.

Example:

python

s = "Hello, World!"
print(s.upper()) # Output: HELLO, WORLD!

22) List some of the methods in list operations.

`append()`, `extend()`, `pop()`, `remove()`, `reverse()`.

Example:

python

lst = [1, 2, 3]
lst.append(4)
print(lst) # Output: [1, 2, 3, 4]

23) State the differences between linear search and binary search.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 22/36
Linear Search Binary Search
Searches sequentially. Divides and conquers.
O(n) time complexity. O(log n) time complexity.
Works on unsorted data. Requires sorted data.

Example of Linear Search:

python

def linear_search(arr, key):


for i in range(len(arr)):
if arr[i] == key:
return i
return -1

This concludes Unit III. Let me know if you'd like to proceed with Unit IV or need clarification!

proceed with unit 4

Let’s continue with Unit IV – Lists, Tuples, and Dictionaries, answering each question in detail with
examples and Python code.

Unit IV – Lists, Tuples, and Dictionaries

1) Define List.

A list in Python is a mutable, ordered collection of elements that can store different data types.

Example:

python

my_list = [1, "Bittu", 3.14, True]


print(my_list) # Output: [1, 'Bittu', 3.14, True]

2) What is cloning of List?

Cloning a list creates a copy of the list.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 23/36
Example:

python

original = [1, 2, 3]
cloned = original[:]
print(cloned) # Output: [1, 2, 3]

3) What is aliasing?

Aliasing means creating a reference to the same list, where changes to one list affect the other.
Example:

python

list1 = [1, 2, 3]
list2 = list1 # Both refer to the same list
list2.append(4)
print(list1) # Output: [1, 2, 3, 4]

4) Define Tuple.

A tuple is an immutable, ordered collection of elements.


Example:

python

my_tuple = (1, "Abirami", 3.14)


print(my_tuple) # Output: (1, 'Abirami', 3.14)

5) Explain Tuple Assignment with Example.

Tuple assignment allows assigning multiple values simultaneously.


Example:

python

a, b, c = (1, 2, 3)
print(a, b, c) # Output: 1 2 3

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 24/36
6) What is slicing?

Slicing is used to extract a portion of a list or tuple.


Syntax:

python

sequence[start:end:step]

Example:

python

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

7) Define Dictionary.

A dictionary in Python is an unordered collection of key-value pairs.

Example:

python

my_dict = {"name": "Bittu", "age": 20}


print(my_dict) # Output: {'name': 'Bittu', 'age': 20}

8) Give an example for List Comprehension.

List comprehension is a concise way to create lists.

Example:

python

squares = [x**2 for x in range(5)]


print(squares) # Output: [0, 1, 4, 9, 16]

9) What is mutability?

Mutability refers to the ability to modify an object after its creation.


Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 25/36
Lists: Mutable.
Tuples: Immutable.

Example:

python

# Mutable List
lst = [1, 2, 3]
lst[0] = 10
print(lst) # Output: [10, 2, 3]

# Immutable Tuple
tpl = (1, 2, 3)
# tpl[0] = 10 # This will raise an error

10) List the functions of tuple data type.

Function Description
`count()` Returns count of an element.
`index()` Returns index of an element.

Example:

python

tpl = (1, 2, 2, 3)
print(tpl.count(2)) # Output: 2
print(tpl.index(3)) # Output: 3

11) List the methods of list data type.

Method Description
`append()` Adds an element to the list.
`remove()` Removes an element by value.
`pop()` Removes and returns the last element.
`extend()` Extends the list with another list.

Example:

python

lst = [1, 2, 3]
lst.append(4)

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 26/36
print(lst) # Output: [1, 2, 3, 4]

12) Comment on Tuple as Return Type.

A function can return multiple values using tuples.


Example:

python

def get_coordinates():
return (10, 20)

x, y = get_coordinates()
print(x, y) # Output: 10 20

13) When is a dictionary used instead of a list?

Use a dictionary when data needs to be accessed by a key instead of an index.

Example:

python

# Using a dictionary for name-age pairs


people = {"Bittu": 20, "Abirami": 22}
print(people["Bittu"]) # Output: 20

14) Differentiate between `append()` and `extend()` methods.

Method Functionality
`append()` Adds a single element to the list.
`extend()` Adds all elements of an iterable to the list.

Example:

python

lst = [1, 2]
lst.append([3, 4])
print(lst) # Output: [1, 2, [3, 4]]

lst = [1, 2]

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 27/36
lst.extend([3, 4])
print(lst) # Output: [1, 2, 3, 4]

15) What is the output of `print(list + tiny_list)`?

python

list = ['abcd', 786, 2.23, 'john', 70.2]


tiny_list = [123, 'john']
print(list + tiny_list)
# Output: ['abcd', 786, 2.23, 'john', 70.2, 123, 'john']

16) What is the difference between Tuples and Lists in Python?

Tuples Lists
Immutable Mutable
Uses parentheses `()` Uses square brackets `[]`
Faster due to immutability Slower due to mutability

17) What is the difference between `del()` and `remove()` methods of a list?

Method Functionality
`del()` Deletes an element by index.
`remove()` Removes an element by value.

Example:

python

lst = [1, 2, 3]
del lst[1]
print(lst) # Output: [1, 3]

lst.remove(3)
print(lst) # Output: [1]

18) How to merge two dictionaries?

Method 1: Using `update()`

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 28/36
python

dict1 = {'a': 1}
dict2 = {'b': 2}
dict1.update(dict2)
print(dict1) # Output: {'a': 1, 'b': 2}

Method 2: Using `**`

python

dict1 = {'a': 1}
dict2 = {'b': 2}
merged_dict = {**dict1, **dict2}
print(merged_dict) # Output: {'a': 1, 'b': 2}

19) Define mutable and immutable data types.

Mutable: Data types that can be changed after creation (e.g., lists, dictionaries).
Immutable: Data types that cannot be changed after creation (e.g., strings, tuples).

20) When is a dictionary used instead of a list?

Use a dictionary when the relationship between data can be represented as key-value pairs.

Example:

python

# Dictionary for storing student marks


marks = {"Bittu": 90, "Abirami": 95}
print(marks["Abirami"]) # Output: 95

This concludes Unit IV. Let me know if you'd like to proceed with Unit V or need clarification!

continue

Please let me know if you'd like to continue with Unit V – Files and Exceptions, or if you have a specific
question or need clarification on anything from the previous units!

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 29/36
yes

Let’s proceed with Unit V – Files and Exceptions, answering each question in detail with examples and
Python code.

Unit V – Files and Exceptions

1) What is a file in Python?

A file in Python is a storage unit on a disk where data is stored in a specific format, such as text or
binary. Python allows file operations like reading, writing, and appending.
Example:

python

# Creating and writing to a file


file = open("example.txt", "w")
file.write("Hello, World!")
file.close()

2) List the file modes in Python.

Mode Description
`"r"` Read mode (default).
`"w"` Write mode (overwrites file).
`"a"` Append mode.
`"rb"`, `"wb"` Read/Write in binary mode.

`"r+"` Read and write.

3) What is the syntax for opening a file?

Syntax:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 30/36
python

file_object = open(filename, mode)

Example:

python

file = open("data.txt", "r")

4) Write a Python program to create a text file and write data into it.

python

# Writing data into a file


file = open("myfile.txt", "w")
file.write("Welcome to Python Programming!")
file.close()

print("Data written to file successfully.")

5) How do you read the content of a file in Python?

Use the `read()` or `readlines()` method to read file content.


Example:

python

# Reading file content


file = open("myfile.txt", "r")
content = file.read()
print(content) # Output: Welcome to Python Programming!
file.close()

6) Differentiate between `read()` and `readlines()` methods.

Method Functionality
`read()` Reads the entire file as a single string.
`readlines()` Reads the file line by line and returns a list of lines.

Example:
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 31/36
python

file = open("example.txt", "r")

# Using read()
print(file.read())

# Using readlines()
file.seek(0) # Reset cursor
print(file.readlines())

file.close()

7) Write a Python program to count the number of words in a file.

python

# Counting words in a file


file = open("example.txt", "r")
content = file.read()
words = content.split()
print(f"Number of words: {len(words)}")
file.close()

8) Explain the use of the `with` statement in file handling.

The `with` statement ensures that files are automatically closed after their operations are complete.

Example:

python

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


content = file.read()
print(content) # File is automatically closed after this block

9) What are exceptions in Python?

Exceptions are errors detected during program execution that disrupt normal flow. Python provides
mechanisms to handle exceptions gracefully.

Example:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 32/36
python

try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")

10) What is exception handling?

Exception handling refers to managing errors in a program using `try`, `except`, `else`, and `finally`
blocks.

11) Write the syntax for `try`, `except`, `else`, and `finally` blocks.

Syntax:

python

try:
# Code that may raise an exception
except ExceptionType:
# Code to handle the exception
else:
# Code that runs if no exception occurs
finally:
# Code that always runs (optional)

12) Write a Python program to handle a division by zero exception.

python

try:
num = int(input("Enter numerator: "))
denom = int(input("Enter denominator: "))
result = num / denom
print(f"Result: {result}")
except ZeroDivisionError:
print("Error: Cannot divide by zero!")

13) List some commonly used exceptions in Python.

Exception Description
`ZeroDivisionError` Raised when dividing by zero.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 33/36
Exception Description
`ValueError` Raised for invalid input value.
`FileNotFoundError` Raised when a file is not found.
`TypeError` Raised for incompatible types.

14) Write a Python program to raise a custom exception.

python

class CustomError(Exception):
pass

try:
raise CustomError("This is a custom error!")
except CustomError as e:
print(e)

15) Explain the `raise` statement in Python.

The `raise` statement is used to explicitly raise an exception.


Example:

python

def check_age(age):
if age < 18:
raise ValueError("Age must be at least 18.")
print("Age is valid.")

check_age(15) # Raises ValueError

16) Write a Python program to handle multiple exceptions.

python

try:
x = int(input("Enter a number: "))
print(10 / x)
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except ValueError:
print("Error: Invalid input!")

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 34/36
17) Explain the importance of the `finally` block.

The `finally` block executes regardless of whether an exception occurs or not, making it useful for
cleanup operations like closing files or releasing resources.
Example:

python

try:
file = open("example.txt", "r")
print(file.read())
except FileNotFoundError:
print("File not found!")
finally:
print("Closing file.")
file.close()

18) Write a Python program to find the largest number in a file.

python

# Assuming numbers are stored one per line in "numbers.txt"


with open("numbers.txt", "r") as file:
numbers = [int(line.strip()) for line in file]
largest = max(numbers)
print(f"Largest number: {largest}")

19) Explain the difference between syntax errors and exceptions.

Syntax Errors Exceptions


Occur during compilation or parsing. Occur during program execution.
Program won’t run. Program can continue with handling.

20) Write a Python program to copy the content of one file into another.

python

with open("source.txt", "r") as src, open("destination.txt", "w") as dest:


dest.write(src.read())
print("Content copied successfully.")

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 35/36
This concludes Unit V. Let me know if you need further explanation or assistance with any specific
questions!

Messages beyond this point are only visible to you

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 36/36

You might also like