Ge 3151
Ge 3151
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:
Let’s begin:
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.
For example, designing an algorithm to sort data efficiently within limited time and space constraints
can be challenging.
Hardware Software
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?
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
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 3/36
else:
print(f"The largest number is {C}")
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!
Let’s continue answering the remaining questions for Unit I - Algorithmic Problem Solving, ensuring
detailed explanations with examples.
Input Statement: A command that allows the user to provide data to the program during
execution.
Example:
python
python
print("Hello, World!")
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 4/36
python
x = 5
Classification:
A flowchart is a diagram that represents the flow of a program using symbols like ovals (start/end),
rectangles (processes), and diamonds (decisions).
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
Symbol Purpose
1. Time-consuming to create.
2. Difficult to update for large programs.
3. Limited flexibility compared to pseudocode.
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.
plaintext
START
INPUT A, B
IF A > B THEN
PRINT "A is bigger"
ELSE
PRINT "B is bigger"
END
STOP
Python Code:
python
if A > B:
print("A is bigger")
else:
print("B is bigger")
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
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.
Let's proceed with Unit II – Data Types, Expressions, and Statements, answering each question with
detailed explanations, examples, and Python code.
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
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.
Syntax:
python
variable_name = value
Example:
python
x = 10
name = "Bittu"
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
Keywords Purpose
`if`, `else`, `elif` Conditional statements.
`for`, `while` Looping statements.
`def`, `return` Define and return from a function.
`import`, `from` Import modules.
Rules:
Syntax:
python
# This is a comment
Example:
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 10/36
python
python
x = 5 # x is an integer variable
y = "Bittu" # y is a string variable
python
python
print("Hello, World!")
`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]
python
result = (7 / 3) * 1.2 + (3 / 2)
print(result) # Output: 4.3
Syntax:
python
def function_name(parameters):
# Body of the function
return value
Example:
python
def greet(name):
return f"Hello, {name}!"
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
Example:
python
square = lambda x: x ** 2
print(square(5)) # Output: 25
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
Example:
python
import random
print(random.randint(1, 10))
Module Purpose
`math` Mathematical operations.
`os` File and directory operations.
`random` Random number generation.
python
python
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
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!
Let's continue with Unit III – Control Flow, Functions, and Strings, answering each question in detail
with examples and Python code.
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
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
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
Syntax:
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 16/36
python
Example:
python
x, y = 10, 20
max_value = x if x > y else y
print(f"The maximum value is {max_value}") # Output: 20
Example:
python
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
Syntax:
python
Example:
python
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.
python
for i in range(3):
for j in range(2):
print(f"i={i}, j={j}")
python
i = 1
while i <= 3:
j = 1
while j <= 2:
print(f"i={i}, j={j}")
j += 1
i += 1
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
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
Example:
python
def square(x):
return x * x
print(square(4)) # Output: 16
1. Positional Parameters
2. Keyword Parameters
3. Default Parameters
4. Variable-length Parameters (`*args`, `**kwargs`)
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 20/36
17) Write the scope of a variable.
Example:
python
x = 10 # Global scope
def func():
y = 5 # Local scope
print(y)
func()
print(x)
Limitations:
Example:
python
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
1. Code Reusability.
2. Improved Readability.
3. Simplifies Debugging.
4. Encourages Modularity.
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 21/36
Composition: Combining functions for complex operations.
Example:
python
def square(x):
return x * x
Common methods:
Example:
python
s = "Hello, World!"
print(s.upper()) # Output: HELLO, WORLD!
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.
python
This concludes Unit III. Let me know if you'd like to proceed with Unit IV or need clarification!
Let’s continue with Unit IV – Lists, Tuples, and Dictionaries, answering each question in detail with
examples and Python code.
1) Define List.
A list in Python is a mutable, ordered collection of elements that can store different data types.
Example:
python
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.
python
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?
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.
Example:
python
Example:
python
9) What is mutability?
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
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
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]
python
def get_coordinates():
return (10, 20)
x, y = get_coordinates()
print(x, y) # Output: 10 20
Example:
python
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]
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]
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}
python
dict1 = {'a': 1}
dict2 = {'b': 2}
merged_dict = {**dict1, **dict2}
print(merged_dict) # Output: {'a': 1, 'b': 2}
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).
Use a dictionary when the relationship between data can be represented as key-value pairs.
Example:
python
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.
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
Mode Description
`"r"` Read mode (default).
`"w"` Write mode (overwrites file).
`"a"` Append mode.
`"rb"`, `"wb"` Read/Write in binary mode.
Syntax:
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 30/36
python
Example:
python
4) Write a Python program to create a text file and write data into it.
python
python
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
# Using read()
print(file.read())
# Using readlines()
file.seek(0) # Reset cursor
print(file.readlines())
file.close()
python
The `with` statement ensures that files are automatically closed after their operations are complete.
Example:
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!")
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)
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!")
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.
python
class CustomError(Exception):
pass
try:
raise CustomError("This is a custom error!")
except CustomError as e:
print(e)
python
def check_age(age):
if age < 18:
raise ValueError("Age must be at least 18.")
print("Age is valid.")
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()
python
20) Write a Python program to copy the content of one file into another.
python
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!
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 36/36