0% found this document useful (0 votes)
2 views26 pages

Sessional 2 Python Question Bank Solver

Uploaded by

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

Sessional 2 Python Question Bank Solver

Uploaded by

ytg035690
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1) Discuss the purpose of break and continue

statement in loops
Answer:
In Python, break and continue are loop control statements. They are used
to change the normal flow of a loop.

1. Break Statement:
 It is used to exit the loop immediately.

 When break is executed, the loop stops and control goes outside the
loop.
Example:
for i in range(1, 6):
if i == 3:
break
print(i)
Output:
1
2

👉 Loop stops when i = 3

2. Continue Statement:
 It is used to skip the current iteration and move to the next
iteration.

 Loop does not stop, only skips that step.

Example:
for i in range(1, 6):
if i == 3:
continue
print(i)
Output:
1
2
4
5

👉 3 is skipped

Conclusion:
 Break → stops loop completely

 Continue → skips one iteration

2) Differentiate between for loop and while loop


with syntax and example
Answer:
Both loops are used for repetition, but they work differently.

Difference:
Feature For Loop While Loop
Use Used when number of iterations is Used when condition is
known based
Conditio Automatically controlled Manually controlled
n
Syntax Simple Needs condition update

1. For Loop Syntax:


for variable in range(start, stop):

statements

Example:
for i in range(1, 6):
print(i)
Output:
1 2 3 4 5
2. While Loop Syntax:
while condition:
statements
Example:
i=1
while i <= 5:
print(i)
i += 1
Output:
1 2 3 4 5

Conclusion:
 For loop → fixed iterations

 While loop → condition-based iterations

3) What is the use of list in Python?


Answer:
A list in Python is a data structure used to store multiple items in a single
variable.

Uses of List:
 It stores multiple values together

 It can store different data types (int, string, float, etc.)

 It is ordered and changeable (mutable)

 It allows duplicate values

Example:
my_list = [10, 20, 30, "Hello", 5.5]
print(my_list)
Output:
[10, 20, 30, 'Hello', 5.5]

Accessing Elements:
print(my_list[1])
👉 Output: 20

Conclusion:
 List is used to store and manage multiple values easily

 It is very useful in programs where we need collection of data

4) Explain the string data type with suitable


example
Answer:
A string is a data type in Python used to store text or characters.
 Strings are written inside single (' ') or double (" ") quotes

 It is an immutable data type (cannot be changed)

Example:
name = "Rahul"
print(name)
Output:
Rahul

String Operations:
1. Concatenation:
a = "Hello"
b = "World"
print(a + " " + b)
👉 Output: Hello World

2. Length of String:
print(len(name))
👉 Output: 5

Conclusion:
 String is used to store text data

 It is immutable and widely used in Python programs

5) What is the purpose of set in Python?


Answer:
A set in Python is a collection of unique elements.

Purpose of Set:
 It is used to store unique values only

 It removes duplicate values automatically

 It is unordered (no fixed position of elements)

 It is useful for mathematical operations like union, intersection

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

👉 Duplicate value (3) is removed

Common Operations:
1. Add element:
my_set.add(5)

2. Remove element:
my_set.remove(2)

Conclusion:
 Set is used when we need unique and unordered data

 It helps in removing duplicates easily

6) Define floor division with example


Answer:
Floor division in Python is used to divide two numbers and return the
largest integer less than or equal to the result.
👉 It is represented by //

Example 1:
print(10 // 3)

Output:
3

👉 Because 10 ÷ 3 = 3.33 → floor value = 3

Example 2:
print(10 // 4)

Output:
2

👉 Because 10 ÷ 4 = 2.5 → floor value = 2

Example 3 (Negative case):


print(-10 // 3)
Output:
-4

👉 Floor goes to lower integer (not toward zero)

Conclusion:
 // gives integer result

 It always rounds down to nearest integer

7) Explain the iteration and write a program to


demonstrate the Tower of Hanoi
Answer:
Iteration:
Iteration means repeating a set of instructions multiple times using loops
like for and while.
👉 It helps to reduce code repetition and makes programs efficient.

Tower of Hanoi:
It is a famous problem where:
 We have 3 rods (A, B, C)

 Some disks are placed on rod A

 Goal is to move all disks to rod C

 Rules:

a. Only one disk can be moved at a time

b. Bigger disk cannot be placed on smaller disk

Program:
def hanoi(n, source, auxiliary, destination):
if n == 1:
print("Move disk 1 from", source, "to", destination)
return
hanoi(n-1, source, destination, auxiliary)
print("Move disk", n, "from", source, "to", destination)
hanoi(n-1, auxiliary, source, destination)
# Example

n=3

hanoi(n, 'A', 'B', 'C')

Conclusion:
 Iteration means repeating steps

 Tower of Hanoi is solved using recursion (repeated steps)

8) Explain all the conditional statements in Python


using small code examples
Answer:
Conditional statements are used to make decisions in a program.

1. if Statement:
Executes code if condition is true.
x = 10
if x > 5:
print("Greater")

2. if-else Statement:
Executes one block if true, otherwise another.
x=3
if x > 5:
print("Greater")
else:
print("Smaller")

3. if-elif-else Statement:
Used when there are multiple conditions.
x=0
if x > 0:
print("Positive")
elif x < 0:
print("Negative")
else:
print("Zero")

4. Nested if:
if inside another if.
x = 10
if x > 5:
if x < 20:
print("Between 5 and 20")

Conclusion:
 if → single condition

 if-else → two choices

 if-elif-else → multiple conditions

 Used for decision making


9) What do you mean by operator precedence and
associativity? Explain
Answer:
Operator Precedence:
Operator precedence means the order in which operations are
performed in an expression.
👉 Higher precedence operator is executed first.

Example:
result = 10 + 5 * 2
print(result)
Output:
20

👉 First 5 * 2 = 10, then 10 + 10 = 20


👉 Because * has higher precedence than +

Associativity:
Associativity tells the direction of evaluation when operators have same
precedence.
👉 It can be:
 Left to Right

 Right to Left

Example:
result = 10 - 5 - 2
print(result)
Output:
3

👉 Evaluated as: (10 - 5) - 2 = 3


👉 Because - is left to right
Conclusion:
 Precedence → which operator first

 Associativity → direction of execution

10) Discuss the use of nested loop in Python and


write a program to print right angle triangle of star
(*)
Answer:
Nested Loop:
A nested loop means a loop inside another loop.
👉 Outer loop controls rows
👉 Inner loop controls columns

Use:
 Used for pattern printing

 Used in matrix operations

 Used when we need multi-level repetition

Program (Right Angle Triangle):


for i in range(1, 6):
for j in range(i):
print("*", end=" ")
print()

Output:
*
* *
* * *
* * * *
* * * * *
Conclusion:
 Nested loop is used for complex repetition

 Very useful in pattern programs

11) Explain function in Python with syntax and


example
Answer:
A function in Python is a block of code that performs a specific task.
👉 It helps in:
 Code reuse

 Better readability

 Reducing repetition

Syntax:
def function_name(parameters):
statements

Example:
def greet():
print("Hello World")

greet()
Output:
Hello World

Function with Parameters:


def add(a, b):
print(a + b)
add(5, 3)
👉 Output: 8

Conclusion:
 Function = reusable block of code

 Makes program simple and organized

12) Explain different types of function arguments


in Python
Answer:
In Python, function arguments are used to pass values to functions.

Types of Arguments:

1. Positional Arguments:
Values are passed in the correct order.
def add(a, b):
print(a + b)

add(2, 3)
👉 Output: 5

2. Keyword Arguments:
Values are passed using parameter names.
add(a=2, b=3)

3. Default Arguments:
Function has default values.
def greet(name="User"):
print("Hello", name)

greet()

👉 Output: Hello User

4. Variable Length Arguments:


Used when number of arguments is not fixed.
def total(*numbers):

print(sum(numbers))

total(1, 2, 3, 4)

👉 Output: 10

Conclusion:
 Arguments help to pass data to functions

 Different types make functions flexible

13) What is recursion? Explain with example


Answer:
Recursion is a technique in which a function calls itself to solve a problem.
👉 It is useful for problems that can be divided into smaller sub-problems

Key Points:
 A recursive function must have a base case (to stop recursion)

 Without base case, it will run infinitely


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

print(factorial(5))

Output:
120

👉 Calculation:
5 × 4 × 3 × 2 × 1 = 120

Conclusion:
 Recursion = function calling itself

 Needs base condition to stop

14) Explain Python modules and packages


Answer:
Module:
A module is a file that contains Python code (functions, variables, etc.)
👉 It helps to organize code and reuse it

Example:
# [Link]
def add(a, b):
return a + b
Using module:
import mymodule
print([Link](2, 3))

Package:
A package is a collection of multiple modules in a folder.
👉 It helps to organize large programs into folders

Structure Example:
mypackage/
[Link]
[Link]

Conclusion:
 Module = single file

 Package = collection of modules

 Both help in code organization and reuse

15) Explain file handling in Python with example


Answer:
File handling in Python is used to create, read, write and update files.
👉 It helps to store data permanently.

Steps in File Handling:


1. Open the file

2. Perform operation (read/write)

3. Close the file

Modes of File:
 'r' → Read

 'w' → Write
 'a' → Append

Example (Write in file):


file = open("[Link]", "w")
[Link]("Hello World")
[Link]()

Example (Read file):


file = open("[Link]", "r")
print([Link]())
[Link]()

Conclusion:
 File handling is used to store and manage data in files

 Important for real-world applications

16) Explain exception handling in Python with


example
Answer:
Exception handling is used to handle errors during program execution
so that program does not crash.

Keywords Used:
 try → code that may cause error

 except → handles error

 finally → always executes

Example:
try:
a = 10
b=0
print(a / b)
except:
print("Error: Division by zero")
finally:
print("Program finished")

Output:
Error: Division by zero
Program finished

Conclusion:
 Prevents program crash

 Helps in safe execution of code

17) What is dictionary in Python? Explain with


example
Answer:
A dictionary in Python is a data structure used to store data in key-value
pairs.
👉 Each value is associated with a unique key

Features:
 Stores data as key : value

 It is mutable (changeable)

 Keys must be unique

 It is unordered
Example:
student = {
"name": "Rahul",
"age": 20,
"marks": 85
}

print(student)
Output:
{'name': 'Rahul', 'age': 20, 'marks': 85}

Accessing Value:
print(student["name"])

👉 Output: Rahul

Conclusion:
 Dictionary is used to store data in pair form

 Very useful for real-life data (like student info)

18) Explain tuple in Python with example


Answer:
A tuple in Python is a collection used to store multiple items.
👉 It is similar to list but immutable (cannot be changed)

Features:
 Written using ( ) brackets

 Allows duplicate values

 Ordered collection
 Cannot be modified

Example:
my_tuple = (10, 20, 30, 20)
print(my_tuple)
Output:
(10, 20, 30, 20)

Accessing Elements:
print(my_tuple[1])

👉 Output: 20

Conclusion:
 Tuple is used when data should be fixed (unchangeable)

 Faster than list

19) Explain lambda function in Python with


example
Answer:
A lambda function is a small anonymous function (function without
name).
👉 It is used for short and simple operations

Syntax:
lambda arguments : expression

Example:
add = lambda a, b: a + b
print(add(3, 5))
Output:
8

Another Example:
square = lambda x: x * x

print(square(4))
👉 Output: 16

Conclusion:
 Lambda = small one-line function

 Used to make code short and simple

20) What is list comprehension? Explain with


example
Answer:
List comprehension is a short and easy way to create lists using a
single line of code.
👉 It makes code faster and cleaner

Syntax:
[expression for item in iterable if condition]

Example 1:
numbers = [x for x in range(1, 6)]

print(numbers)
Output:
[1, 2, 3, 4, 5]

Example 2 (with condition):


even = [x for x in range(1, 11) if x % 2 == 0]

print(even)

👉 Output: [2, 4, 6, 8, 10]

Conclusion:
 List comprehension is used to create lists quickly

 Makes code short and readable

21) Explain map() function in Python with example


Answer:
The map() function is used to apply a function to each element of an
iterable (like list).
👉 It helps to perform operation on all elements easily

Syntax:
map(function, iterable)

Example:
numbers = [1, 2, 3, 4]

square = list(map(lambda x: x*x, numbers))

print(square)

Output:
[1, 4, 9, 16]
Explanation:
 Each element is passed to lambda function

 Square of each number is calculated

Conclusion:
 map() is used to apply function on all elements

 Makes code short and efficient

22) Explain filter() function in Python with example


Answer:
The filter() function is used to select only those elements from a list that
satisfy a condition.

Syntax:
filter(function, iterable)

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

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

print(even)

Output:
[2, 4, 6]

Explanation:
 It checks condition (even numbers)

 Only true values are returned


Conclusion:
 filter() is used to select required elements

 Helps in data filtering

23) Explain reduce() function in Python with


example
Answer:
The reduce() function is used to apply a function on all elements of a list
and reduce them to a single value.
👉 It is available in functools module

Syntax:
from functools import reduce
reduce(function, iterable)

Example:
from functools import reduce

numbers = [1, 2, 3, 4]

result = reduce(lambda a, b: a + b, numbers)

print(result)

Output:
10

Explanation:
 It adds elements step by step

 ((1+2)=3 → 3+3=6 → 6+4=10)


Conclusion:
 reduce() is used to get single output from list

 Useful for sum, product, etc.

24) Explain difference between local and global


variables in Python
Answer:
Variables in Python are of two types based on scope:
👉 Local variable and Global variable

1. Local Variable:
 Declared inside a function

 Can be used only inside that function

Example:
def my_func():
x = 10
print(x)

my_func()

2. Global Variable:
 Declared outside the function

 Can be used anywhere in the program

Example:
x = 20

def my_func():
print(x)

my_func()

Difference:
Featur Local Global
e Variable Variable
Scope Inside Whole
function program
Acces Limited Everywhere
s

Conclusion:
 Local → limited scope

 Global → wide scope

You might also like