0% found this document useful (0 votes)
15 views84 pages

Question Bank for Python_Answerkey

The document is a question bank covering various topics in Python programming, including its history, key features, data types, control flow statements, and functions. It includes multiple-choice questions, programming exercises, and explanations of concepts such as recursion, variable scope, and string manipulation. Each section provides examples and code snippets to illustrate the concepts discussed.

Uploaded by

190020107043ait
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)
15 views84 pages

Question Bank for Python_Answerkey

The document is a question bank covering various topics in Python programming, including its history, key features, data types, control flow statements, and functions. It includes multiple-choice questions, programming exercises, and explanations of concepts such as recursion, variable scope, and string manipulation. Each section provides examples and code snippets to illustrate the concepts discussed.

Uploaded by

190020107043ait
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/ 84

Question Bank

2 marks Questions
UNIT-I: INTRODUCTION
1. What is the history of Python programming language?
python was created by Guido van Rossum in the late 1980s at the
National Research Institute for Mathematics and Computer Science 1
(CWI) in the Netherlands. It was conceived as a successor to the ABC
language and first released in 1991. Its design philosophy emphasizes
code readability with notable use of significant whitespace
2. List four key features of Python.
Readability: Python's syntax is designed to be clean and easy to
understand.
Interpreted: Python code is executed line by line, making debugging
easier.
Dynamically Typed: You don't need to declare the type of a variable.
Extensive Libraries: Python has a large standard library and a vast
ecosystem of third-party packages.

3. Explain the purpose of quotations in Python with an example.


Quotations in Python are used to define string literals. They tell Python
that the enclosed characters should be treated as text, not code.
message = "Hello, Python!"
print(message)

4. Describe the significance of indentation in Python programming.


indentation in Python is crucial for defining code blocks. Unlike many
other languages that use curly braces, Python uses whitespace (spaces or
tabs) to indicate which statements belong to a particular block of code
(e.g., within a loop, conditional statement, or function). Consistent
indentation is essential for the correct execution of Python programs.
5. Write a simple Python program to print "Hello, World!".
→ print("Hello, World!")
6. Demonstrate how to use input operations to accept a user’s name and
display it.
→name = input("Enter your name: ")
print("Hello,", name + "!")

7. Differentiate between single-line and multi-line statements in Python.


A single-line statement is a complete instruction that fits on one line of
code. A multi-line statement spans across multiple lines, often used for
readability with longer expressions or code blocks. You can explicitly
break a long statement using a backslash \ or implicitly within
parentheses (), square brackets [], or curly braces {}

8. Compare the use of single, double, and triple quotations in Python.


Single quotes ('...') and double quotes ("...") are largely
interchangeable and used to represent string literals. They are useful
when the string itself contains the other type of quote (e.g., "He said,
'Hello!'" or 'It\'s a beautiful day').
Triple quotes ('''...''' or """...""") are used for multi-line strings and
docstrings (documentation strings used to explain what a function, class,
or module does).

9. Assess the importance of Python’s interactive mode for beginners.


Python's interactive mode which is incredibly valuable for beginners. It
allows you to execute small snippets of code and immediately see the
results. This instant feedback helps in understanding basic concepts,
experimenting with syntax, and debugging simple errors without having
to write and run an entire program.
10. Design a Python program that takes two numbers as input and prints
their sum.
num1_str = input("Enter the first number: ")
num2_str = input("Enter the second number: ")
num1 = float(num1_str)
num2 = float(num2_str)
sum_result = num1 + num2
print("The sum is:", sum_result)

UNIT-II: DATA, EXPRESSIONS, STATEMENTS


11. Define the term "variable" in Python.
In Python, a variable is a name given to a memory location that holds a
value. It acts as a symbolic reference to that data, allowing you to access
and manipulate it throughout your program. Think of it like a label
attached to a container
12. List the basic data types in Python.

The basic data types in Python are:

int: Integers (whole numbers), e.g., 10, -5.

● float: Floating-point numbers (numbers with decimal points), e.g., 3.14,


-0.001.
● str: Strings (sequences of characters), e.g., "hello", 'world'.
● bool: Booleans (representing truth values), either True or False.
● NoneType: Represents the absence of a value, denoted by None
13. Explain the precedence of operators in Python with an example.
Operator precedence determines the order in which operations are
performed in an expression. Python follows a specific order (similar to
mathematical conventions). For example, multiplication and division
have higher precedence than addition and subtraction. Parentheses can be
used to override this 1 order.
it folows PEMDAS ORDER:
parenthesis>exponential>multiplication>division>addition>substraction
example:
result = 2 + 3 * 4 # Multiplication (3 * 4 = 12) happens before addition
(2 + 12 = 14)
print(result)
# Output: 14
result_with_parentheses = (2 + 3) * 4 # Addition (2 + 3 = 5) happens
first due to parentheses, then multiplication (5 * 4 = 20)
print(result_with_parentheses)
# Output: 20

14. Describe how tuple assignment works in Python.

Tuple assignment allows you to assign values to multiple variables


simultaneously using a tuple on the left-hand side of the assignment
operator. The number of variables on the left must match the number of
elements in the tuple on the right. Python unpacks the tuple and assigns
the corresponding values to the variables.

code
point = (10, 20)
x, y = point # x gets 10, y gets 20
print(f"x: {x}, y: {y}")
a, b, c = 1, "hello", True # Assigning multiple values at once
print(f"a: {a}, b: {b}, c: {c}")
15. Write a Python program to exchange the values of two variables.
a=5
b = 10
# Method 1: Using a temporary variable
temp = a
a=b
b = temp
print(f"After exchange (using temp): a = {a}, b = {b}")
#Method 2: Using tuple assignment (more Pythonic)
x=5
y = 10
x, y = y, x
print(f"After exchange (using tuple assignment): x = {x}, y = {y}")

16. Create a program to calculate the distance between two points using
coordinates.
import math
x1 = float(input("Enter x-coordinate of the first point: "))
y1 = float(input("Enter y-coordinate of the first point: "))
x2 = float(input("Enter x-coordinate of the second point: "))
y2 = float(input("Enter y-coordinate of the second point: "))
distance = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
print(f"The distance between the two points is: {distance}")
17. Compare the use of comments and expressions in a Python program.
Comments are explanatory notes added to the code to make it more
understandable for humans. They are ignored by the Python interpreter.
Comments start with a # and can be single-line or multi-line (using triple
quotes, though these are often used for docstrings).
Expressions are combinations of values, variables, operators, and
function calls that evaluate to a value. They represent computations or
data retrieval that the Python interpreter executes.
In essence, comments are for human readers, while expressions are
instructions for the computer to execute.
18. Analyze how Python’s interactive mode differs from script mode.
Interactive Mode: You type and execute Python code one line (or a
block) at a time. The interpreter reads your input, evaluates it, and prints
the result immediately (REPL: Read-Eval-Print Loop). It's great for quick
testing, exploration, and learning.
Script Mode: You write a complete Python program in one or more files
(with a .py extension). You then execute the entire script using the
Python interpreter (python your_script.py). This is used for
developing larger applications and reusable code.

19. Justify the need for type conversion in Python expressions.


Type conversion (also known as type casting) is necessary when you want
to perform operations on values of different data types that are not
automatically compatible. For example, you can't directly add a string to
an integer. You need to explicitly convert one of them to the other type to
perform the operation.

num_str = "10"
num_int = 5
# print(num_str + num_int) # This would raise a TypeError
sum_result = int(num_str) + num_int # Convert the string to an integer
before adding
print("The sum is:", sum_result)
20. Design a program to circulate the values of three variables (e.g.,
a→b, b→c, c→a).

a=1
b=2
c=3
print(f"Before circulation: a = {a}, b = {b}, c = {c}")

# Method 1: Using a temporary variable


temp = a
a=c
c=b
b = temp
print(f"After circulation (using temp): a = {a}, b = {b}, c = {c}")

# Method 2: Using tuple assignment (more Pythonic)


x=1
y=2
z=3
x, y, z = z, x, y
print(f"After circulation (using tuple assignment): x = {x}, y = {y}, z =
{z}")
UNIT-III: CONTROL FLOW STATEMENTS AND STRINGS

21. What is the purpose of the "break" statement in Python?

The break statement is used to immediately terminate the innermost


loop (either a for or a while loop) it is encountered in. The program
execution then resumes at the statement immediately following the
terminated loop. It's often used to exit a loop prematurely based on a
certain condition.

22. List three in-built string methods in Python.

here are three handy built-in string methods:

.upper(): Returns a new string where all characters are converted to


uppercase.

.lower(): Returns a new string where all characters are converted to


lowercase.

.strip(): Returns a new string with leading and trailing whitespace


removed.

23. Explain the difference between "while" and "for" loops in Python.

A while loop executes a block of code repeatedly as long as a specified


condition remains true. You typically use it when you don't know in
advance how many times the loop needs to iterate, and the termination
depends on a changing condition.
A for loop iterates over a sequence (like a list, tuple, string, or the result
of a range() function) and executes a block of code for each item in
the sequence. It's ideal when you know the number of iterations
beforehand.
24. Describe how string slicing works with an example.

String slicing allows you to extract a portion (substring) of a string by


specifying a range of indices.

The syntax is string[start:end:step].

start: The index where the slice begins (inclusive, defaults to 0 if


omitted).

end: The index where the slice ends (exclusive, defaults to the end of the
string if omitted).

step: The increment between indices (defaults to 1 if omitted).

my_string = "PythonIsFun"

print(my_string[0:6]) # Output: Python (characters from index 0 up to,


but not including, 6)

print(my_string[:6]) # Output: Python (start index is assumed to be 0)

print(my_string[6:]) # Output: IsFun (end index is assumed to be the


end of the string)

print(my_string[::2]) # Output: PtoFu (every second character)

print(my_string[::-1]) # Output: nuSfIsnohtyP (reversing the string)


25. Write a Python program using an if-elif-else statement to check if a
number is positive, negative, or zero.
number = float(input("Enter a number: "))
if number > 0:
print("The number is positive.")
elif number < 0:
print("The number is negative.")
else:
print("The number is zero.")

26. Demonstrate the use of a for loop to print the characters of a string.
text = "Hello"
for char in text:
print(char)

27. Differentiate between the "continue" and "pass" statements with


examples.
The continue statement skips the rest of the code within the current
iteration of a loop and moves to the next iteration.
for i in range(5):
if i == 3:
continue # Skip the rest of the loop body when i is 3
print(i)
# Output: 0, 1, 2, 4
The pass statement is a null operation; nothing happens when it is
executed. It is used as a placeholder where a statement is syntactically
required but you don't want any code to be executed.
def my_function():
pass # Placeholder for future implementation
if True:
pass # Syntactically required, but no action needed
28. Compare nested if statements and if-elif-else statements in terms
of readability.

Nested if statements involve placing one if statement inside another.


While they allow for complex conditional logic, deeply nested if
statements can become harder to read and follow, potentially leading to
"spaghetti code." It can be difficult to track which conditions must be true
to reach a particular block of code.

if-elif-else statements provide a more structured and often more


readable way to handle multiple mutually exclusive conditions. The
conditions are checked sequentially, and the block of code associated with
the first true condition is executed. Once a condition is met, the rest of the
elif and else blocks are skipped. This structure makes the logic
clearer and easier to understand.

Generally, if-elif-else is preferred for handling a series of distinct


choices as it improves readability and avoids deep indentation. Nested if
statements are more appropriate when you need to check a secondary condition
only after a primary condition is already true.

29. Assess the effectiveness of string formatting operations in Python.

String formatting operations in Python are highly effective for creating dynamic
and readable strings by embedding variables or expressions within string
literals. Python offers several powerful methods:

● %-formatting (older style): While still functional, it's less readable and
prone to errors if the types don't match.
● .format() method: This is a more versatile and readable approach,
allowing you to use positional or keyword arguments for substitution.
● f-strings (formatted string literals - Python 3.6+): This is the most
modern and often the most concise and readable way to format strings.
You can directly embed expressions inside curly braces {} within the
string.
F-strings, in particular, enhance code clarity and reduce verbosity, making string
formatting very effective in Python.

30. Design a program to reverse a string using a while loop.


input_string = input("Enter a string: ")
reversed_string = ""
index = len(input_string) - 1
while index >= 0:
reversed_string += input_string[index]
index -= 1
print("Reversed string:", reversed_string)
UNIT-IV: FUNCTIONS AND FILES

31. Define the term "recursion" in Python.


Recursion in Python is a programming technique where a function calls
itself directly or indirectly to solve a problem. A recursive function
typically has two parts:
a base case that stops the recursion
and
a recursive step that breaks the problem down into smaller, self-similar
subproblems and calls the function again with these subproblems.

32. List two format operators used in Python file operations.

When working with files in Python, especially with methods like

write() or when formatting data to be written, you might encounter

format operators similar to string formatting, although they are less

common with modern f-strings. Two examples are:

● %s: Format as a string.


● %d: Format as a decimal integer.

However, for file I/O, it's generally recommended to use the more flexible
.format() method or f-strings for better readability and control.
33. Explain the difference between local and global scope in Python
functions.

Local Scope:

Variables defined inside a function have local scope. They are only accessible
within that specific function. Once the function finishes executing, these
variables are destroyed.

Global Scope:
Variables defined outside of any function have global scope. They are
accessible from anywhere in the program, including inside functions.
However, to modify a global variable from within a function, you need to
explicitly declare it using the global keyword.

34. Describe how to read data from a file in Python.

You can read data from a file in Python using the open() function to
open the file and then various methods of the file object:

1. f = open("filename.txt", "r"): Opens the file in read mode


("r").
2. data = f.read(): Reads the entire content of the file as a single
string.
3. lines = f.readlines(): Reads all lines of the file and returns
them as a list of strings.
4. line = f.readline(): Reads a single line from the file, including
the newline character if present. You can call this method repeatedly to
read the file line by line.
5. You can also iterate over the file object directly to read it line by line
efficiently:

with open("filename.txt", "r") as f:


for line in f:
# Process each line
print(line.strip()) # Remove potential newline character
6.f.close(): It's crucial to close the file after you're done with it to release
system resources. The with open(...) statement automatically handles
closing the file, which is the recommended approach.

35. Write a Python function that returns the square of a number.


def square(number):
"""This function returns the square of a given number."""
return number ** 2

result = square(5)
print(result)
# Output: 25
36. Create a program to write "Hello, File!" to a text file.
try:
with open("my_file.txt", "w") as file:
file.write("Hello, File!\n")
print("Successfully wrote to my_file.txt")
except Exception as e:
print(f"An error occurred: {e}")
37. Compare function composition and recursion with examples.
Function Composition: This involves combining multiple functions to
create a more complex operation. The output of one function becomes the
input of another. It's a way to build functionality step-by-step
def add_two(x):
return x + 2
def multiply_by_three(y):
return y * 3
result = multiply_by_three(add_two(5)) # add_two(5) returns 7, then
multiply_by_three(7) returns 21
print(result)
# Output: 21
Recursion: As defined earlier, a function calls itself to solve a problem
by breaking it down into smaller, self-similar instances
def factorial_recursive(n):
if n == 0:
return 1 # Base case
else:
return n * factorial_recursive(n - 1) # Recursive step
result = factorial_recursive(5)
print(result) # Output: 120

38. Analyze the role of parameters in Python functions.

Parameters are variables listed inside the parentheses in a function definition.


They act as placeholders for the values (arguments) that will be passed to the
function when it is called. Parameters allow functions to be more flexible and
operate on different data without needing to be rewritten for each specific input.

● Positional Parameters: Arguments are passed based on their order in the


function call and are matched to the parameters in the same order.
● Keyword Arguments: Arguments are passed with the parameter name
followed by an equals sign (e.g., name="Alice"). This allows you to
pass arguments out of order and improves code readability.
● Default Parameter Values: You can provide default values for
parameters in the function definition. If an argument for that parameter is
not provided in the function call, the default value is used.
● *args (Arbitrary Positional Arguments): Allows a function to accept
any number of positional arguments, which are collected into a tuple.
● **kwargs (Arbitrary Keyword Arguments): Allows a function to
accept any number of keyword arguments, which are collected into a
dictionary.

Parameters are essential for making functions reusable and adaptable.


39. Evaluate the advantages of using return values in functions.

Using return values in functions offers several key advantages:

Modularity and Reusability: Functions can perform a specific task and


return a result, which can then be used by other parts of the program or
even by other functions. This promotes modularity and makes the code
more organized and reusable.

Data Flow and Communication: Return values facilitate the flow of


data between different parts of the program. A function can process data
and pass the result back to the caller for further use.

Calculation and Transformation: Functions designed for calculations or


data transformations rely on return values to provide the computed or
modified data.

Conditional Logic: Return values can be used to signal the outcome of a


function's execution, allowing the calling code to make decisions based
on the returned value (e.g., success or failure, a specific calculated value).

Avoiding Side Effects (Ideally): Functions that primarily rely on return


values tend to have fewer side effects (modifying global variables or
external state), which can make the code easier to understand and debug.
40. Design a recursive function to calculate the factorial of a number.
def factorial_recursive(n):
"""Calculates the factorial of a non-negative integer recursively."""
if n == 0:
return 1 # Base case: factorial of 0 is 1
elif n < 0:
return "Factorial is not defined for negative numbers" # Handling
invalid input
else:
return n * factorial_recursive(n - 1) # Recursive step
# Example usage
number = 5
result = factorial_recursive(number)
print(f"The factorial of {number} is {result}") # Output: The factorial of 5
is 120
number_negative = -2
result_negative = factorial_recursive(number_negative)
print(result_negative)
# Output: Factorial is not defined for negative numbers
UNIT-V: LIST, SET, TUPLES, DICTIONARIES
41. What is the difference between a list and a tuple in Python?

The primary difference lies in their mutability.

● List: Lists are mutable, meaning you can change their contents after
creation (add, remove, or modify elements). They are defined using
square brackets [].
● Tuple: Tuples are immutable, meaning once created, their contents
cannot be changed. They are defined using parentheses (), although the
parentheses are optional in some contexts.

Lists are typically used for collections of items where you might need to modify
the order or content, while tuples are used for collections of items that should
remain fixed.

42. List three dictionary methods in Python.

→three useful dictionary methods:

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

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

.items(): Returns a view object that displays a list of 1 key-value pairs


(tuples) in the dictionary.

43. Explain the concept of mutability in Python lists.

Mutability in Python lists means that you can modify the list object after it has
been created. This includes:

● Adding elements: Using methods like .append(), .insert(), or


the + operator (which creates a new list).
● Removing elements: Using methods like .remove(), .pop(), or the
del keyword.
● Modifying elements: Assigning a new value to an element at a specific
index.

This ability to change the contents of a list in-place makes them a dynamic and
flexible data structure.

44. Describe how tuple assignment can be used as a return value.


Python functions can return multiple values by returning a tuple. The
values are implicitly packed into a tuple when separated by commas in
the return statement. You can then use tuple assignment to unpack
these returned values into separate variables when calling the function.
def get_coordinates():
x = 10
y = 20
return x, y # Returns a tuple (10, 20)

point_x, point_y = get_coordinates()


print(f"x: {point_x}, y: {point_y}") # Output: x: 10, y: 20

45. Write a Python program to append an element to a list using a list


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

46. Create a dictionary and demonstrate how to access its values.


student = {
"name": "Alice",
"age": 20,
"major": "Computer Science"
}

# Accessing values using keys


print(student["name"]) # Output: Alice
print(student["age"]) # Output: 20
print(student["major"]) # Output: Computer Science

# Using the .get() method (safer, returns None if key doesn't exist)
print(student.get("city")) # Output: None
print(student.get("age", "N/A")) # Output: 20 (returns default "N/A" if key
not found)

47. Compare the operations of sets and lists in Python.

Lists: Ordered collections of items. Allow duplicate elements. Elements


can be accessed by index. Support various operations for adding,
removing, and modifying elements.

Sets: Unordered collections of unique elements. Do not allow duplicates.


Do not support indexing (as they are unordered). Support mathematical
set operations like union (|), intersection (&), difference (-), and
symmetric difference (^).

Lists are used when the order of elements matters and duplicates are allowed,
while sets are used when you need to work with unique elements and perform
set-related operations efficiently
48. Analyze the difference between aliasing and cloning in lists.

Aliasing: When you assign one list to another variable (e.g., list2 =
list1), you are not creating a new list. Instead, both variables refer to
the same list object in memory. Changes made through one alias will
affect the other.
list1 = [1, 2, 3]
list2 = list1 # Aliasing
list2.append(4)
print(list1)
# Output: [1, 2, 3, 4] (list1 is also changed)

Cloning: Cloning creates a completely new list object with the same
elements as the original. Changes to the clone will not affect the original
list. You can clone a list using slicing ([:]) or the copy() method
list1 = [1, 2, 3]
list2 = list1[:] # Cloning using slicing
list3 = list1.copy() # Cloning using the copy() method
list2.append(4)
list3.remove(1)
print(list1) # Output: [1, 2, 3] (original list remains unchanged)
print(list2) # Output: [1, 2, 3, 4]
print(list3) # Output: [2, 3]
49. Assess the usefulness of NumPy over traditional Python lists for
numerical operations.

NumPy (Numerical Python) provides significant advantages over traditional


Python lists for numerical operations, especially when dealing with large
datasets and complex computations:

● Efficiency: NumPy arrays are implemented in C, making numerical


operations significantly faster than with Python lists, which involve more
overhead.
● Memory Efficiency: NumPy arrays are more memory-efficient for
storing large amounts of numerical data compared to Python lists.
● Broadcasting: NumPy allows for efficient element-wise operations on
arrays of different shapes (with certain compatibility rules), a feature not
directly available in standard Python lists.
● Specialized Functions: NumPy provides a vast library of optimized
mathematical functions (linear algebra, Fourier transforms, random
number generation, etc.) that are highly efficient and convenient for
numerical tasks.
● Multidimensional Arrays: NumPy excels at handling multidimensional
arrays (matrices, tensors), which are fundamental in many scientific and
engineering applications.

50. Design a program using Matplotlib to plot a simple line graph with
given data points.

import matplotlib.pyplot as plt


# Sample data points
x_points = [1, 2, 3, 4, 5]
y_points = [2, 4, 1, 5, 3]

# Create the plot


plt.plot(x_points, y_points)
# Add labels and title
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Simple Line Graph")

# Display the plot


plt.show()
Python

Explanation:

1. import matplotlib.pyplot as plt: This line imports the


pyplot module from the matplotlib library and gives it a common
alias plt for easier use.

2. x_points = [1, 2, 3, 4, 5] and y_points = [2, 4, 1,


5, 3]: These lines define two Python lists representing the data points
for the x and y axes of our graph.

3. plt.plot(x_points, y_points): This is the core function that


creates the line graph. It takes the x_points and y_points lists as
input and plots them. Matplotlib automatically connects the points with a
line.

4. plt.xlabel("X-axis"): This sets the label for the x-axis of the


graph.

5. plt.ylabel("Y-axis"): This sets the label for the y-axis of the


graph.

6. plt.title("Simple Line Graph"): This sets the title of the


graph.

7. plt.show(): This function displays the generated plot in a new


window.
To run this program:

1. Make sure you have the matplotlib library installed. If not, you can
install it using pip:
Bash

pip install matplotlib

2. Save the code as a Python file (e.g., line_graph.py).

3. Run the file from your terminal:

python line_graph.py

3 marks Questions:
UNIT-I: INTRODUCTION
1. Outline the history of Python programming language with key
milestones.

Python's journey began in the late 1980s with Guido van Rossum at CWI in the
Netherlands, conceived as a successor to ABC.

● Early 1990s: The first version, Python 0.9.0, was released in 1991.
● 1994: Python 1.0 was released, featuring functional programming tools
like map, filter, and reduce.
● 2000: Python 2.0 introduced list comprehensions and a garbage collection
system. This era saw Python's growing adoption.
● 2008: Python 3.0 (Python 3000 or Py3k) was released, introducing
significant changes aimed at modernizing the language and addressing
design flaws. This led to a period of dual Python 2 and 3 usage.
● 2020: Python 2 officially reached its end-of-life, marking the full
transition to Python 3, which continues to evolve with new features and
improvements in subsequent versions.
2. List and briefly describe three features of Python that make it
popular.
Readability: Python's syntax emphasizes clarity and conciseness, using
significant whitespace for code block definition. This makes it easier to
read, understand, and maintain code, often described as being almost
English-like.
Versatility: Python supports multiple programming paradigms, including
procedural, object-oriented, and functional programming. Its extensive
standard library and 1 vast ecosystem of third-party packages make it
suitable for a wide range of applications, from web development 2 and
data science to scripting and automation.
Large and Supportive Community: Python boasts a vibrant and active
community of developers. This translates to abundant online resources,
tutorials, libraries, and frameworks, making it easier for both beginners
and experienced programmers to find solutions and support.

3. Explain how quotations (single, double, and triple) are used in


Python with examples.

Python uses three types of quotations to define string literals:

Single quotes ('...'): Used to enclose single-line strings. Useful when the
string contains double quotes.

message = 'This is a string with "double quotes" inside.'

print(message)

Double quotes ("..."): Also used to enclose single-line strings. Useful


when the string contains single quotes.

greeting = "Hello, it's nice to meet you!"

print(greeting)
Triple quotes ('''...''' or """..."""): Used for multi-line strings or
docstrings (documentation strings used to explain code). They can span
multiple lines without the need for escape characters.

poem = """The woods are lovely, dark and deep,

But I have promises to keep,

And miles to go before I sleep,

And miles to go before I sleep."""

print(poem)

def my_function():

"""This is a docstring explaining what my_function does."""

pass

print(my_function. doc )

4. Discuss the role of lines and indentation in structuring Python code.

In Python, the structure of code is defined by two key elements:

Lines: Each logical statement in Python typically resides on a separate


line. This enhances readability by clearly separating individual
instructions. While multi-line statements are possible (using backslashes
or within parentheses, brackets, or braces), keeping logical units on single
lines is generally preferred for clarity.

Indentation: Unlike many other programming languages that use curly


braces to define code blocks (e.g., for loops, if statements, functions),
Python uses indentation (whitespace) to indicate these blocks. Consistent
indentation (typically 4 spaces per level) is not just a matter of style; it is
a fundamental part of Python's syntax. Incorrect indentation will lead to
IndentationError and prevent the code from running correctly.
This enforced indentation contributes significantly to Python's readability
by visually representing the code's logical structure.

5. Write a Python program that takes a user’s age as input and prints a
greeting message.
age_str = input("Please enter your age: ")
try:
age = int(age_str)
if age < 18:
print(f"Hello young one! You are {age} years old.")
else:
print(f"Greetings! You are {age} years old.")
except ValueError:
print("Invalid input. Please enter a valid integer for your age.)
6. Demonstrate the use of multi-line statements in Python with a simple
example.
Using multi-line statements improves the readability of your code,
especially when dealing with lengthy lines that would otherwise be
difficult to follow on a single line. Python's flexibility in handling these
structures makes the code cleaner and more maintainable.
# Using a backslash (\) to break a long statement into multiple lines
long_string = "This is a very long string that needs to be broken " \
"into multiple lines for better readability."
print(long_string)
# Implicitly breaking a statement within parentheses ()
result = (10 + 5 - 3 * 2
+ 8 / 4)
print(result)
# Implicitly breaking a statement within square brackets [] (for lists)
my_list = [
"apple",
"banana",
"cherry",
"date"
]
print(my_list)
# Implicitly breaking a statement within curly braces {} (for
dictionaries)
my_info = {
"name": "John Doe",
"age": 30,
"city": "New York"
}
print(my_info)

7. Differentiate between input and output operations in Python with


examples.
Input Operations: These operations allow a Python program to receive
data from the outside world, typically from the user. The primary function
for basic input is input(). It reads a line of text from the standard input
(usually the keyboard) and returns it as a string.
name = input("Enter your name: ")
print(f"Hello, {name}!")
age_str = input("Enter your age: ")
age = int(age_str) # Convert the input string to an integer
print(f"You are {age} years old.")
Output Operations: These operations allow a Python program to send
data to the outside world, typically to the console (standard output). The
primary function for basic output is print(). It displays the specified
values to the console.
message = "Welcome to Python!"
print(message)
number = 42
print("The answer is:", number)
x=5
y = 10
print(f"The sum of {x} and {y} is {x + y}") # Using f-strings for formatted
output

8. Compare the readability of code with proper indentation versus


without indentation.
Code with proper indentation is significantly more readable. The
indentation clearly visually delineates the blocks of code associated with
each conditional statement (if, else). This makes it easy to understand
the logical flow and the scope of each block. Without indentation, the
code becomes a wall of text, making it very difficult to determine which
statements belong to which conditional block, leading to confusion and
potential errors. Python's reliance on indentation enforces this readability,
making it a key characteristic of the language.
→code with indentation:
if x > 5:
if y < 10:
print("Condition met")
result = x + y
else:
print("Inner else")
else:
print("Outer else")
→code without indentation
if x > 5:
if y < 10:
print("Condition met")
result = x + y
else:
print("Inner else")
else:
print("Outer else")

9. Assess the significance of Python’s simplicity for beginner


programmers.

Python's simplicity is a major advantage for beginner programmers due to


several reasons:

● Gentle Learning Curve: Python's syntax is relatively easy to grasp


compared to more complex languages. Its English-like structure and
reduced verbosity mean beginners can focus on fundamental
programming concepts rather than getting bogged down in intricate
syntax rules.
● Faster Learning: The ease of reading and writing Python code allows
beginners to learn and implement basic programs more quickly. This
rapid feedback and sense of accomplishment can be highly motivating.
● Reduced Cognitive Load: The clear and concise syntax reduces the
cognitive load on learners, allowing them to concentrate on
problem-solving and algorithmic thinking rather than struggling with the
language's complexities.
● Focus on Concepts: Python's simplicity allows educators to focus on
teaching core programming principles (like variables, loops, and
functions) without the added burden of explaining complex
language-specific features early on.
● Large Beginner-Friendly Community: The popularity of Python means
there are abundant resources available for beginners, including tutorials,
online courses, and supportive communities, making it easier to find help
and learn effectively.

10. Design a Python program that accepts two strings as input and
concatenates them with a space.
string1 = input("Enter the first string: ")
string2 = input("Enter the second string: ")
concatenated_string = string1 + " " + string2
print("The concatenated string is:", concatenated_string)

UNIT-II: DATA, EXPRESSIONS, STATEMENTS


11. Define the five basic data types in Python with one example each.
Integer (int): Represents whole numbers (positive, negative, or zero)
without any decimal point.
age = 30
Float (float): Represents real numbers with a decimal point.
price = 99.99
String (str): Represents sequences of characters, enclosed in single or
double quotes.
name = "Alice"
Boolean (bool): Represents truth values, either True or False.
is_valid = True
NoneType (NoneType): Represents the absence of a value. There is
only one value of this type: None.
result = None
12. State the rules for operator precedence in Python expressions.

Python follows a specific order of operations, often remembered by the


acronym PEMDAS/BODMAS:

1. Parentheses (()): Expressions within parentheses are evaluated first.


2. Exponents (**): Exponentiation (raising to a power) is evaluated next.
3. Multiplication (*), Division (/), Floor Division (//), Modulo (%):
These operators have equal precedence and are evaluated from left to
right.
4. Addition (+), Subtraction (-): These operators have equal precedence
and are evaluated from left to right.

Operators with higher precedence are evaluated before operators with lower
precedence. Parentheses can be used to override 1 the default precedence.

13. Explain how tuple assignment simplifies swapping variable values in


Python.
Tuple assignment provides a concise and Pythonic way to swap the
values of two or more variables without the need for a temporary
variable. It works by simultaneously assigning the values on the
right-hand side (as a tuple) to the variables on the left-hand side (also
implicitly forming a tuple).
a=5
b = 10
print(f"Before swap: a = {a}, b = {b}")
a, b = b, a # Tuple assignment for swapping
print(f"After swap: a = {a}, b = {b}")
14. Describe the purpose of comments in Python with an example.

Comments in Python are explanatory notes added to the code to make it more
understandable for humans. They are ignored by the Python interpreter and do
not affect the program's execution. Comments are crucial for:

Single-line comments: Start with a hash symbol (#) and continue to the end of
the line.

# This line initializes the counter variable

count = 0

Multi-line comments (Docstrings): While not strictly comments, triple-quoted


strings ('''Docstring goes here''' or """Docstring goes
here""") are often used for multi-line explanations, especially for
documenting functions, classes, and modules. These are accessible at runtime
using the doc attribute.

code:

def calculate_area(length, width):

"""

This function calculates the area of a rectangle.

Args:

length: The length of the rectangle.

width: The width of the rectangle.

Returns:

The area of the rectangle.

"""

return length * width


15. Write a Python program to exchange the values of two variables
without using a temporary variable.
a=5
b = 10
print(f"Before swap: a = {a}, b = {b}")

# Method 1: Using arithmetic operations (can have limitations with


very large numbers)
a=a+b
b=a-b
a=a-b
print(f"After swap (arithmetic): a = {a}, b = {b}")

# Method 2: Using bitwise XOR operation (works for integers)


x=5
y = 10
print(f"Before swap: x = {x}, y = {y}")
x=x^y
y=x^y
x=x^y
print(f"After swap (XOR): x = {x}, y = {y}")

# Method 3: Using tuple assignment (the most Pythonic way)


p=5
q = 10
print(f"Before swap: p = {p}, q = {q}")
p, q = q, p
print(f"After swap (tuple assignment): p = {p}, q = {q}")
16. Create a program to compute the Euclidean distance between two points
given their coordinates.
import math
def euclidean_distance(x1, y1, x2, y2):
"""Computes the Euclidean distance between two points in a 2D
plane."""
distance = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
return distance

# Get coordinates of the two points from the user


x1 = float(input("Enter x-coordinate of the first point: "))
y1 = float(input("Enter y-coordinate of the first point: "))
x2 = float(input("Enter x-coordinate of the second point: "))
y2 = float(input("Enter y-coordinate of the second point: "))

# Calculate the distance


distance = euclidean_distance(x1, y1, x2, y2)

# Print the result


print(f"The Euclidean distance between ({x1}, {y1}) and ({x2}, {y2}) is:
{distance}")
17. Compare the use of Python interpreter in interactive mode versus
script mode.

18. Analyse the impact of incorrect operator precedence in a


mathematical expression.

Incorrect operator precedence in a mathematical expression can lead to


unintended order of operations, resulting in a completely different and incorrect
result. For example:

Consider the expression 3 + 4 * 2.

● Correct Precedence (Multiplication before Addition): 3 + (4 * 2)


= 3 + 8 = 11
● Incorrect Precedence (Addition before Multiplication): (3 + 4) *
2 = 7 * 2 = 14

As seen, the difference in precedence leads to two distinct outcomes. In


complex expressions with multiple operators, ignoring or misunderstanding the
precedence rules can introduce significant errors in calculations, potentially
leading to flawed logic and incorrect program behavior. Using parentheses
explicitly can override the default precedence and ensure the expression is
evaluated as intended, improving code correctness and readability.

19. Justify the use of type conversion in handling mixed data types in
expressions.
type conversion (or type casting) is essential when you need to perform
operations involving different data types that Python doesn't
automatically handle. Without explicit conversion, you might encounter
TypeError exceptions because certain operations are not defined
between incompatible types
For example, you cannot directly add a string and an integer:
num_str = "10"
num_int = 5
# result = num_str + num_int # This will raise a TypeError
To perform the addition, you need to convert the string to an integer (or
the integer to a string):
result_int = int(num_str) + num_int # Convert string to integer
print(result_int) # Output: 15
result_str = num_str + str(num_int) # Convert integer to string
print(result_str) # Output: 105
20. Design a program to circulate the values of four variables in a
clockwise manner.
def circulate_clockwise(a, b, c, d):
"""Circulates the values of four variables clockwise (a->b, b->c, c->d,
d->a)."""
temp = d
d=c
c=b
b=a
a = temp
return a, b, c, d

# Initialize four variables


var1 = 10
var2 = 20
var3 = 30
var4 = 40
print(f"Before circulation: var1 = {var1}, var2 = {var2}, var3 = {var3},
var4 = {var4}")
# Circulate the values
var1, var2, var3, var4 = circulate_clockwise(var1, var2, var3, var4)
print(f"After circulation: var1 = {var1}, var2 = {var2}, var3 = {var3},
var4 = {var4}")
# Another way using list and tuple assignment
def circulate_clockwise_list(vars_list):
"""Circulates the values in a list clockwise."""
if len(vars_list) != 4:
return "List must have four elements"
return [vars_list[3], vars_list[0], vars_list[1], vars_list[2]]
my_vars = [100, 200, 300, 400]
print(f"Before circulation (list): {my_vars}")
my_vars = circulate_clockwise_list(my_vars)
print(f"After circulation (list): {my_vars}")

UNIT-III: CONTROL FLOW STATEMENTS AND STRINGS


21. Define the "continue" and "break" statements with their purposes in
loops.
Answer:
continue Statement:
The continue statement is used inside loops to skip the rest of the current
iteration and move to the next one. It's helpful when you want to ignore
certain conditions but still continue looping.
Example:
Code:
for i in range(1, 6):
if i == 3:
continue
print(i)
Output: 1, 2, 4, 5 (skips 3)
break Statement:
The break statement is used to exit a loop entirely, stopping further
iterations. It's useful when you want to stop looping based on a condition.
Example:
Code:
for i in range(1, 6):
if i == 3:
break
print(i)

Output: 1, 2 (stops at 3)
22. List and briefly explain three in-built string methods in Python.
Answer:
1. lower():
The lower() method converts all characters in a string to lowercase. It’s useful when you
want to make a string case-insensitive.
Example:
text = "Hello"
print(text.lower())
Output: "hello"
2. upper():
The upper() method converts all characters in a string to uppercase. It's commonly used
when you need to make text uniform in all caps.
Example:
text = "hello"
print(text.upper())
Output: "HELLO"
3. strip():
The strip() method removes any leading and trailing whitespace (spaces, tabs, etc.) from a
string. It's helpful when you want to clean up extra spaces from the start or end of a string.
Example:
text = " Hello World "
print(text.strip())
Output: "Hello World"
23. Explain the role of the "else" clause when used with loops in Python.
Answer:
Role of the else Clause with Loops:
In Python, the else clause can be used in both for and while loops. It runs only if the loop
completes normally, meaning without being interrupted by a break statement. If the loop
is stopped by a break, the else block is skipped.
Key Points:
• The else block is executed when the loop finishes all its iterations without encountering
a break.
• It is often used to specify what to do when the loop successfully completes all tasks
(e.g., a search that didn’t find a match).
Example:
for i in range(1, 4):
print(i)
else:
print("Loop completed without interruption")
Output:
1
2
3
Loop completed without interruption
If you use a break, the else block will not run:
for i in range(1, 4):
if i == 2:
break
print(i)
else:
print("Loop completed without interruption")
Output:
1
(No output from the else because the loop was interrupted by break)
24. Discuss how string formatting operations enhance output readability.
Answer :
String Formatting and Output Readability:
String formatting in Python makes it easier to create and control the appearance of output.
It helps make the text more readable, organized, and clear by inserting variables into strings
and aligning them as needed.
Key Benefits:
1. Inserting Variables Cleanly: String formatting allows you to insert variables directly
into a string, making your code more concise and readable.
Example:
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
Output: My name is Alice and I am 25 years old.
This avoids awkward concatenation and makes the output more natural.
2. Controlling Alignment and Spacing: Formatting helps align text, numbers, or tables
neatly, which makes the output easier to read, especially for reports or tables.
Example:
print(f"{'Name':<10} {'Age':<5}")
print(f"{'Alice':<10} {25:<5}")
print(f"{'Bob':<10} {30:<5}")
Output:
Name Age
Alice 25
Bob 30
3. Formatting Numbers: String formatting allows you to control the precision or the
appearance of numbers, which is helpful for showing things like currency or
percentages.
Example:
price = 49.995
print(f"Price: ${price:.2f}")
Output: Price: $50.00
25. Write a Python program using nested if statements to classify a number as
even/odd and positive/negative.
Answer:
# Get input from the user
num = int(input("Enter a number: "))

# Check if the number is positive, negative, or zero


if num >= 0:
if num == 0:
print("The number is zero, which is neither positive nor negative, and even.")
else:
print("The number is positive.")
if num % 2 == 0:
print("It is also even.")
else:
print("It is also odd.")
else:
print("The number is negative.")
if num % 2 == 0:
print("It is also even.")
else:
print("It is also odd.")
Enter a number: 4
The number is positive.
It is also even.
26. Demonstrate a for loop to count vowels in a given string.
Answer:
Counting Vowels Using a for Loop:
We can use a for loop in Python to go through each character in a string and count how
many of them are vowels (a, e, i, o, u).
Here’s a simple program:
text = "Hello World"
vowels = "aeiouAEIOU"
count = 0
for char in text:
if char in vowels:
count += 1

print("Number of vowels:", count)


Output:
Number of vowels: 3
27. Compare the functionality of "while" and "for" loops with examples.
Answer:
for Loop:
• Used when you know how many times you want to repeat something.
• It loops over a sequence like a list, string, or range.
Example:
for i in range(5):
print(i)
Output:
0
1
2
3
4
This loop runs 5 times, automatically going from 0 to 4.

while Loop:
• Used when you don’t know in advance how many times to loop.
• It keeps running as long as a condition is true.
Example:
i=0
while i < 5:
print(i)
i += 1
Output:
0
1
2
3
4
28.Differentiate between string slicing and string methods in manipulating
strings.
Answer:
1. String Slicing:
• What it is: A way to extract part of a string using index positions.
• How it works: Use square brackets [] with a start and end index.
Example:
text = "Hello World"
print(text[0:5])
Output:
Hello
2 . String Methods:
• What they are: Built-in functions used to modify or analyze strings.
Examples:
text = " Hello "
print(text.strip()) # Removes extra spaces
print(text.upper()) # Converts to uppercase
Output:
Hello
HELLO
29. Evaluate the efficiency of using the "pass" statement in program
development.
Answer:
Evaluating the Efficiency of the pass Statement:
The pass statement in Python is a placeholder. It does nothing
when executed, but it lets the code run without errors when a block
is required syntactically.
Why it's useful:
1. Helps During Development:
When you're still planning or writing your code, you might
leave some parts incomplete. Instead of deleting them or writing
dummy code, you can use pass.
Example:
def future_function():
pass # I'll write this later
2. Prevents Syntax Errors:
Python requires at least one statement inside loops, functions,
classes, or if blocks. pass fills that need when you have nothing
to put yet.
3. Keeps Code Structure Clear:
It allows you to outline your program without breaking it,
which is helpful when working on big projects step-by-step.
30. Design a program to check if a string is a palindrome using a while loop.
Answer:
strr = str(input("Enter a string: "))

org_str = strr.lower()

rev_str = org_str[::-1]

if org_str == rev_str:
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")

UNIT-IV: FUNCTIONS AND FILES


31. Define function composition and recursion in Python.
Answer:
Function Composition:
• What it is: Function composition means combining two or more functions so
that the output of one function becomes the input of another.
• It helps break a complex task into smaller, reusable parts.
Example:
def add_two(x):
return x + 2

def multiply_by_three(x):
return x * 3
# Compose the functions
result = multiply_by_three(add_two(4))
print(result)
Output:
18 # (4 + 2) * 3
Recursion:
• What it is: Recursion is when a function calls itself to solve a smaller part of the
problem.
• It's useful for tasks that can be broken down into smaller, similar sub-tasks — like
calculating factorials or traversing trees.
Example:
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)

print(factorial(5))
Output:
120
32. List three key operations involved in file handling in Python.
Answer:
Three Key File Handling Operations in Python:
1. Opening a File
Before you can read or write a file, you need to open it using the open() function.
Example:
file = open("example.txt", "r") # "r" means read mode
2. Reading or Writing
Once the file is open, you can either read its content or write new content.
Read Example:
content = file.read()
Write Example:
file = open("example.txt", "w")
file.write("Hello, World!")
3. Closing the File
Always close the file after you're done to free up system resources.
Example:
file.close()
33. Explain the difference between local and global variables with an
example.
Answer:
Local vs Global Variables in Python
Global Variable:
• A variable declared outside any function.
• It can be used anywhere in the program, including inside
functions (unless overridden).
Local Variable:
• A variable declared inside a function.
• It can only be used within that function, not outside.

Example:
x = 10 # Global variable

def show():
y = 5 # Local variable
print("Inside function: x =", x) # Can access global
print("Inside function: y =", y)

show()
print("Outside function: x =", x)
# print(y) # This would give an error because y is local
Output:
Inside function: x = 10
Inside function: y = 5
Outside function: x = 10
34. Discuss how format operators improve file output in Python.

Answer:

Absolutely! Here’s a human-friendly, 3-mark answer on how format operators


improve file output in Python:

How Format Operators Improve File Output in Python


Answer:
Format operators like %, .format(), or f-strings (f"") help you neatly insert values
into strings. They make file output look clean, structured, and professional.

Why they’re useful in file output:


1. Organized Data:
Format operators help you create well-aligned and readable text when writing to
files—great for reports, logs, or tables.
2. Custom Formatting:
You can control number precision, padding, alignment, and more.
3. Dynamic Content:
Easily insert variables into file text without messy string concatenation.

Example:
name = "Alice"
score = 95.678
Code:
with open("report.txt", "w") as f:
f.write(f"Student: {name}\n")
f.write(f"Score: {score:.2f}\n")
Output:
Content in report.txt:
Student: Alice
Score: 95.68
35. Write a Python function that takes two parameters and returns their
product.
Answer:
def product(a,b):
return a * b

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


second number: ")))
print(f"The product of the two numbers is: {A}")

36. Create a program to read a text file and print its contents line by line.
Answer:
# Open the file in read mode
with open("sample.txt", "r") as file:
# Loop through each line in the file
for line in file:
print(line.strip()) # .strip() removes extra newline characters
37. Compare the use of return values versus print statements in functions.
Answer:
Return Values vs Print Statements in Functions
Return Values:
• return sends a value back to the caller of the function.
• The value can be stored, used in calculations, or passed to other functions.
• It makes the function more reusable and flexible.
Example:
def add(a, b):
return a + b

result = add(3, 4)
print(result) # Output: 7
Best for logic, calculations, and when you need to use the result later.
Print Statements:
• print() simply displays output on the screen.
• It’s used for debugging or showing results to the user.
• Doesn’t give back a value to work with in the rest of the program.
Example:
def add(a, b):
print(a + b)

add(3, 4) # Output: 7
You can’t use the result of print() for further processing.
38. Analyze the advantages of recursion over iteration in solving problems
like factorial.
Answer:
Advantage of Recursion
1. Simpler & Cleaner Code
• Recursion allows you to express a problem (like factorial) in a natural
and elegant way.
• The code is often shorter and easier to understand logically.
Example (Factorial using Recursion):
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
2. Matches the Problem’s Structure
• Some problems, like factorial, tree traversal, or Fibonacci, are
naturally recursive in definition.
• Recursion directly mirrors the way the problem is described
mathematically.
3. Useful for Complex Structures
• Recursion is very effective in handling problems with nested or
branching structures like trees and graphs.
Disadvantage:
• Recursion uses more memory (due to the call stack).
• It can be less efficient than iteration for simple tasks unless carefully
optimized.
39. Assess the importance of proper file path handling in file operations.
Answer:
Importance of Proper File Handling
1. Finding the Right File
If the path is incorrect, Python won’t be able to locate the file — causing errors like
FileNotFoundError. Using the right path ensures your program works smoothly
across folders.
2. Cross-Platform Compatibility
Different operating systems use different path styles (e.g., Windows uses \,
Linux/macOS use /). Using tools like os.path or Pathlib helps your code work on
any system.
Example:
import os
path = os.path.join("folder", "file.txt")
3. Avoiding Accidental Data Loss
Using a wrong or absolute path (like C:\) might overwrite important files or save
them in the wrong place. Correct paths keep files organized and safe.
40. Design a recursive function to compute the nth Fibonacci number.
Answer:
def fact(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
Fnm1 = fact(n-1)
Fnm2 = fact(n-2)
Fib = Fnm1 + Fnm2
return Fib

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


print(Num)

UNIT-V: LIST, SET, TUPLES, DICTIONARIES


41. Define mutability and immutability with respect to lists and tuples.
Answer:
Mutability refers to the ability to change or modify an object after it has been
created.
o Lists in Python are mutable, which means you can modify their elements
after creation. You can add, remove, or change the values of list elements.
Example:
my_list = [1, 2, 3]
my_list[0] = 100 # Modifying the first element
print(my_list) # Output: [100, 2, 3]
• Immutability refers to the inability to change an object once it has been created.
o Tuples in Python are immutable, meaning that once a tuple is created, its
contents cannot be altered. You cannot add, remove, or modify the
elements of a tuple.
Example:
my_tuple = (1, 2, 3)
# Attempting to modify an element will raise an error:
# my_tuple[0] = 100 # This will cause a TypeError
42. List three operations that can be performed on a Python dictionary.
Answer:
Properties:
1. Adding or updating values: You can add new key-value pairs or modify existing
values using the key.
o Example: my_dict['key'] = value
2. Accessing values: Use keys to access their corresponding values.
o Example: value = my_dict['key']
3. Deleting items: You can remove key-value pairs using del or pop().
o Example: del my_dict['key']

43. Explain the concept of aliasing in lists with an example.


Answer:
Aliasing occurs when two or more variables point to the same list object in memory.
Modifying the list through one variable will reflect in the other, as both refer to the
same list.
Example:
python
CopyEdit
list1 = [1, 2, 3]
list2 = list1 # Aliasing, both point to the same list
list2[0] = 100 # Modifying list2 also affects list1
print(list1) # Output: [100, 2, 3]

44. Discuss how tuples can be used as return values in functions.


Answer:
Tuples can be used to return multiple values from a function in an organized way.
Since tuples are immutable, they can ensure that the returned values are not
accidentally modified after the function call.
Example:
python
CopyEdit
def get_student_info():
name = "Alice"
marks = 85
return (name, marks)

info = get_student_info()
print(info) # Output: ('Alice', 85)
45. Write a Python program to sort a list of numbers using a list method.
Answer:
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
numbers.sort()
print(numbers) # Output: [1, 1, 2, 3, 4, 5, 6, 9]
46. Create a dictionary to store student names and marks, then print the
highest mark.
Answer:
students = {'Alice': 85, 'Bob': 90, 'Charlie': 92}
highest_mark = max(students, key=students.get)
print(f"The highest mark is {students[highest_mark]} by
{highest_mark}")
47. Compare the use of sets and lists for storing unique elements.
Answer:
• Sets are unordered collections that automatically ensure uniqueness of
elements. They are ideal when you need to store unique elements and perform set
operations like union, intersection, or difference.
• Lists allow duplicate values and maintain order. They are useful when the order
of elements matters, and duplicates are acceptable.

48. Analyze the difference between cloning and aliasing in list operations.
Answer:

49.Evaluate the role of NumPy in simplifying array-based computations


compared to lists.
Answer:
NumPy provides a powerful array object (ndarray) that is optimized for
numerical computations. Unlike Python lists, NumPy arrays support element-
wise operations and are much faster and more memory-efficient for large-scale
computations. NumPy also offers a wide range of mathematical and statistical
functions.
Example:
import numpy as np
arr = np.array([1, 2, 3])
print(arr * 2) # Output: [2 4 6]

50.Design a program using Matplotlib to plot a bar chart of five students’


marks.
Answer:
import matplotlib.pyplot as plt

# Student names and marks


students = ['Alice', 'Bob', 'Charlie', 'David', 'Eva']
marks = [85, 90, 92, 78, 88]

plt.bar(students, marks)
plt.xlabel('Students')
plt.ylabel('Marks')
plt.title('Bar Chart of Student Marks')
plt.show()

5 marks Questions:
UNIT-I: INTRODUCTION
1. Describe the history of Python, highlighting its origin, major versions,
and contributors.
Answer:
History of Python – 5 Marks
Python was created by Guido van Rossum in the late 1980s at the Centrum Wiskunde
& Informatica (CWI) in the Netherlands. He started working on it as a hobby
project during Christmas in 1989 and released the first version, Python 0.9.0, in
1991. His goal was to make a language that combined readability, simplicity, and
power, inspired by the ABC language and C.
The name “Python” was actually inspired by Monty Python’s Flying Circus, a British
comedy show — not the snake!
Major Versions:
• Python 1.0 (1994): Introduced basic features like functions, modules, and
exception handling.
• Python 2.0 (2000): Added list comprehensions, garbage collection, and Unicode
support. It was popular but had some design issues.
• Python 3.0 (2008): A complete redesign to fix long-term flaws — but not
backward compatible. Introduced better syntax, print as a function, and better
Unicode handling.
Contributors & Growth:
Guido remained Python’s “Benevolent Dictator For Life (BDFL)” until he stepped
down in 2018. Since then, Python’s development is led by a core development
team and the Python Software Foundation (PSF). Thanks to its clean syntax and
versatility, Python has become one of the most popular programming languages
in the world, used in web development, AI, data science, automation, and more.
2. Enumerate and explain five key features of Python that distinguish it
from other programming languages.
Answer:
Five Key Features of Python – 5 Marks
1. Simple and Readable Syntax
Python code looks almost like plain English, making it easy to write
and understand. This simplicity helps beginners learn programming
faster and makes collaboration easier.
2. Interpreted Language
Python doesn't need to be compiled. You can run code line by line
using an interpreter, which is great for testing, debugging, and rapid
development.
3. Dynamically Typed
You don’t need to declare data types for variables. Python figures it
out on its own at runtime, which speeds up coding and reduces
boilerplate.
4. Extensive Standard Library
Python comes with a “batteries-included” philosophy. It includes
built-in modules for things like file handling, regular expressions,
math, and even web services—saving time and effort.
5. Large Community and Versatility
Python has a massive global community and tons of third-party
libraries. Whether you’re doing web development (like with
Django), data science (with Pandas/Numpy), or automation, there’s
likely already a solution in Python.

3. Explain the significance of quotations in Python and illustrate their use


with examples for single, double, and triple quotes.
Answer:
In Python, quotations are used to define string literals. A string is a
sequence of characters, and Python allows three types of quotes to
enclose strings:
1. Single Quotes ' '
Used for simple strings.
python
CopyEdit
name = 'Alice'
print(name) # Output: Alice
2. Double Quotes " "
Functionally the same as single quotes but useful when the string contains
an apostrophe.
python
CopyEdit
sentence = "It's a sunny day"
print(sentence) # Output: It's a sunny day
3. Triple Quotes ''' ''' or """ """
Used for multi-line strings or docstrings (comments for
functions/classes).
python
CopyEdit
message = '''Hello,
This is a multi-line string.'''
print(message)

def greet():
"""This function prints a greeting message."""
print("Hi!")
Why It Matters:
• Flexibility: You can choose quotes based on the content.
• Avoid Escaping: Using different quotes avoids backslashes (e.g., using
double quotes for a string with a single quote).
• Docstrings: Triple quotes are essential for documenting functions and
classes.

4. Discuss how lines and indentation affect the execution of a Python


program, with an example.
Answer:
In Python, indentation is crucial because it defines the structure of
the code. Unlike many other languages that use braces {} or
keywords to mark code blocks, Python uses indentation (spaces or
tabs) to group statements.
Why It Matters:
• Proper indentation tells Python which lines of code belong to a
particular block, such as inside a loop, function, or conditional.
• Incorrect indentation will cause errors or lead to unexpected
behavior.
Example:
# Correct indentation
if True:
print("This is inside the if block")
print("Still inside the block")
print("This is outside the block")

# Incorrect indentation (will cause an error)


if True:
print("This will cause an IndentationError")
Key Points:
• A typical indent is 4 spaces.
• Mixing tabs and spaces can lead to errors.
• Every line in a block must be indented the same.
5. Write a Python program that accepts a user’s name and age as input and
prints a formatted welcome message.
Answer:
Algorithm:
1. Start
2. Ask the user to enter their name
3. Ask the user to enter their age
4. Store the inputs
5. Print a formatted welcome message using the name and age
6. End
Python Program:
# Step 1: Accept user input
name = input("Enter your name: ")
age = input("Enter your age: ")

# Step 2: Display a formatted welcome message


print(f"Welcome, {name}! You are {age} years old.")

Sample Output:
yaml
CopyEdit
Enter your name: Sara
Enter your age: 21
Welcome, Sara! You are 21 years old.

6. Demonstrate the use of multi-line statements to calculate and display the


area and perimeter of a rectangle.
Answer:
In Python, you can use a backslash (\) to break long statements into
multiple lines for better readability. You can also use parentheses for
implicit line continuation.

Python Program (using multi-line statements):


# Taking input
length = float(input("Enter the length of the rectangle: "))
breadth = float(input("Enter the breadth of the rectangle: "))

# Calculating area using multi-line statement


area = length * \
breadth
# Calculating perimeter using multi-line statement
perimeter = 2 * (
length + breadth
)

# Displaying results
print("Area of rectangle:", area)
print("Perimeter of rectangle:", perimeter)

Sample Output:
Enter the length of the rectangle: 5
Enter the breadth of the rectangle: 3
Area of rectangle: 15.0
Perimeter of rectangle: 16.0

7. Compare input and output operations in Python, providing examples of


each and their practical uses.
Answer:
1. Input Operation
• Function Used: input()
• Purpose: Takes data from the user as a string.
• Syntax:
• name = input("Enter your name: ")
• Practical Use: Useful for collecting user information in programs like
forms, quizzes, or calculators.
2. Output Operation
• Function Used: print()
• Purpose: Displays data or messages on the screen.
• Syntax:
• print("Hello,", name)
• Practical Use: Used to show results, errors, or confirmation messages.

Combined Example:
age = input("Enter your age: ")
print("You are", age, "years old.")
8. Differentiate between Python’s script mode and interactive mode,
analyzing their advantages in coding.
Answer:

9. Assess the impact of Python’s simplicity and readability on its adoption


in educational settings.
Answer:
Impact of Python’s Simplicity and Readability in Education – 5
Marks
Python’s simple and readable syntax has had a major impact on its
widespread adoption in educational settings. Its code resembles plain
English, which makes it much easier for beginners to learn
programming concepts without being overwhelmed by complex
syntax.
Key Points:
1. Beginner-Friendly Syntax:
Python removes unnecessary complexity (like semicolons and curly
braces), helping students focus on logic and problem-solving rather
than formatting rules.
2. Quick Learning Curve:
Learners can start writing useful programs quickly, which keeps them
motivated and engaged.
3. Strong Community and Resources:
Tons of tutorials, books, and forums are available for students, making
self-learning easier.
4. Used in Real-World Applications:
Python is not just for learning—it’s used in web development, data
science, and AI. This gives students practical skills from the start.
5. Supported by Education Platforms:
Many online platforms and schools (like Code.org, Coursera, and
universities) teach Python as a first programming language.

10. Design a Python program that takes three inputs (name, city, and hobby)
and generates a personalized multi-line story.
Answer:

Algorithm:
1. Start
2. Prompt the user to enter their name.
3. Prompt the user to enter the city they live in.
4. Prompt the user to enter their favorite hobby.
5. Store the inputs (name, city, hobby).
6. Use the inputs to create a multi-line string (story) with placeholders for the
name, city, and hobby.
7. Print the personalized story.
8. End
Code:
# Taking input from the user
name = input("Enter your name: ")
city = input("Enter the city you live in: ")
hobby = input("Enter your favorite hobby: ")

# Generating a multi-line personalized story


story = f"""
Once upon a time in the beautiful city of {city},
there lived a cheerful person named {name}.
Every day, {name} loved spending time doing {hobby}.
It brought joy and excitement to their life,
and they became known all over {city} for their passion.

The end.
"""
# Displaying the story
print(story)
Output:
Enter your name: isha
Enter the city you live in: Paris
Enter your favorite hobby: painting

Once upon a time in the beautiful city of Paris,


there lived a cheerful person named isha.
Every day, Isha loved spending time doing painting.
It brought joy and excitement to their life,
and they became known all over Paris for their passion.

The end.

UNIT-II: DATA, EXPRESSIONS, STATEMENTS

11. List and describe the five basic data types in Python, providing an
example for each.
Python offers a variety of built-in data types, which are crucial for storing and
manipulating data. Here's a detailed breakdown:
1. Integer (int)
o Represents whole numbers without a decimal point.
o Example: age = 25
o Use case: Counting, indexing, etc.
2. Float (float)
o Represents real numbers or numbers with a decimal point.
o Example: height = 5.9
o Use case: Measurements, scientific calculations, etc.
3. String (str)
o Represents sequences of characters enclosed in quotes.
o Example: name = "Alice"
o Use case: Storing text, messages, and labels.
4. Boolean (bool)
o Represents truth values: True or False.
o Example: is_adult = True
o Use case: Conditional expressions, flags.
5. List (list)
o An ordered, mutable collection of items, which can be of mixed types.
o Example: fruits = ["apple", "banana", "cherry"]
o Use case: Storing collections of data, like items, names, etc.

12. Explain the precedence of operators in Python with a table and examples
of arithmetic operations.
Python follows operator precedence rules to determine the order in which
operations are evaluated. Here's a breakdown:
Operator Description Example
() Parentheses (3 + 2) * 4
** Exponentiation 2 ** 3
Multiplication, Division, Modulo, Floor 4 * 5, 10 /
*, /, %, //
Division 2
+, - Addition, Subtraction 3 + 2, 5 - 2
Example:
result = 3 + 5 * 2 / 4 # According to precedence, 5 * 2 is done first
print(result) # Output: 5.0
13. Discuss how tuple assignment works in Python and illustrate its use in
swapping values with an example.
Tuple assignment allows multiple variables to be assigned values
simultaneously, and it's commonly used in swapping variables.
Example (Swapping values):
x=5
y = 10
x, y = y, x # Swap using tuple assignment
print(x, y) # Output: 10 5
How it works:
• On the right side of the assignment (y, x), Python creates a tuple of the values of
y and x.
• On the left side (x, y), Python unpacks the tuple, assigning the first element to x
and the second element to y.

14. Explain the role of comments and expressions in Python, highlighting


their importance in code clarity.
• Comments: Comments are used to explain what the code does and are not
executed by Python. They begin with # and are vital for code readability and
maintaining the code.
o Example: # This line prints a greeting
• Expressions: An expression is any combination of values, variables, and
operators that evaluates to a result. It can be arithmetic or logical.
o Example: 3 + 5 is an expression that evaluates to 8.
Importance:
• Comments help developers understand code, especially when it's being worked
on by others or revisited after a long time.
• Expressions perform operations or calculations and are the foundation of
programming logic.

15. Write a Python program to exchange the values of two variables using
tuple assignment and verify the result.
Algorithm:
1. Start
2. Assign initial values to two variables (e.g., x and y).
3. Swap their values using tuple assignment.
4. Print the values of x and y to verify the swap.
5. End.
Python Program:
# Initial values
x=3
y=7

# Swapping using tuple assignment


x, y = y, x

# Verifying the result


print("x =", x) # Output: x = 7
print("y =", y) # Output: y = 3
16. Create a program to calculate the distance between two points using
user-input coordinates and the distance formula.
Algorithm:
1. Start
2. Accept two pairs of coordinates from the user (x1, y1 and x2, y2).
3. Apply the distance formula:
d = sqrt((x2 - x1)^2 + (y2 - y1)^2)
4. Display the calculated distance.
5. End.
Python Program:
import math

# Taking user input


x1, y1 = map(float, input("Enter the coordinates of the first point (x1, y1):
").split())
x2, y2 = map(float, input("Enter the coordinates of the second point (x2, y2):
").split())

# Calculating distance
distance = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)

# Displaying the result


print(f"The distance between the points is: {distance}")

17. Compare the functionality of Python’s interactive mode versus script


mode with examples of their use cases.
• Interactive Mode: You type code directly into the Python shell or terminal, and
it runs immediately.
o Example Use Case: Quick tests or experimenting with code.
o Example:
o >>> print("Hello!")
o Hello!
• Script Mode: Write your code in a .py file and execute the entire file. It’s used
for larger, more complex programs.
o Example Use Case: Building complete applications or performing batch
processing.
o Example: Save the script as hello.py and run it via terminal:
o python hello.py
Interactive mode is perfect for quick experiments, while script mode is ideal for
full-fledged programs.

18. Analyze the effect of operator precedence on the evaluation of a complex


expression like 3 + 5 * 2 / 4.
Operator precedence dictates the order of operations in an expression. In this
case, multiplication and division have higher precedence than addition.
Example:
result = 3 + 5 * 2 / 4
# First, 5 * 2 is evaluated to 10
# Then, 10 / 4 is evaluated to 2.5
# Finally, 3 + 2.5 gives 5.5
print(result) # Output: 5.5

19. Evaluate the necessity of type conversion in Python when working with
mixed data types in expressions.
In Python, type conversion (or casting) is required when mixing different data
types in expressions, such as trying to combine strings with numbers.
Example:
age = 25
message = "Your age is " + str(age) # Converting int to string
print(message) # Output: Your age is 25

20. Design a Python program to circulate the values of five variables in a


circular pattern and display each step.
Algorithm:
1. Start
2. Assign values to five variables.
3. Use tuple assignment to shift the values in a circular manner.
4. Print the result after each step to show the circulation.
5. End.
Python Program:
# Initial values
a, b, c, d, e = 1, 2, 3, 4, 5

# Displaying the initial values


print(a, b, c, d, e)

# Circulating values
a, b, c, d, e = e, a, b, c, d

# Displaying after circulation


print(a, b, c, d, e) # Output: 5 1 2 3 4

UNIT-III: CONTROL FLOW STATEMENTS AND STRINGS

21. Define and explain the purpose of "break," "continue," and "pass"
statements in Python loops with examples.
• Break: The break statement is used to exit a loop prematurely when a certain
condition is met.
o Example:
o for i in range(5):
o if i == 3:
o break
o print(i) # Output: 0, 1, 2
o Purpose: Exits the loop when a specific condition is encountered, skipping
the remaining iterations.
• Continue: The continue statement skips the rest of the current loop iteration and
proceeds to the next iteration.
o Example:
o for i in range(5):
o if i == 3:
o continue
o print(i) # Output: 0, 1, 2, 4
o Purpose: Skips the current iteration of the loop, allowing the loop to
continue from the next iteration.
• Pass: The pass statement is a placeholder that does nothing but is used
syntactically to maintain the structure of the program.
o Example:
o for i in range(5):
o if i == 3:
o pass
o print(i) # Output: 0, 1, 2, 3, 4
o Purpose: Used where a statement is syntactically required but no action is
needed.

22. List and describe five in-built string methods in Python, including their
syntax and use.
1. str.lower(): Converts all characters in a string to lowercase.
o Syntax: string.lower()
o Example:
o text = "HELLO"
o print(text.lower()) # Output: hello
2. str.upper(): Converts all characters in a string to uppercase.
o Syntax: string.upper()
o Example:
o text = "hello"
o print(text.upper()) # Output: HELLO
3. str.replace(): Replaces a specified substring with another substring.
o Syntax: string.replace(old, new)
o Example:
o text = "Hello world"
o print(text.replace("world", "Python")) # Output: Hello Python
4. str.split(): Splits a string into a list based on a delimiter (space by default).
o Syntax: string.split(delimiter)
o Example:
o text = "Python is awesome"
o print(text.split()) # Output: ['Python', 'is', 'awesome']
5. str.strip(): Removes leading and trailing whitespaces from a string.
o Syntax: string.strip()
o Example:
o text = " Hello "
o print(text.strip()) # Output: Hello

23. Discuss the significance of the "else" clause with loops, providing an
example of its application.
The else clause in loops runs only if the loop completes without being interrupted
by a break statement. It’s useful when you want to execute something after the
loop finishes naturally.
Example:
for i in range(5):
print(i)
else:
print("Loop finished!") # Output: Loop finished!
• Significance: The else block executes only if the loop wasn’t terminated early
using break. If the loop was interrupted by break, the else block is skipped.

24. Explain string formatting operations in Python and illustrate with two
different methods.
Python provides multiple ways to format strings. Here are two common methods:
1. F-strings (formatted string literals):
o Syntax: f"string {variable}"
o Example:
o name = "Alice"
o age = 25
o print(f"Hello, {name}. You are {age} years old.") # Output: Hello, Alice.
You are 25 years old.
2. str.format() method:
o Syntax: "string {}".format(variable)
o Example:
o name = "Bob"
o age = 30
o print("Hello, {}. You are {} years old.".format(name, age)) # Output:
Hello, Bob. You are 30 years old.
Both methods provide powerful ways to create dynamic strings by inserting
variables inside them.

25. Write a Python program using if-elif-else and nested if to categorize a


number as positive/negative, even/odd.
Algorithm:
1. Start
2. Accept input for the number.
3. Check if the number is positive or negative using an if-elif condition.
4. For positive numbers, check if it’s even or odd using a nested if.
5. Display the appropriate message.
6. End.
Python Program:
# Accepting input from the user
num = int(input("Enter a number: "))

# Categorizing the number


if num > 0:
if num % 2 == 0:
print(f"{num} is positive and even.")
else:
print(f"{num} is positive and odd.")
elif num < 0:
if num % 2 == 0:
print(f"{num} is negative and even.")
else:
print(f"{num} is negative and odd.")
else:
print("The number is zero.")
Example Output:
Enter a number: 7
7 is positive and odd.

26. Create a program using a for loop to reverse a string and print the result
with proper formatting.
Algorithm:
1. Start
2. Accept input for the string.
3. Use a for loop to iterate over the string in reverse order.
4. Print the reversed string.
5. End.
Python Program:
# Accepting input string
text = input("Enter a string: ")

# Reversing the string using a for loop


reversed_text = ""
for char in text:
reversed_text = char + reversed_text

# Printing the reversed string


print(f"Reversed string: {reversed_text}")
Example Output:
Enter a string: hello
Reversed string: olleh

27. Compare the use of "while" and "for" loops in Python, providing
examples for different scenarios.
• For loop: Best for iterating over a known range or iterable (like a list or a string).
It's ideal when the number of iterations is predetermined.
o Example:
o for i in range(5):
o print(i) # Output: 0, 1, 2, 3, 4
• While loop: Best for situations where the loop needs to continue until a certain
condition is met, and you may not know how many iterations will occur.
o Example:
o i=0
o while i < 5:
o print(i) # Output: 0, 1, 2, 3, 4
o i += 1
Key Difference: Use a for loop when you know how many times you need to
iterate. Use a while loop when you are unsure and want to iterate based on a
condition.

28. Analyze the differences between string slicing and string methods in
terms of flexibility and efficiency.
• String Slicing: Allows you to extract a part of the string by specifying the
starting and ending indices.
o Example:
o text = "Python"
o sliced_text = text[1:4] # Output: 'yth'
o Flexibility: String slicing provides great flexibility when working with
specific indices.
o Efficiency: It is efficient because slicing directly accesses a portion of the
string.
• String Methods: Offer pre-built functionality like converting case, replacing
substrings, etc.
o Example:
o text = "Python"
o upper_text = text.upper() # Output: 'PYTHON'
o Flexibility: String methods are great for common tasks but are limited to
predefined actions.
o Efficiency: Less flexible than slicing, but can simplify tasks without
requiring custom code.

29. Assess the usefulness of the "continue" statement versus "if-else" logic in
loop control.
• continue Statement: Skips the current iteration and moves to the next iteration of
the loop.
o Usefulness: It is useful when you want to skip some iterations without
affecting the rest of the loop’s logic.
o Example:
o for i in range(5):
o if i == 3:
o continue
o print(i) # Output: 0, 1, 2, 4
• if-else Logic: Allows you to decide what to do in each iteration based on a
condition.
o Usefulness: It is more explicit and can be used to handle more complex
logic.
o Example:
o for i in range(5):
o if i == 3:
o print("Skipping 3")
o else:
o print(i) # Output: 0, 1, 2, Skipping 3, 4

30. Design a Python program to check if a user-input string is a palindrome,


using both loops and string slicing.
Algorithm:
1. Start
2. Accept the string input.
3. Check if the string is the same when reversed using loops and slicing.
4. Display the result.
5. End.
Python Program (Loop + Slicing):
# Accepting input string
text = input
("Enter a string: ")
Using slicing to reverse the string
reversed_text = text[::-1]
Checking if the string is a palindrome
if text == reversed_text: print(f"{text} is a palindrome.") else: print(f"{text} is
not a palindrome.")

**Example Output**:
Enter a string: radar radar is a palindrome.

---

UNIT-IV: FUNCTIONS AND FILES

31. Define recursion and function composition in Python, providing an example for
each concept.
• Recursion: Recursion occurs when a function calls itself to solve a smaller
instance of the same problem, usually with a base case to stop further
recursion.
Example:
def factorial(n):
if n == 0: # Base case
return 1
else:
return n * factorial(n - 1)
• Purpose: Recursion helps break down problems into simpler sub-problems,
especially useful for problems like tree traversal or calculating factorials.

• Function Composition: Function composition involves combining multiple


functions so that the output of one function becomes the input for the next.
Example:
def add(x):
return x + 3

def multiply(x):
return x * 2

def composed_function(x):
return multiply(add(x)) # First add, then multiply

result = composed_function(4)
print(result) # Output: 14 (4 + 3 = 7, 7 * 2 = 14)
• Purpose: Function composition simplifies complex operations by combining
smaller, reusable functions.

32. Explain the process of reading and writing files in Python, including the role of
format operators.
• Reading Files: Use open() to open a file in read mode ('r'), then read the
content using methods like .read() or .readlines().
• Writing Files: Use open() with write ('w') or append ('a') mode to write data
to the file.
Format Operators: These are used for formatting strings when writing to files, like
using f-strings or .format().
Example (Reading and Writing Files):
# Writing to a file
with open("data.txt", "w") as file:
file.write("Hello, world!\n")
file.write("This is a test file.\n")

# Reading from the file


with open("data.txt", "r") as file:
content = file.read()
print(content)
Example with Format Operators:
name = "Alice"
age = 25
with open("person.txt", "w") as file:
file.write(f"Name: {name}, Age: {age}\n")
• Purpose: Reading and writing files enables data storage and retrieval.
Format operators ensure the data is written in a structured and readable
way.

33. Discuss the difference between local and global scope in Python functions with
a detailed example.
• Local Scope: Variables defined inside a function are local to that function
and cannot be accessed from outside.
• Global Scope: Variables defined outside any function are global and can be
accessed throughout the script, even inside functions.
Example:
x = 10 # Global variable

def my_function():
y = 5 # Local variable
print("Inside function: x =", x) # Global variable accessed
print("Inside function: y =", y) # Local variable accessed

my_function()
print("Outside function: x =", x)
# print("Outside function: y =", y) # This will raise an error since y is local
• Purpose: Understanding scope helps manage variable access and avoid
naming conflicts in programs.

34. Explain how filenames and paths are handled in Python file operations, with an
example.
• File Paths:
o Relative Path: Specifies the file location relative to the current working
directory.
o Absolute Path: Specifies the full path to the file, starting from the root
of the file system.
• Path Handling in Python: Use os and os.path for manipulating file paths
(e.g., joining paths, getting the file name).
Example:
# Absolute path
with open("C:/Users/username/Documents/sample.txt", "r") as file:
print(file.read())

# Relative path
with open("sample.txt", "r") as file:
print(file.read())
• Purpose: Understanding file paths ensures that files can be accessed
correctly, whether they are in the same directory or in different locations.

35. Write a Python function that takes three numbers as parameters and returns
their average.
Algorithm:
1. Start.
2. Accept three numbers as input.
3. Calculate their sum.
4. Divide the sum by 3 to find the average.
5. Return the average.
6. End.
Python Program:
def average(num1, num2, num3):
return (num1 + num2 + num3) / 3

# Example usage
result = average(10, 20, 30)
print(f"The average is: {result}") # Output: 20.0

36. Create a program to write a list of student names to a file and then read and
display them.
Algorithm:
1. Define a list of student names.
2. Open a file in write mode and write the names.
3. Close the file after writing.
4. Open the file in read mode and display the names.
5. End.
Python Program:
# List of student names
students = ["Alice", "Bob", "Charlie", "Diana"]

# Write names to the file


with open("students.txt", "w") as file:
for student in students:
file.write(student + "\n")
# Read names from the file and display
with open("students.txt", "r") as file:
content = file.read()
print(content)
Example Output:
Alice
Bob
Charlie
Diana

37. Compare the use of recursion versus iteration in solving a factorial problem,
with examples.
• Recursion: A function calls itself to reduce the problem to smaller
subproblems, useful for problems like factorials.
• Iteration: Uses a loop to repeatedly execute the same code until a condition is
met, often more efficient for simple repetitive tasks.
Factorial using Recursion:
def factorial_recursive(n):
if n == 0:
return 1
return n * factorial_recursive(n - 1)
Factorial using Iteration:
def factorial_iterative(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
• Comparison: Recursion is more elegant but may lead to stack overflow for
large inputs. Iteration tends to be more efficient and easier to understand.

38. Analyze the advantages and limitations of using return values in functions
compared to global variables.
• Return Values: Functions return values to provide output, keeping the scope
of the result limited to the function.
o Advantage: Makes code modular and easier to debug.
o Limitation: Requires passing the result around explicitly.
• Global Variables: Can be accessed anywhere in the program.
o Advantage: Convenient for sharing data across functions.
o Limitation: Makes debugging difficult due to unpredictable side effects
and changes.
• Recommendation: Prefer return values for better code structure and
maintainability.

39. Evaluate the importance of proper error handling in file operations in Python.
• Error Handling: When working with files, proper error handling ensures
that your program can handle issues like missing files, permissions errors,
and other I/O problems without crashing.
• Common Techniques: Use try-except blocks to handle exceptions and
provide feedback or alternative actions.
Example:
try:
with open("non_existent_file.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("Error: The file was not found!")
• Purpose: Proper error handling ensures that your program runs smoothly
even in unpredictable situations, improving user experience and program
reliability.

40. Design a recursive function to compute the sum of digits in a number and test it
with user input.
Algorithm:
1. Start.
2. Accept a number as input.
3. If the number is 0, return 0 (base case).
4. Otherwise, return the last digit of the number plus the sum of the remaining
digits.
5. End.
Python Program:
def sum_of_digits(n):
if n == 0:
return 0
else:
return n % 10 + sum_of_digits(n // 10)

# Test with user input


num = int(input("Enter a number: "))
result = sum_of_digits(num)
print(f"The sum of digits is: {result}")
Example Output:
Enter a number: 1234
The sum of digits is: 10
UNIT-V: LIST, SET, TUPLES, DICTIONARIES

41. Define and differentiate between lists, tuples, and sets in Python with examples.
• Lists: Lists are ordered, mutable collections that can hold heterogeneous
items. You can change their contents (e.g., add, remove, or modify elements).
Example:
my_list = [1, 2, 3, 'apple', True]
my_list[0] = 10 # Modifying an element
• Tuples: Tuples are ordered, immutable collections. Once created, their
content cannot be changed. Tuples are typically used for storing data that
should not be altered.
Example:
my_tuple = (1, 2, 3, 'apple')
# my_tuple[0] = 10 # This would raise an error because tuples are immutable
• Sets: Sets are unordered collections of unique items. They do not allow
duplicate values and do not maintain any specific order.
Example:
my_set = {1, 2, 3, 4}
my_set.add(5) # Adding an element to a set

42. List and explain five dictionary methods in Python, including their practical
applications.
1. get(): Retrieves the value associated with a specified key. If the key is not
found, it returns a default value.
Example:
my_dict = {'name': 'Alice', 'age': 25}
print(my_dict.get('name')) # Output: Alice
2. keys(): Returns a view of all keys in the dictionary.
Example:
print(my_dict.keys()) # Output: dict_keys(['name', 'age'])
3. values(): Returns a view of all values in the dictionary.
Example:
print(my_dict.values()) # Output: dict_values(['Alice', 25])
4. update(): Updates the dictionary with key-value pairs from another
dictionary or an iterable.
Example:
my_dict.update({'city': 'New York'})
print(my_dict) # Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}
5. pop(): Removes a key-value pair and returns the value.
Example:
age = my_dict.pop('age') # Removes 'age' and returns the value
print(age) # Output: 25

43. Discuss the concept of mutability in lists and immutability in tuples, with
examples of their implications.
• Mutability (Lists): Lists are mutable, meaning their elements can be changed
after creation. This makes them flexible for scenarios where data might need
to be updated.
Example:
my_list = [1, 2, 3]
my_list[0] = 10 # Modifying a list element
• Immutability (Tuples): Tuples are immutable, which means once created,
their content cannot be changed. This ensures that tuples are safer when
data should not be modified.
Example:
my_tuple = (1, 2, 3)
# my_tuple[0] = 10 # This would raise an error
Implications:
• Mutability of lists makes them suitable for dynamic operations, like updating
a collection.
• Immutability of tuples ensures that the data remains unchanged, making
them useful as keys in dictionaries or when the data should remain constant.

44. Explain how tuples can be used as return values in functions, with an
illustrative example.
• Tuples can be returned by functions to return multiple values from a
function at once. Since tuples are immutable, this can ensure that the
returned values are not modified outside the function.
Example:
def get_user_info():
name = "Alice"
age = 30
return name, age # Returning a tuple

result = get_user_info()
print(result) # Output: ('Alice', 30)
• Purpose: Returning a tuple allows multiple values to be returned efficiently
in a single return statement, which is especially useful when you need to
return related data.

45. Write a Python program to create a list, perform slicing, and append elements,
displaying the results.
Algorithm:
1. Create a list of some initial values.
2. Perform slicing to extract a portion of the list.
3. Append new elements to the list.
4. Display the updated list.
Python Program:
# Step 1: Create a list
my_list = [1, 2, 3, 4, 5]

# Step 2: Perform slicing


sliced_list = my_list[1:4] # Extracting elements from index 1 to 3
print("Sliced List:", sliced_list) # Output: [2, 3, 4]

# Step 3: Append new elements


my_list.append(6)
my_list.append(7)

# Step 4: Display the updated list


print("Updated List:", my_list) # Output: [1, 2, 3, 4, 5, 6, 7]

46. Create a dictionary of five items (product: price) and write a program to
calculate the total price.
Algorithm:
1. Create a dictionary with product names as keys and their prices as values.
2. Iterate through the dictionary to sum up the prices.
3. Display the total price.
Python Program:
# Step 1: Create a dictionary of products and prices
products = {'apple': 1.2, 'banana': 0.5, 'orange': 0.8, 'grapes': 2.5, 'watermelon':
3.0}

# Step 2: Calculate the total price


total_price = sum(products.values())

# Step 3: Display the total price


print(f"Total price: ${total_price:.2f}") # Output: Total price: $8.00

47. Compare the use of sets and lists for storing and manipulating data, with
examples of operations.
• Sets:
o Unordered collections with no duplicate elements. They are fast for
membership testing.
o Operations: Union (|), Intersection (&), Difference (-).
Example:
my_set = {1, 2, 3}
my_set.add(4) # Adding an element
print(my_set) # Output: {1, 2, 3, 4}
• Lists:
o Ordered collections that can contain duplicates.
o Operations: Append, Insert, Remove, Pop.
Example:
my_list = [1, 2, 3, 2]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 2, 4]
• Comparison:
o Sets are more efficient for membership testing and eliminating
duplicates, but they don't maintain order.
o Lists maintain order and allow duplicates, making them suitable for
storing sequences.

48. Analyze the differences between aliasing and cloning in lists, demonstrating
their effects on code.
• Aliasing: When two variables point to the same object in memory, changes to
one variable will affect the other.
Example (Aliasing):
list1 = [1, 2, 3]
list2 = list1 # list2 is now an alias of list1
list2[0] = 10
print(list1) # Output: [10, 2, 3] (list1 is affected)
• Cloning: Creating a copy of the list ensures that changes to the new list do
not affect the original list.
Example (Cloning):
list1 = [1, 2, 3]
list2 = list1.copy() # Cloning list1
list2[0] = 10
print(list1) # Output: [1, 2, 3] (list1 is not affected)
• Implications: Aliasing can lead to unintended side effects, while cloning
avoids this issue by creating independent copies.

49. Assess the advantages of using NumPy and pandas over traditional Python lists
for data analysis.
• NumPy:
o Provides an efficient, vectorized way to perform mathematical and
statistical operations.
o Supports multi-dimensional arrays and offers optimized performance.
• pandas:
o Built on top of NumPy, pandas offers DataFrames, which are ideal for
handling structured data (like tables).
o Efficient for working with time series, missing data, and large datasets.
• Advantages:
o Efficiency: NumPy and pandas outperform lists for large data sets due
to optimized C-based implementations.
o Convenience: pandas provides easy-to-use data manipulation
functions, like grouping, merging, and reshaping data.

50. Design a Python program using Matplotlib to plot a line graph of temperature
data over a week.
Algorithm:
1. Import necessary libraries (matplotlib for plotting, numpy for data).
2. Create a list of temperature data for each day of the week.
3. Use Matplotlib's plot() function to create a line graph.
4. Add labels and a title to the graph.
5. Display the graph.
Python Program:
import matplotlib.pyplot as plt

# Step 1: Temperature data (in Celsius) for each day of the week
days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
temperatures = [22, 24
, 23, 21, 25, 27, 26]
Step 2: Plot the data
plt.plot(days, temperatures, marker='o')
Step 3: Add labels and title
plt.xlabel('Day of the Week') plt.ylabel('Temperature (°C)') plt.title('Temperature
Data Over a Week')
Step 4: Display the graph
plt.show()

Output:

You might also like