0% found this document useful (0 votes)
55 views110 pages

Ilovepdf Merged

Uploaded by

bishtmanju352
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)
55 views110 pages

Ilovepdf Merged

Uploaded by

bishtmanju352
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/ 110

AKTU

Python AKTU
(SEM III) THEORY EXAMINATION 2019-20

Solution
SUBJECT CODE: KNC-302
B.TECH.(CSE /CS IT/ CS AI ML) SEMESTER -IV

Academic Session: 2022-23, Even Semester


Faculty
Dr. Aadarsh Malviya
(Associate Professor Department of CSE)

Dronacharya Group of Institutions


Plot No. 27, Knowledge Park-3, Greater Noida, Uttar Pradesh 201308

Affiliated to

Dr. A P J Abdul Kalam Technical University


Lucknow, Uttar Pradesh 226031
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

.SECTION A
1. Attempt all questions in brief. 2 x 10 = 20

a. What is the difference between list and tuples in Python? CO1


Soln. In Python, both lists and tuples are used to store collections of items, but they have some
fundamental differences. The main differences between lists and tuples are their mutability,
syntax, and usage.

1. Mutability:
 Lists are mutable, which means you can modify, add, or remove elements after the
list is created.
 Tuples, on the other hand, are immutable, meaning they cannot be modified once
created. You cannot add, remove, or modify elements in a tuple.
2. Syntax:
 Lists are defined using square brackets [] and elements are separated by commas.
Example: my_list = [1, 2, 3]
 Tuples are defined using parentheses () and elements are separated by commas.
Example: my_tuple = (1, 2, 3)
3. Usage:
 Lists are commonly used when you have a collection of items that may change over
time. You can add, remove, or modify elements freely. Lists are useful for
implementing data structures like stacks, queues, or dynamic arrays.
 Tuples are typically used when you have a collection of items that should not be
changed. Since tuples are immutable, they provide data integrity and are useful
when you want to ensure that the data remains constant throughout the program.
Tuples are often used to represent fixed collections such as coordinates, database
records, or function arguments.

Here are some examples to illustrate the differences:

# Lists

my_list = [1, 2, 3]

my_list[0] = 10

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

# Tuples

my_tuple = (1, 2, 3)

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 1
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

# Trying to modify the tuple will result in an error

my_tuple[0] = 10 # Raises TypeError: 'tuple' object does not support item assignment

In summary, lists are mutable and commonly used for dynamic collections, while tuples are
immutable and typically used for fixed collections where data integrity is important.

b. In some languages, every statement ends with a semi-colon (;). What happens if you put a semi-
colon at the end of a Python statement?
Soln.
In Python, the use of a semi-colon (;) at the end of a statement is optional and not
required. Python uses a different approach to indicate the end of a statement: line breaks.
Each line break indicates the end of a statement in Python.

If you choose to include a semi-colon at the end of a statement in Python, it will still be
treated as a valid statement, and the interpreter will execute it without any issues. However,
it is considered a style convention in Python to omit the semi-colon unless you have
multiple statements on the same line.

Here's an example to illustrate the usage of a semi-colon in Python:

# Using a semi-colon at the end of the statement (valid but not commonly used)
print("Hello"); # Output: Hello

# Omitting the semi-colon at the end of the statement (preferred style)


print("Hello") # Output: Hello

# Multiple statements on the same line with semi-colons (not recommended)


a = 5; b = 10; print(a + b) # Output: 15
In Python, the recommended style is to use line breaks to separate statements, making the
code more readable and conforming to the common Python coding conventions.
c. Mention five benefits of using Python.
Soln. Here are five benefits of using Python:

1. Readability and Simplicity: Python emphasizes code readability and has a clean and easy-
to-understand syntax. It uses indentation to define code blocks, making it more readable
than languages that use braces. This simplicity allows developers to express concepts with
fewer lines of code, enhancing code maintainability and reducing the time required for
development and debugging.
2. Wide Range of Libraries and Frameworks: Python boasts a vast ecosystem of libraries and
frameworks for various purposes. The Python Package Index (PyPI) contains thousands of
open-source libraries, such as NumPy, Pandas, TensorFlow, Django, Flask, and more. These
libraries empower developers to leverage existing solutions, accelerate development, and
tackle complex tasks efficiently.

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 2
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

3. Portability and Cross-Platform Compatibility: Python is a portable language, meaning it can


run on different operating systems (Windows, macOS, Linux) without major modifications.
It allows developers to write code once and execute it on multiple platforms, reducing the
effort required to create platform-specific versions of the same application.
4. Rapid Development and Prototyping: Python's simplicity and extensive library support
contribute to rapid development and prototyping. It provides high-level data structures
and dynamic typing, enabling developers to focus on solving problems rather than dealing
with complex language mechanics. This feature makes Python an excellent choice for
projects that require quick iteration and experimentation.
5. Community and Support: Python has a vibrant and active community of developers, which
contributes to its growth and evolution. The Python community provides extensive
documentation, tutorials, online forums, and resources that facilitate learning and problem-
solving. Additionally, the community actively contributes to the development of libraries
and frameworks, ensuring continuous improvement and support.

These are just a few of the many advantages of using Python. Its versatility, scalability, and
broad range of applications make it a popular choice for various domains, including web
development, data analysis, machine learning, scientific computing, and more.

d. How is Python an interpreted language?


Soln. Python is considered an interpreted language because it does not need to be compiled
before execution. Instead, Python code is executed line by line using an interpreter. Here's
an overview of how Python's interpretation process works:

1. Source Code: Python programs are written in plain text files with a .py extension. These
files contain human-readable code written in the Python programming language.
2. Lexical Analysis: The Python interpreter first performs a process called lexical analysis,
where it breaks down the source code into a sequence of fundamental components called
tokens. Tokens include keywords, identifiers, operators, literals, and punctuation symbols.
3. Parsing: After lexical analysis, the interpreter parses the tokens to create a parse tree or
abstract syntax tree (AST). The parse tree represents the structure of the code based on
Python's grammar rules, ensuring that the code is syntactically correct.
4. Compilation to Bytecode: Once the parse tree is generated, the Python interpreter
translates it into an intermediate representation called bytecode. Bytecode is a low-level,
platform-independent representation of the code that can be executed by the Python
Virtual Machine (PVM).
5. Execution by the PVM: The bytecode is then executed by the Python Virtual Machine, which
is responsible for interpreting and executing the instructions. The PVM reads the bytecode
line by line and performs the necessary operations to execute the code.

This interpretation process allows Python programs to be executed without the need for
explicit compilation. The code can be modified and run directly, facilitating quick
development cycles and easy experimentation. However, it's worth noting that Python

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 3
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

implementations like CPython can also perform just-in-time (JIT) compilation or optimize
the execution of bytecode to improve performance in some cases.

It's important to mention that while Python is an interpreted language, it does provide
tools like pyc files (compiled bytecode) and packages like PyInstaller or cx_Freeze that can
bundle Python programs into standalone executables. These tools package the interpreter,
bytecode, and necessary dependencies together, providing a way to distribute Python
applications without requiring the end-users to have Python installed.

e. What type of language is python?

Soln. Python is a high-level, general-purpose programming language. It was designed to


prioritize code readability and simplicity, making it easier for developers to express
concepts in fewer lines of code compared to other languages. Python supports multiple
programming paradigms, including procedural, object-oriented, and functional
programming.

Here are some key characteristics that define Python as a programming language:

1. Interpreted: Python is an interpreted language, meaning it does not need to be compiled


before execution. Instead, Python code is executed line by line using an interpreter, which
converts the source code into bytecode that is then executed by the Python Virtual
Machine (PVM).
2. Dynamically Typed: Python is dynamically typed, which means variable types are
determined at runtime. Developers do not need to declare the type of a variable explicitly.
Python infers the variable type based on the assigned value, allowing for flexibility and
reducing the verbosity of code.
3. Object-Oriented: Python fully supports object-oriented programming (OOP) principles. It
provides classes, objects, and inheritance, allowing developers to create and use objects
with encapsulated data and behaviors. Python also supports concepts like polymorphism
and abstraction, making it suitable for building complex, modular applications.
4. Multipurpose: Python is a versatile language that can be used for various purposes. It has a
broad range of libraries and frameworks that support areas such as web development, data
analysis, scientific computing, machine learning, artificial intelligence, automation, scripting,
and more. Its versatility contributes to its popularity and widespread adoption.
5. Extensive Standard Library: Python has a comprehensive standard library that provides a
wide range of modules and functions for common tasks. The standard library includes
modules for file I/O, networking, regular expressions, mathematical operations, data
serialization, and much more. This extensive library ecosystem enhances Python's
capabilities and enables developers to accomplish complex tasks efficiently.

Python's combination of simplicity, readability, versatility, and a thriving community has


made it a popular choice among developers for a wide range of applications and use cases.

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 4
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

f. What are local variables and global variables in Python?

In Python, variables can be classified as local variables and global variables based on their
scope and visibility within a program. Here's an explanation of each:

1. Local Variables:
 Local variables are defined within a specific block, such as a function or a loop. They
have limited scope and are only accessible within the block where they are defined.
 Local variables are created when a block is entered and destroyed when the block is
exited.
 Local variables are used to store temporary or intermediate values that are relevant
only within a specific block.
 If you try to access a local variable outside its scope, you will encounter a
NameError.
Example:

def my_function():

x = 10 # local variable

print(x)

my_function() # Output: 10

print(x) # Raises NameError: name 'x' is not defined

Global Variables:
 Global variables are defined outside of any function or block and are accessible
throughout the program.
 Global variables have a global scope, meaning they can be accessed and modified
from any part of the program, including functions, loops, or other blocks.
 Global variables are typically used to store data that needs to be shared and
accessed by multiple parts of the program.
 If you want to modify a global variable within a function, you need to use the
global keyword to explicitly indicate that you are referring to the global variable
and not creating a new local variable.

x = 10 # global variable

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 5
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

def my_function():

global x

x += 5 # Modifying the global variable

print(x)

my_function() # Output: 15

print(x) # Output: 15 (value modified by the function)

It's generally recommended to use global variables sparingly and prefer local variables
whenever possible. Using local variables helps encapsulate data within specific blocks and
improves code readability, maintainability, and reduces the chances of unintended
modifications.

It's important to note that in Python, nested functions have access to variables from
enclosing functions, creating a concept known as "closure." However, this is beyond the
scope of local and global variables.

g. What is the difference between Python Arrays and lists?

In Python, arrays and lists are both used to store collections of items, but they have some
fundamental differences in terms of functionality and underlying implementation.

Lists:

 Lists in Python are a built-in data type and are extremely versatile. They can contain
elements of different data types and can be resized dynamically.
 Lists are implemented as dynamic arrays internally. This means that the elements are stored
in contiguous memory locations, allowing efficient access to individual elements by their
index.
 Lists support various built-in methods and operations, such as appending or removing
elements, slicing, sorting, and more. They offer a wide range of functionalities, making
them suitable for most general-purpose scenarios.
 Lists are represented using square brackets [] and are mutable, meaning you can modify,
add, or remove elements after the list is created.

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 6
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

Arrays:

 Arrays in Python are provided by external libraries, such as the NumPy library, and are not
part of the built-in Python data types. To use arrays, you need to import the appropriate
library.
 Arrays are homogeneous data structures, meaning they can only store elements of the
same data type. This restriction allows for more efficient storage and operations.
 Arrays are implemented as fixed-size, contiguous blocks of memory, optimized for
numerical operations. Due to their fixed size, arrays cannot be resized once created.
 Arrays provide a wide range of mathematical operations and functions optimized for
numerical computations, such as matrix operations, linear algebra, statistical analysis, and
more.
 Arrays are represented using library-specific syntax (e.g., numpy.array()) and can be
multidimensional.
 Arrays generally offer better performance for numerical computations and large-scale data
processing compared to lists.

Here's a basic example comparing lists and arrays:

# Using lists

my_list = [1, 2, 3]

my_list.append(4)

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

# Using arrays (NumPy library)

import numpy as np

my_array = np.array([1, 2, 3])

my_array = np.append(my_array, 4)

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

In summary, lists are versatile, dynamic arrays that can store elements of different types

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 7
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

and provide extensive built-in functionality. Arrays, on the other hand, are typically used for
numerical computations, provide optimized operations, and require homogeneous data
types. Arrays are commonly accessed via external libraries like NumPy.

h. D efine ADTinterface.

An "ADT interface" refers to the interface or contract that defines the operations and
behaviors of an Abstract Data Type (ADT). An ADT is a high-level description of a data
structure that specifies the behavior of the data structure without specifying the
implementation details. It focuses on what operations can be performed on the data
structure and what properties those operations have.

The ADT interface serves as a blueprint or template for implementing the ADT in a
programming language. It defines the set of methods, functions, or operations that a
concrete implementation of the ADT should provide. The ADT interface describes the
inputs, outputs, and expected behavior of each operation, without specifying how the
operations are implemented internally.

The purpose of an ADT interface is to provide a clear and standardized way to interact with
the data structure, regardless of the specific implementation. It allows different
implementations of the same ADT to be used interchangeably as long as they adhere to
the defined interface.

For example, let's consider an ADT interface for a Stack:

class StackInterface:

def push(self, item):

"""Inserts an item onto the top of the stack."""

def pop(self):

"""Removes and returns the item from the top of the stack."""

def peek(self):

"""Returns the item from the top of the stack without removing it."""

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 8
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

def is_empty(self):

"""Checks if the stack is empty and returns a boolean value."""

def size(self):

"""Returns the number of items currently in the stack."""

In the above example, the StackInterface defines the set of operations that any concrete
implementation of a stack should support. The interface specifies the methods push(),
pop(), peek(), is_empty(), and size(), along with their respective descriptions. A class
implementing this interface would need to provide the implementations for these
methods.

By separating the ADT interface from its implementation, it allows for abstraction,
modularity, and code reuse. Multiple implementations of the same ADT can be created as
long as they adhere to the defined interface, providing flexibility and allowing different
implementations to be used interchangeably in various parts of the program.

i. Define floor division with example

Floor division is a mathematical operation that returns the largest integer value less than or
equal to the division result of two numbers. In Python, the floor division operator is
denoted by a double forward slash ( //).

Here's an example to illustrate floor division

# Floor division example

result = 10 // 3

print(result) # Output: 3

In the above example, we perform floor division on the numbers 10 and 3 using the //
operator. The result is 3, as the largest integer value less than or equal to the division of 10
by 3 is 3.

It's important to note that floor division always returns an integer, discarding any decimal
remainder. It essentially performs integer division, rounding down the result if necessary.
This behavior distinguishes floor division from regular division ( /), which returns a floating-

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 9
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

point result with decimal places.

Here are a few more examples to showcase the behavior of floor division:

# Floor division examples

print(15 // 4) # Output: 3

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

print(7.5 // 2.5) # Output: 3.0

print(8 // 2) # Output: 4

In the above examples, the floor division operation returns the largest integer that is less than or
equal to the division result, irrespective of the positive or negative signs of the operands.

j. Differentiate Fruitful functions and void functions.

Fruitful functions and void functions are two different types of functions in programming,
differing in their return values and their primary purpose. Here's a breakdown of each:

1. Fruitful Functions (Value-Returning Functions):


 Fruitful functions are functions that compute a value and return it as the result.
 These functions take input arguments, perform some operations or computations
based on the inputs, and then produce and return a value as the output.
 The return value can be of any data type: numbers, strings, lists, objects, etc.
 Fruitful functions are designed to provide a result that can be used or further
processed by other parts of the program.
 The calling code typically receives the return value and can assign it to a variable,
use it in expressions, or pass it as an argument to another function.
def add_numbers(a, b):

sum = a + b

return sum

result = add_numbers(5, 3)

print(result) # Output: 8

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 10
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

1. In the above example, the add_numbers function takes two arguments, performs addition,
and returns the sum as the result. The returned value is then assigned to the result
variable.
2. Void Functions (Non-Value-Returning Functions):
 Void functions are functions that perform some operations or actions without
returning a value.
 These functions can modify the program state, print output, or perform other
actions, but they do not produce a specific result that can be used in expressions or
assigned to a variable.
 Void functions are primarily used for their side effects, such as altering the
program's state or producing output, rather than computing and returning a value.
 Void functions are commonly used for tasks like printing, updating variables, or
modifying data structures.
def greet(name):

print("Hello, " + name + "!")

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

1. In the above example, the greet function takes a name argument and prints a greeting
message to the console. It does not return any value; instead, it performs an action directly.

In summary, fruitful functions are used to compute and return values that can be used
elsewhere in the program, while void functions are used for their side effects without
returning a specific result. The choice between these types of functions depends on the
specific requirements and purpose of the function in your program.

Section B
2 Attempt any three of the following: 3 x 10 = 30
a. Explain iterator. Write a program to demonstrate the tower of Hanoi using function CO1
Soln. An iterator in Python is an object that implements the iterator protocol, which consists of
two methods: __iter__() and __next__(). Iterators are used to traverse or loop over a
sequence of elements, such as a list or a string, in a controlled and efficient manner. They
provide a way to access elements of a collection one at a time, without the need to store
the entire collection in memory.

To demonstrate the Tower of Hanoi problem using functions, we can define a recursive
function that follows the rules of the problem. Here's an example program:

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 11
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

def tower_of_hanoi(n, source, target, auxiliary):

if n > 0:

# Move n-1 disks from source to auxiliary tower

tower_of_hanoi(n-1, source, auxiliary, target)

# Move the nth disk from source to target tower

print(f"Move disk {n} from {source} to {target}")

# Move the n-1 disks from auxiliary to target tower

tower_of_hanoi(n-1, auxiliary, target, source)

# Test the function

tower_of_hanoi(3, 'A', 'C', 'B')

In the above program, the tower_of_hanoi function takes four parameters: n (the number
of disks), source (the source tower), target (the target tower), and auxiliary (the
auxiliary tower).

The function follows the recursive algorithm of the Tower of Hanoi problem:

1. If n is greater than 0:
 Move n-1 disks from the source tower to the auxiliary tower recursively.
 Move the nth disk from the source tower to the target tower.
 Move the n-1 disks from the auxiliary tower to the target tower recursively.

The function is initially called with n=3, source tower as 'A', target tower as 'C', and auxiliary
tower as 'B'. The program then prints the sequence of moves required to solve the Tower
of Hanoi problem for 3 disks.

Running the program will output:

Move disk 1 from A to C

Move disk 2 from A to B

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 12
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

Move disk 1 from C to B

Move disk 3 from A to C

Move disk 1 from B to A

Move disk 2 from B to C

Move disk 1 from A to C

Each line represents a move, indicating the disk number and the towers involved in the
move.

The Tower of Hanoi problem is a classic example of recursion and helps demonstrate the
concept of recursive function calls.

b. Discuss function in python with its parts and scope. Explain with example. (Take Simple calculator CO2
with add, subtract, Division and Multiplication)
Soln. In Python, a function is a named block of reusable code that performs a specific task or a
set of operations. Functions help in modularizing code, promoting code reuse, and
improving code organization. A function consists of several parts, including the function
signature, parameters, body, and return statement (if applicable). The scope of a function
determines where and how the function and its variables can be accessed.

Let's discuss each part of a function and explain them using an example of a simple
calculator that performs addition, subtraction, division, and multiplication:

def calculator(operation, num1, num2):


"""
A simple calculator function to perform basic arithmetic operations.

Parameters:
- operation: The operation to be performed ('add', 'subtract', 'multiply', 'divide').
- num1: The first number.
- num2: The second number.

Returns:
- The result of the arithmetic operation.
"""
if operation == 'add':
result = num1 + num2
elif operation == 'subtract':
result = num1 - num2
elif operation == 'multiply':
result = num1 * num2
elif operation == 'divide':
result = num1 / num2

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 13
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

else:
print("Invalid operation!")
return None

return result

# Test the calculator function


result = calculator('add', 5, 3)
print(result) # Output: 8

result = calculator('subtract', 5, 3)
print(result) # Output: 2

result = calculator('multiply', 5, 3)
print(result) # Output: 15

result = calculator('divide', 10, 2)


print(result) # Output: 5
1. Function Signature: The function signature is the first line of a function and includes the
def keyword, the function name (calculator in this example), and the parameter list
enclosed in parentheses.
2. Parameters: Parameters are placeholders that allow passing values into the function. In this
example, the calculator function takes three parameters: operation, num1, and num2.
These parameters represent the operation to be performed and the two numbers on which
the operation is to be applied.
3. Function Body: The function body contains the set of statements or code that are executed
when the function is called. In the calculator function, the body consists of conditional
statements (if-elif-else) that determine the arithmetic operation to perform based on
the value of the operation parameter.
4. Return Statement: The return statement specifies the value to be returned from the
function. In this example, the calculator function returns the result of the arithmetic
operation as the output. If an invalid operation is provided, it prints an error message and
returns None.
5. Scope: The scope of a variable refers to the region or part of the program where the
variable is accessible. In the example, the variables operation, num1, num2, and result are
local variables. They are defined within the function and can only be accessed within the
function's body. The result variable is also used as the return value of the function,
making it accessible to the calling code.
Variables defined outside the function, such as the result variable in the calling code,
have a different scope and are separate from the function's scope.

In the example, the calculator function takes the operation and two numbers as input
and performs the requested arithmetic operation. The calling code demonstrates how to
use the function by passing different operations and numbers and printing the resulting

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 14
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

output.

The function encapsulates the logic

c. Discuss ADT in python.How to define ADT? Write code for a student information CO4
Soln. In Python, an Abstract Data Type (ADT) is a concept that defines a high-level description of
a data structure along with the operations that can be performed on that data structure. It
focuses on what the data structure does rather than how it is implemented. ADTs provide
an abstraction layer, allowing us to think about data structures in a more conceptual
manner.

To define an ADT in Python, we can use a class as a blueprint and define methods that
represent the operations or behaviors associated with the data structure. These methods
encapsulate the behavior and logic related to the ADT, providing a clear interface for
interacting with the data.

Let's consider an example of defining an ADT for student information:

class Student:
def __init__(self, name, age, roll_number):
self.name = name
self.age = age
self.roll_number = roll_number

def get_name(self):
return self.name

def get_age(self):
return self.age

def get_roll_number(self):
return self.roll_number

def set_name(self, name):


self.name = name

def set_age(self, age):


self.age = age

def set_roll_number(self, roll_number):


self.roll_number = roll_number

def display_info(self):
print(f"Name: {self.name}")
print(f"Age: {self.age}")
print(f"Roll Number: {self.roll_number}")

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 15
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

# Usage of the Student ADT


student1 = Student("Alice", 20, "A001")
student1.display_info()

student1.set_age(21)
student1.display_info()

In the above example, we define a Student class representing the ADT for student
information. The class has instance variables ( name, age, and roll_number ) to store the
student's information.

The class also provides methods to interact with the student's data, such as get_name(),
get_age(), get_roll_number() for retrieving the information, and set_name(),
set_age(), set_roll_number() for updating the information.

Additionally, there is a display_info() method that prints the student's information to


the console.

By encapsulating the student's information and providing methods to access and modify
that information, we have created an ADT for student information. This abstraction allows
us to work with student objects in a more meaningful and structured way.

We can create multiple student objects and manipulate their information using the defined
methods. In the example, student1 is an instance of the Student class, and we
demonstrate how to access and update the student's information by calling the
appropriate methods.

By following this approach, you can define and work with different ADTs in Python,
encapsulating data and providing operations to manipulate and access that data in a
controlled manner.

d. Explain all the Conditional statement in Python using small code example CO3
Soln. the three conditional statements in Python—if, elif, and else—along with small code
examples for each.

1. if statement: The if statement allows you to execute a block of code if a certain condition
is true.
Example:
x = 10

if x > 5:
print("x is greater than 5")
1. In this example, the code inside the if block will be executed only if the condition x > 5 is
true. If the condition is false, the code block is skipped.

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 16
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

2. if-else statement: The if-else statement allows you to execute different blocks of code
based on a condition. If the condition is true, the if block is executed; otherwise, the else
block is executed.
Example:
x=3

if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
1. In this example, if the condition x > 5 is true, the code inside the if block is executed.
Otherwise, the code inside the else block is executed.
2. if-elif- else statement: The if-elif-else statement allows you to test multiple
conditions and execute the block of code associated with the first true condition. It
provides an alternative to a long chain of if-else statements.
Example:

x=7

if x > 10:
print("x is greater than 10")
elif x > 5:
print("x is greater than 5 but less than or equal to 10")
else:
print("x is less than or equal to 5")
1. In this example, multiple conditions are checked sequentially. The code inside the if block
is executed if the condition x > 10 is true. If it's false, the condition x > 5 is checked, and
the corresponding elif block is executed if true. If both conditions are false, the code
inside the else block is executed.

These are the basic conditional statements in Python. They allow you to control the flow of
your program based on certain conditions, enabling different code paths to be executed
depending on the evaluation of the conditions.

e. What is Python? How Python is interpreted? What are the tools that help CO5
to find bugs or perform static analysis? What are Python decorators?
1. What is Python? Python is a high-level, interpreted, and dynamically-typed programming
Soln.
language. It was created by Guido van Rossum and first released in 1991. Python
emphasizes code readability, simplicity, and a clear syntax, which makes it easy to learn and
understand. It supports multiple programming paradigms, including procedural, object-
oriented, and functional programming.
2. How Python is interpreted? Python is an interpreted language, which means that Python
programs are executed line by line at runtime, without the need for prior compilation.
When you run a Python program, the Python interpreter reads and executes the code one
statement at a time. It translates each statement into intermediate bytecode, which is then

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 17
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

executed by the Python Virtual Machine (PVM).


The Python interpreter can be implemented in different ways, such as using the CPython
interpreter (the default and most widely used implementation), Jython (runs on the Java
Virtual Machine), IronPython (runs on the .NET Common Language Runtime), and PyPy (a
Just-in-Time compiler-based interpreter).
3. Tools for finding bugs or performing static analysis in Python: There are several tools
available for finding bugs, performing static analysis, and improving code quality in Python.
Some popular ones include:
 Pylint: A widely used tool that checks Python code for errors, style issues, and
potential bugs.
 Pyflakes: A lightweight tool that focuses on finding common programming errors in
Python code.
 Flake8: Combines the functionalities of Pylint, Pyflakes, and a style guide checker
called pycodestyle.
 Bandit: A security-focused tool that helps identify common security issues in Python
code.
 mypy: A static type checker for Python that helps catch type-related errors and
provides type annotations.
 PyCharm: An integrated development environment (IDE) for Python that includes
built-in code inspection, debugging, and error highlighting features.
4. Python decorators: Python decorators are a powerful feature that allows you to modify the
behavior of functions or classes by wrapping them with additional functionality. Decorators
are denoted by the @ symbol followed by the decorator name, placed above the function
or class definition.
Here's an example of a decorator that logs the execution time of a function:
import time

def timer_decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
execution_time = end_time - start_time
print(f"Execution time: {execution_time} seconds")
return result
return wrapper

@timer_decorator
def my_function():
time.sleep(2)
print("Function execution complete.")

my_function()

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 18
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

In this example, the timer_decorator is defined, which takes a function as input, wraps it
with additional code to measure the execution time, and returns the modified function. The
@timer_decorator syntax is then used to apply the decorator to the my_function
function. When my_function is called, the decorator code is executed before and after the
function's execution, allowing us to log the time taken for execution.
Decorators provide a clean and reusable way to add functionality to functions or classes
without modifying their original code, making it easier to separate concerns and enhance
code modularity.

Section C
3. Attempt any one part of the following: 1 x 10 = 10
a. Write short notes with example:The Programming Cycle for Python, Elements of Python, Type CO5
Conversion in Python, Operator Precedence, and Boolean Expression.
1. The Programming Cycle for Python:
 Problem Analysis: Identify the problem to be solved and analyze its requirements.
 Algorithm Design: Plan the solution by breaking it down into smaller steps.
 Coding: Implement the solution using the Python programming language.
 Testing and Debugging: Verify that the code produces the expected results and fix
any issues.
 Deployment and Maintenance: Deploy the code and maintain it by making updates or
improvements as needed.
2. Elements of Python:
 Variables: Used to store data values. Example: x = 10
 Data Types: Determines the type and behavior of a value. Example: name = "John"
 Operators: Perform operations on values. Example: result = num1 + num2
 Control Flow Statements: Control the flow of program execution. Example: if
condition:
 Functions: Reusable blocks of code that perform specific tasks. Example: def add(x,
y):
3. Type Conversion in Python:
 Implicit Conversion: Automatic conversion of one data type to another. Example: num1
= 10.5 + 5
Explicit Conversion (Type Casting): Manual conversion of one data type to another.
Example: num2 = int("10")
4. Operator Precedence:
 Determines the order in which operators are evaluated in an expression.
 Operators with higher precedence are evaluated first.
 Example: result = 5 + 3 * 2 In this case, the multiplication ( *) has higher
precedence than addition ( +), so 3 * 2 is evaluated first, resulting in 6. Then, the
addition is performed, resulting in 5 + 6 and the final value is 11.
5. Boolean Expression:
 Represents a condition that can be either true or false.
 Used in control flow statements and logical operations.

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 19
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

 Example: x > 10 In this case, the expression evaluates to True if the value of x is
greater than 10, and False otherwise.

These short notes provide an overview of each topic, and the examples illustrate their usage
in Python programming.

b. How memory is managed in Python? Explain PEP 8. Write a Python CO1


program to print even length words in a string
1. Memory Management in Python: Python uses automatic memory management through a
mechanism called "garbage collection." Here are some key points:
 Python utilizes a private heap space for memory management.
 Objects are dynamically allocated and deallocated as needed.
 Python's garbage collector automatically reclaims memory occupied by objects that
are no longer in use.
 Memory allocation and deallocation are handled by the Python runtime, relieving the
programmer from managing memory explicitly.
2. PEP 8 (Python Enhancement Proposal 8): PEP 8 is a style guide for Python code, providing
guidelines and best practices to enhance code readability and maintainability. Here are some
highlights:
 Use consistent indentation (4 spaces per level).
 Limit line length to 79 characters.
 Use meaningful variable and function names.
 Separate code blocks with blank lines.
 Follow naming conventions for functions, variables, and classes.
 Use comments to explain code and provide documentation.
 Follow the import conventions and module organization.
 Strive for clarity and readability over cleverness.
3. Python program to print even length words in a string: Here's an example program that
prints the even length words in a string:
def print_even_length_words(string):
words = string.split()
for word in words:
if len(word) % 2 == 0:
print(word)

# Example usage
input_string = "Python is a powerful and versatile programming language"
print_even_length_words(input_string)
In this program, the print_even_length_words function takes a string as input. It splits the
string into individual words using the split() method and stores them in the words list.
Then, it iterates over each word and checks if its length is even using the modulo operator
(%). If the length is even, the word is printed.
The example input string is "Python is a powerful and versatile programming language." The
program will print the words "Python," "is," "powerful," and "language" because they have an

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 20
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

even length (i.e., the number of characters is divisible by 2).

4. Attempt any one part of the following: 1 x 10 = 10


a. Explain Expression Evaluation & Float Representation with example. Write a Python Program for CO2
How to check if a given number is Fibonacci number
Expression Evaluation: Expression evaluation refers to the process of calculating the value
of an expression involving operators, operands, and variables. Python follows operator
precedence and associativity rules to evaluate expressions. Here's an example:

x = 10
y=5
z=3

result = (x + y) * z - y ** 2
print(result) # Output: 38
1. In this example, the expression result is assigned the value of (x + y) * z - y ** 2.
The expression is evaluated step by step:
 First, x + y is evaluated as 10 + 5, resulting in 15.
 Then, (x + y) * z is evaluated as 15 * 3, resulting in 45.
 Finally, (x + y) * z - y ** 2 is evaluated as 45 - 5 ** 2, resulting in 38.
The final value, 38, is stored in the result variable and printed.
2. Float Representation: Floating-point numbers in Python (and most programming
languages) are represented using the IEEE 754 standard. Floating-point numbers have two
components: a significand (or mantissa) and an exponent. They are stored in binary
format. However, due to the limitations of binary representation, some decimal numbers
cannot be represented precisely. This can lead to rounding errors. Here's an example:

x = 0.1
y = 0.2
result = x + y
print(result) # Output: 0.30000000000000004
1. In this example, adding 0.1 and 0.2 should ideally result in 0.3. However, due to the
inherent imprecision of floating-point representation, the result is slightly off. The actual
value stored in result is 0.30000000000000004. This is a common issue when working
with floating-point arithmetic.
2. Python Program to Check if a Given Number is a Fibonacci Number: Here's an example
program to check if a given number is a Fibonacci number:

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

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 21
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

while b < n:
a, b = b, a + b
return b == n

# Example usage
num = int(input("Enter a number: "))
if is_fibonacci(num):
print(f"{num} is a Fibonacci number.")
else:
print(f"{num} is not a Fibonacci number.")
In this program, the is_fibonacci function takes a number n as input. It initializes two
variables, a and b, to represent the current and next Fibonacci numbers. It then iterates
using a while loop, updating a and b to the next Fibonacci numbers until b becomes
greater than or equal to n. If b is equal to n, it means n is a Fibonacci number, and the
function returns True. Otherwise, it returns False.
The program prompts the user to enter a number and checks if it is a Fibonacci number
using the is_fibonacci function. It then prints an appropriate message based on the
result.

b. E xplain the purpose and working of loops. Discuss Break and continue with example. Write a CO2
Python program to convert time from 12 hour to 24-hour format.
Loops in programming are used to execute a block of code repeatedly based on a
specified condition. They provide a way to automate repetitive tasks and iterate over a
collection of data. Python provides two types of loops: for loop and while loop.

1. Purpose and Working of Loops:


 for loop: It iterates over a sequence (such as a list, tuple, string, or range) or any
iterable object. The loop variable takes the value of each item in the sequence, and
the block of code inside the loop is executed for each iteration.
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)

apple
banana
orange
while loop: It repeatedly executes a block of code as long as a specified condition is true.
The condition is checked before each iteration, and the loop continues until the condition
becomes false. Example:
count = 0
while count < 5:
print(count)
count += 1

0
1
2

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 22
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

3
4

break and continue statements:


 break: It is used to exit the loop prematurely when a certain condition is met.
When break is encountered, the loop immediately terminates, and the program
continues with the next statement after the loop. Example:
numbers = [1, 2, 3, 4, 5]
for number in numbers:
if number == 3:
break
print(number)

1
2

.
continue: It is used to skip the current iteration of the loop and move to the next
iteration. When continue is encountered, the remaining code in the loop body for the
current iteration is skipped, and the loop proceeds with the next iteration. Example:
numbers = [1, 2, 3, 4, 5]
for number in numbers:
if number == 3:
continue
print(number)

1
2
4
5

Python program to convert time from 12-hour to 24-hour format: Here's an example
program that converts time from the 12-hour format to the 24-hour format:

def convert_to_24_hour_format(time_12_hour):
hours, minutes, period = time_12_hour.split()
hours = int(hours)
minutes = int(minutes)

if period.lower() == "pm":
if hours != 12:
hours += 12
else:
if hours == 12:
hours = 0

return f"{hours:02d}:{minutes:02d}"

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 23
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

# Example usage
time_12_hour = input("Enter time in 12-hour format (e.g., 01:30 PM): ")
time_24_hour = convert_to_24_hour_format(time_12_hour)
print(f"Time in 24-hour format: {time_24_hour}")

In this program, the convert_to_24_hour_format function takes a time string in the 12-
hour format (e.g., "01:30 PM") as input. It splits the time string into hours, minutes, and
the period

5. Attempt any one part of the following: 1 x 10 = 10

a. Explain higher order function with respect to lambda expression. Write a CO2
Python code to Count occurrences of an element in a list
A higher-order function is a function that takes one or more functions as arguments or
returns a function as its result. It allows functions to be treated as first-class objects,
meaning they can be assigned to variables, passed as arguments to other functions, and
returned from functions.

Lambda expressions, also known as anonymous functions, are a concise way to define
small, one-line functions without a formal function definition. They are commonly used in
conjunction with higher-order functions.

Here's an example of a higher-order function using a lambda expression:

def apply_operation(func, x, y):


return func(x, y)

# Example usage
addition = lambda a, b: a + b
result = apply_operation(addition, 5, 3)
print(result) # Output: 8

In this example, the apply_operation function is a higher-order function that takes three
arguments: func, x, and y. func is expected to be a function that takes two arguments
and performs some operation on them. Inside the apply_operation function, func is
called with the arguments x and y and the result is returned.

The lambda expression lambda a, b: a + b defines an anonymous function that takes


two arguments a and b and returns their sum. This lambda function is assigned to the
variable addition. When apply_operation is called with addition as the func argument,
the lambda function is executed with the provided values of x and y, resulting in 8.

Now, let's write a Python code to count the occurrences of an element in a list:

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 24
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

def count_occurrences(lst, element):


count = 0
for item in lst:
if item == element:
count += 1
return count

# Example usage
numbers = [1, 2, 3, 4, 2, 5, 2]
element = 2
occurrences = count_occurrences(numbers, element)
print(f"The element {element} occurs {occurrences} times.") # Output: The element 2 occurs 3
times.

In this code, the count_occurrences function takes two arguments: lst (the list in which
occurrences are to be counted) and element (the element to be counted). It initializes a
count variable to keep track of the occurrences and iterates over each item in the list. If an
item matches the specified element, the count is incremented. Finally, the count is
returned as the result.

The example usage demonstrates how to count the occurrences of the element 2 in the
numbers list, which results in 3.

b. Explain Unpacking Sequences, Mutable Sequences, and List CO2


Comprehension with example.Write a program to sort list of dictionaries
by values in Python – Using lambda function.
Unpacking Sequences: Unpacking sequences in Python allows you to assign the elements
of a sequence (such as a list, tuple, or string) to multiple variables in a single line. It
provides a convenient way to extract individual elements from a sequence. Here's an
example:

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

1. In this example, the elements of the numbers list are unpacked and assigned to the
variables a, b, and c. Each variable receives one element from the list.
2. Mutable Sequences: Mutable sequences in Python are sequences that can be modified
after they are created. The most commonly used mutable sequence in Python is the list.
Mutable sequences allow operations such as adding, removing, or modifying elements.
Here's an example:

fruits = ['apple', 'banana', 'orange']


fruits[1] = 'grape'
print(fruits) # Output: ['apple', 'grape', 'orange']

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 25
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

1. In this example, the second element of the fruits list is modified from 'banana' to
'grape' using the index assignment.
2. List Comprehension: List comprehension is a concise way to create lists based on existing
lists or other iterable objects. It allows you to generate new lists by specifying the desired
elements and any conditions or transformations. Here's an example:

numbers = [1, 2, 3, 4, 5]
squares = [num ** 2 for num in numbers]
print(squares) # Output: [1, 4, 9, 16, 25]

1. In this example, the list comprehension [num ** 2 for num in numbers] generates a
new list squares where each element is the square of the corresponding element in the
numbers list.
2. Sorting a List of Dictionaries by Values using Lambda Function: Here's an example
program that sorts a list of dictionaries by values using a lambda function:

students = [
{"name": "Alice", "age": 20},
{"name": "Bob", "age": 18},
{"name": "Charlie", "age": 22}
]

sorted_students = sorted(students, key=lambda x: x['age'])


print(sorted_students)

[{'name': 'Bob', 'age': 18}, {'name': 'Alice', 'age': 20}, {'name': 'Charlie', 'age': 22}]

In this code, the students list contains dictionaries representing student information. The
sorted function is used to sort the list based on the 'age' key in each dictionary. The key
argument of the sorted function accepts a lambda function lambda x: x['age'] that
returns the value of the 'age' key for each dictionary. The resulting sorted list,
sorted_students, is printed, showing the students sorted in ascending order of their
ages.

6. Attempt any one part of the following: 1 x 10 = 10


a. Discuss File I/O in python. How to perform open, read,write, and close into a file? Write a Python CO2
program to read a file line-by-line store it into a variable

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 26
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

File I/O (Input/Output) in Python refers to the operations performed on files, such as
reading data from a file or writing data to a file. Python provides built-in functions and
methods to perform file operations.

Here's an overview of how to perform file operations in Python:

1. Opening a File: To open a file, you can use the built-in open() function. It takes two
parameters: the file name or file path and the mode in which the file should be opened.
The mode can be 'r' for reading (default), 'w' for writing, 'a' for appending, or 'x' for
creating a new file. Here's an example:

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

1. In this example, the file named "example.txt" is opened in read mode ('r').
2. Reading from a File: Once a file is opened, you can read its contents using various
methods. The most common method is read(), which reads the entire content of the file
as a string. Here's an example:

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


content = file.read()
print(content)

1. This code reads the contents of the "example.txt" file and stores it in the content variable.
The print() statement then outputs the file content.
2. Writing to a File: To write data to a file, you need to open the file in write mode ('w' or
'a' for append). You can use the write() method to write a string to the file. Here's an
example:

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


file.write("Hello, World!")
file.close()

1. In this code, the file named "example.txt" is opened in write mode. The write() method is
used to write the string "Hello, World!" to the file. Finally, the file is closed using the
close() method.
2. Closing a File: It is essential to close the file after you have finished working with it to free
up system resources. You can use the close() method to close the file. Here's an
example:

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


# Perform file operations...
file.close()

1. In this example, the file is closed using the close() method after performing the required

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 27
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

file operations.

Now, let's write a Python program to read a file line-by-line and store it into a variable:

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


lines = file.readlines()
file.close()

print(lines)

In this code, the file named "example.txt" is opened in read mode. The readlines()
method is used to read all lines of the file and store them in a list. The file is then closed
using the close() method. Finally, the content of the file, stored in the lines list, is
printed.
b. Discuss Exceptions and Assertions in python.How to handle Exceptions with Try-Finally? Explain CO2
5 Built-in Exceptions with example.
Exceptions in Python are events that occur during the execution of a program, resulting in
the disruption of the normal flow of instructions. They are used to handle errors,
exceptional situations, and unexpected behavior that may occur during program
execution.

Exception Handling: Exception handling is a mechanism in Python that allows you to


handle and recover from exceptions. It helps you deal with errors and prevents your
program from crashing. The try-except-finally block is used for exception handling in
Python.

Here's the general syntax of a try-except-finally block:

try:
# Code that may raise an exception
# ...
except ExceptionType:
# Code to handle the exception
# ...
finally:
# Code that will be executed regardless of whether an exception occurred or not
# ...

The try block contains the code that may raise an exception. If an exception occurs, it is
caught by the appropriate except block based on the type of the exception. The finally
block is optional and is executed regardless of whether an exception occurred or not. It is
commonly used for cleanup tasks.

Handling Exceptions with Try-Finally: The try-finally block is used when you want to
ensure that certain code is always executed, regardless of whether an exception is raised

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 28
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

or not. It ensures that the cleanup code in the finally block is executed even if an
exception occurs. Here's an example:

file = None
try:
file = open("example.txt", "r")
# Perform file operations...
finally:
if file:
file.close()

In this example, the file is opened in the try block, and file operations are performed. The
finally block is used to close the file using the close() method, even if an exception
occurs during the file operations.

Built-in Exceptions in Python: Python provides a set of built-in exceptions that cover
common error conditions. Here are five examples of built-in exceptions:

1. ValueError: Raised when a function receives an argument of the correct type but an
invalid value.

def convert_to_int(value):
try:
return int(value)
except ValueError:
print("Invalid value")
return None

result = convert_to_int("abc")

TypeError: Raised when an operation or function is performed on an object of


inappropriate type.

numbers = [1, 2, 3]
result = numbers + "abc"

IndexError: Raised when an index is out of range.

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

FileNotFoundError: Raised when a file or directory is requested but cannot be found.

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 29
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

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

ZeroDivisionError: Raised when dividing a number by zero.

result = 10 / 0

7. Attempt any one part of the following: 10*1

a. Discuss and differentiate Iterators & Recursion. Write a program for Recursive Fibonacci series CO2
In each example, the corresponding exception is raised, and if not handled, it will result in
a program termination. By using exception handling with try-except blocks, you can
catch and handle these exceptions gracefully, allowing your program to continue running
or performing appropriate error handling logic.

Iterators and recursion are both concepts used in programming, but they serve different
purposes and have distinct characteristics.

1. Iterators:
 An iterator is an object that enables the traversal of a container or a sequence of
elements.
 It provides a way to access elements of a collection one by one without exposing
the underlying implementation details.
 Iterators are used to iterate over data structures such as lists, tuples, dictionaries,
and sets.
 The iter() function is used to create an iterator from an iterable object, and the
next() function is used to access the next element in the iteration.
 Iterators follow the Iterator Protocol, which requires them to implement the
__iter__() and __next__() methods.
 Example:

numbers = [1, 2, 3, 4, 5]
iterator = iter(numbers)
print(next(iterator)) # Output: 1
print(next(iterator)) # Output: 2

Recursion:
 Recursion is a programming technique where a function calls itself to solve a
problem by breaking it down into smaller, similar subproblems.
 It is based on the principle of solving a complex problem by solving smaller
instances of the same problem.

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 30
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

 Recursive functions have a base case that defines the termination condition and
one or more recursive calls that solve smaller subproblems.
 Recursion is commonly used for solving problems that exhibit a recursive structure,
such as tree traversal, factorial calculation, and Fibonacci series.
 Example: Recursive Fibonacci series

def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)

num_terms = 10
for i in range(num_terms):
print(fibonacci(i))

1.
 In this example, the fibonacci() function uses recursion to calculate the Fibonacci
series. It has a base case where it returns the value of n when n is less than or equal
to 1. For larger values of n, it recursively calls itself to calculate the sum of the
previous two terms in the series.

In summary, iterators are used for traversing and accessing elements in a collection, while
recursion is a technique for solving problems by breaking them down into smaller
subproblems and solving them recursively.

b. Discuss Sorting & Merging. Explain different types of sorting with CO2
example.Write a Python Program for Sieve of Eratosthenes.
Sorting and merging are fundamental operations in computer science and data
processing. Let's discuss them in detail:

1. Sorting: Sorting refers to the process of arranging elements in a particular order. It is


commonly used to organize data in a more structured and meaningful way. There are
various sorting algorithms available, each with its own advantages and characteristics.
Here are a few commonly used sorting algorithms:
 Bubble Sort: Bubble Sort compares adjacent elements and swaps them if they are
in the wrong order. It repeatedly passes through the list until the list is sorted.

def bubble_sort(arr):
n = len(arr)
for i in range(n - 1):
for j in range(n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 31
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

def bubble_sort(arr):
n = len(arr)
for i in range(n - 1):
for j in range(n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]

Selection Sort: Selection Sort repeatedly finds the minimum element from the unsorted
part of the list and swaps it with the element at the beginning of the unsorted part.

def selection_sort(arr):
n = len(arr)
for i in range(n):
min_idx = i
for j in range(i + 1, n):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]

Insertion Sort: Insertion Sort builds the final sorted list one item at a time by inserting
each item into its correct position within the sorted part of the list

def insertion_sort(arr):
n = len(arr)
for i in range(1, n):
key = arr[i]
j=i-1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key

Merging: Merging involves combining two or more sorted sequences into a single sorted
sequence. It is commonly used in merge sort algorithms and when working with data
structures like mergeable heaps. Here's an example of merging two sorted lists:

def merge_sorted_lists(list1, list2):


merged_list = []
i, j = 0, 0
while i < len(list1) and j < len(list2):
if list1[i] <= list2[j]:
merged_list.append(list1[i])
i += 1
else:
merged_list.append(list2[j])

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 32
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

j += 1
# Add remaining elements from list1, if any
merged_list.extend(list1[i:])
# Add remaining elements from list2, if any
merged_list.extend(list2[j:])
return merged_list

list1 = [1, 3, 5, 7]
list2 = [2, 4, 6, 8]
merged = merge_sorted_lists(list1, list2)
print(merged) # Output: [1, 2, 3, 4, 5, 6, 7, 8]

1. In this example, merge_sorted_lists() function takes two sorted lists (list1 and list2)
and merges them into a single sorted list (merged_list) using a two-pointer approach.
The resulting merged list is then printed.

Now, let's write a Python program for the Sieve of Eratosthenes, which is an algorithm for
finding all prime numbers up to a given limit:

def sieve

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 33
Printed Page: 1 of 2
Subject Code: KNC302
0Roll No: 0 0 0 0 0 0 0 0 0 0 0 0 0

BTECH
(SEM III) THEORY EXAMINATION 2021-22
PYTHON PROGRAMMING
Time: 3 Hours Total Marks: 50
Note: Attempt all Sections. If you require any missing data, then choose suitably.

SECTION A
1. Attempt all questions in brief. 2*5 = 10
Qno Questions CO
(a) Explain the Programming Cycle for Python in detail. 1
(b) What will be the output of the following Python code? 2
i=0
while i< 3:
print(i)
i += 1
else:
print(0)
(c) What will be the output of the following Python code? 3
def cube(x):
return x * x * x
x = cube(3)
print x
(d) How do we define an Interface for an ADT? 4
(e) How do you perform a search in Python? 5

SECTION B
2. Attempt any three of the following: 5*3 = 15
Qno Questions CO
(a) What do you mean by Python IDE? Explain in detail. 1
(b) How can you randomize the items of a list in place in Python? 2
(c) Explain Tuples and Unpacking Sequences in Python Data Structure. 3
(d) What are File input and output operations in Python Programming? 4
(e) Solve the Tower of Hanoi problem for n= 3 disk and show all the steps. 5

SECTION C
3. Attempt any one part of the following: 5*1 = 5
Qno Questions CO
(a) Write a program in Python to execute the Selection sort algorithm. 5
(b) Explain why python is considered an interpreted language. 1

4. Attempt any one part of the following: 5 *1 = 5


Qno Questions CO
(a) Write a Python program to construct the following pattern, using a 2
nested for loop.

*
**
***
****
*****
Printed Page: 2 of 2
Subject Code: KNC302
0Roll No: 0 0 0 0 0 0 0 0 0 0 0 0 0

BTECH
(SEM III) THEORY EXAMINATION 2021-22
PYTHON PROGRAMMING
****
***
**
*
(b) Write a program to produce Fibonacci series in Python. 4

5. Attempt any one part of the following: 5*1 = 5


Qno Questions CO
(a) Write a Python program to change a given string to a new string where 3
the first and last chars have been exchanged.
(b) Write a Python program to add an item in a tuple. 3

6. Attempt any one part of the following: 5*1 = 5


Qno Questions CO
(a) How to create and import a module in Python? 4
(b) Explain the algorithm Sieve of Eratosthene used in Python 4
Programming.

7. Attempt any one part of the following: 5*1 = 5


Qno Questions CO
(a) Write a Recursive function in python BinarySearch(Arr,l,R,X) to 5
search the given element X to be searched from the List Arr having R
elements, where l represent slower bound and R represents the upper
bound.
(b) Explain the terms Merge List and Merge Sort in Python Programming. 5
AKTU
Python AKTU Question Paper 2022-23
Solution
SUBJECT CODE: KNC-302
B.TECH.(CSE /CS IT/ CS AI ML) SEMESTER -IV

Academic Session: 2022-23, Even Semester


Faculty
Dr. Aadarsh Malviya
(Associate Professor Department of CSE)

Dronacharya Group of Institutions


Plot No. 27, Knowledge Park-3, Greater Noida, Uttar Pradesh 201308

Affiliated to

Dr. A P J Abdul Kalam Technical University


Lucknow, Uttar Pradesh 226031
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2021-22 solution

.SECTION A
1. Attempt all questions in brief. 2*5 = 10

a. Explain the Programming Cycle for Python in detail. CO1


Soln. The programming cycle, also known as the software development cycle or the software
development process, refers to the set of activities involved in creating, testing, and
maintaining a software application. It encompasses the entire life cycle of software
development, from the initial planning and analysis stages to deployment and
maintenance. Here's a detailed explanation of the programming cycle for Python:

1. Requirements Gathering and Analysis:


 In this stage, the requirements for the software are gathered by interacting with
stakeholders such as clients or end-users.
 The requirements are analyzed to understand the scope of the project, the problem
it aims to solve, and the desired functionalities of the software.
 The analysis phase helps identify the key features and constraints of the software.
2. Design:
 Once the requirements are gathered, the software design phase begins.
 The design process involves creating a high-level architectural design and breaking
it down into smaller modules or components.
 The design may include user interface design, database schema design, and
algorithm design.
 The design phase helps create a blueprint for the software's structure and
functionality.
3. Implementation:
 The implementation phase is where the actual coding takes place.
 Using Python, programmers write code based on the design specifications.
 The code is typically divided into functions, classes, and modules to enhance
modularity and maintainability.
 Best practices and coding standards are followed to ensure readability and
maintainability of the code.
4. Testing:
 In this phase, the developed software is tested to identify and fix any defects or
bugs.
 Various testing techniques, such as unit testing, integration testing, and system
testing, are employed to ensure the software behaves as expected.
 Python provides testing frameworks like pytest and unittest that facilitate the
creation and execution of test cases.
5. Deployment:
 Once the software passes the testing phase, it is ready for deployment.
 Deployment involves making the software available to end-users or deploying it to
production environments.
 Python offers several deployment options, including standalone executables, web

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 1
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2021-22 solution

applications using frameworks like Django or Flask, or packaging the software as


libraries or modules.
6. Maintenance and Updates:
 After deployment, the software enters the maintenance phase.
 During this phase, any issues reported by users are addressed, and updates or
enhancements are implemented as required.
 Maintenance may include bug fixes, performance optimizations, security updates, or
adding new features.
 The maintenance phase continues throughout the software's lifespan to ensure its
reliability and effectiveness.

It's important to note that the programming cycle is not strictly linear. It often involves
iterations and feedback loops, where developers revisit earlier stages to refine and improve
the software based on user feedback or changing requirements. This iterative nature allows
for flexibility and continuous improvement in the development process.

b. What will be the output of the following Python code? i = 0 while i< 3: print(i) i += 1 else: print(0)
Soln. 0
1
2
0
c. W hat will be the output of the following Python code? def cube(x): return x * x * x x = cube(3)
print x
Soln. 27
d. How do we define an Interface for an ADT?
Soln. In Python, there is no explicit language construct for defining interfaces like in some other
programming languages. However, you can define an interface for an Abstract Data Type
(ADT) in Python by using a combination of conventions and techniques. Here are some
common approaches:

1. Documentation: Clearly document the methods and their expected behavior that should be
implemented by classes adhering to the interface. Use docstrings to provide detailed
explanations of the purpose, parameters, and return values of each method.
2. Abstract Base Classes (ABCs): Python's abc module provides a mechanism for defining
abstract base classes, which can serve as interfaces. By inheriting from the ABC class and
using the @abstractmethod decorator, you can define abstract methods that must be
implemented by concrete classes.
from abc import ABC, abstractmethod

class MyInterface(ABC):
@abstractmethod
def method1(self):
pass

@abstractmethod

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 2
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2021-22 solution

def method2(self, param):


pass
1. Classes that implement MyInterface will need to provide concrete implementations for
method1 and method2.
2. Duck Typing: In Python, the focus is on "duck typing," which means that if an object
behaves like a particular interface (even without explicitly declaring it), it can be considered
as implementing that interface. Instead of checking whether an object inherits from a
specific class or implements a particular interface, you can directly use the object and rely
on the presence of specific methods or attributes.
class MyInterface:
def method1(self):
raise NotImplementedError()

def method2(self, param):


raise NotImplementedError()
1. This approach relies on the developer's responsibility to ensure that any class claiming to
implement MyInterface must provide implementations for method1 and method2.
However, there is no strict enforcement by the language.

Remember that in Python, the focus is on the behavior of objects rather than their types.
So, even without formal interfaces, you can design your code in such a way that classes
adhere to a specific interface contract through documentation, naming conventions,
and/or the use of abstract base classes.

e. How do you perform a search in Python?

Soln. In Python, there are several ways to perform a search operation depending on the data
structure and the type of search you want to perform. Here are some common methods for
performing searches in Python:

1. List Search:
 If you have a list and want to find the index of a specific element, you can use the
index() method.

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

index = my_list.index(3)

print(index) # Output: 2

If you want to check if an element exists in a list, you can use the in operator.

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

exists = 3 in my_list

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 3
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2021-22 solution

print(exists) # Output: True

String Search:
 To search for a substring within a string, you can use the find() method.

my_string = "Hello, World!"

index = my_string.find("World")

print(index) # Output: 7

To check if a substring exists in a string, you can use the in operator.

my_string = "Hello, World!"

exists = "World" in my_string

print(exists) # Output: True

Dictionary Search:
 If you have a dictionary and want to check if a key exists, you can use the in
operator

my_dict = {"name": "John", "age": 30}

exists = "name" in my_dict

print(exists) # Output: True

To retrieve the value associated with a key in a dictionary, you can use square brackets.

my_dict = {"name": "John", "age": 30}

value = my_dict["name"]

print(value) # Output: "John"

1. Customized Search:
 If you need to perform a more complex search, you can use iterative algorithms like
linear search or binary search.
 Linear Search: Iterate through a list or an iterable and check each element until a
match is found.
 Binary Search: Requires a sorted sequence and repeatedly divides the search space
in half until the target is found or determined to be absent.
It's important to choose the appropriate search algorithm based on the characteristics of

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 4
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2021-22 solution

your data and the efficiency requirements of your program.

These are just a few examples of search operations in Python. The method you choose will
depend on the data structure and the specific requirements of your search task.

Section B
2. Attempt any three of the following: 5*3 = 15
a. What do you mean by Python IDE? Explain in detail CO1
Soln. An Integrated Development Environment (IDE) is a software application that provides
comprehensive tools and features to streamline the process of writing, testing, and
debugging code. It offers a dedicated environment for developing software applications
and makes the development process more efficient and productive. In the context of
Python, a Python IDE refers to an IDE specifically designed for Python programming. Here's
a detailed explanation of Python IDEs:

Features of Python IDEs:

1. Code Editor: Python IDEs typically provide a code editor with syntax highlighting, code
completion, and intelligent code suggestions. These features help developers write code
faster and with fewer errors.
2. Debugging Support: IDEs offer built-in debuggers that allow developers to set breakpoints,
step through the code, inspect variables, and analyze the program's execution flow. This
helps in identifying and resolving bugs and issues in the code.
3. Integrated Terminal: Python IDEs often include an integrated terminal or command prompt
within the IDE itself. This allows developers to execute Python code, run scripts, and
interact with the Python interpreter without leaving the IDE.
4. Project Management: IDEs provide project management capabilities, allowing developers
to organize their code into projects, manage dependencies, and navigate between project
files easily. They often have features like project templates, version control integration, and
project-specific configurations.
5. Testing Framework Integration: Python IDEs often support integration with testing
frameworks like pytest or unittest. This integration allows developers to easily create, run,
and analyze unit tests within the IDE.
6. Code Refactoring: IDEs provide tools for code refactoring, which enable developers to
efficiently restructure and improve their code without manually modifying each occurrence.
Examples of code refactoring include renaming variables, extracting methods, and
optimizing imports.
7. Documentation Integration: Many Python IDEs offer integration with documentation tools,
allowing developers to easily access Python's official documentation or other relevant
documentation sources within the IDE. This helps in quickly referring to function signatures,
library documentation, and usage examples.

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 5
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2021-22 solution

8. Collaboration and Teamwork: Some Python IDEs support collaboration features, allowing
multiple developers to work on the same codebase simultaneously. These features can
include code sharing, real-time editing, and collaborative debugging.

Popular Python IDEs:

1. PyCharm: Developed by JetBrains, PyCharm is a widely used cross-platform Python IDE that
offers a comprehensive set of features for Python development.
2. Visual Studio Code (VS Code): Although not a dedicated Python IDE, VS Code provides
excellent Python support through extensions. It offers a lightweight and customizable
environment with powerful features for Python development.
3. Jupyter Notebook: Jupyter Notebook is an open-source web-based environment that
allows interactive Python coding, data analysis, and visualization. It supports Markdown,
code execution, and rich media integration.
4. Spyder: Designed specifically for scientific computing, Spyder is an open-source Python IDE
that provides a MATLAB-like environment with advanced features for data exploration,
analysis, and visualization.
5. IDLE: IDLE is a basic Python IDE that comes bundled with the standard Python distribution.
It offers a simple integrated environment suitable for beginners or quick scripting tasks.

These are just a few examples of Python IDEs, and there are many more available, each
with its own set of features and advantages. The choice of a Python IDE depends on
individual preferences, the complexity of the project, and specific requirements.

b. How can you randomize the items of a list in place in Python? CO2
Soln. To randomize or shuffle the items of a list in place (i.e., modifying the original list), you can
make use of the random module in Python. The random module provides functions for
generating random numbers and performing random operations. Specifically, the
shuffle() function from the random module can be used to shuffle the items of a list.
Here's an example:

import random

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

random.shuffle(my_list)

print(my_list)

The output will be a randomized order of the elements in the list, such as [3, 2, 1, 5,
4] or [4, 5, 1, 2, 3]. The original list is modified directly.

The random.shuffle() function shuffles the items of the list in a random order using the
Fisher-Yates algorithm. It rearranges the elements by swapping them repeatedly, resulting

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 6
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2021-22 solution

in a random permutation.

Note that the random.shuffle() function modifies the list in place, and it doesn't return
any value. If you want to create a new randomized list without modifying the original list,
you can use the sample() function from the random module:

import random

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

randomized_list = random.sample(my_list, len(my_list))

print(randomized_list)
In this case, the random.sample() function returns a new list that contains a randomized
sample of the elements from the original list. The original list remains unmodified.
c. What are File input and output operations in Python Programming? CO4
Soln. File input and output operations, commonly referred to as file I/O operations, involve
reading data from files (input) and writing data to files (output) in Python programming.
These operations allow you to interact with files on the disk, enabling data persistence and
communication with external resources. Here's an overview of file input and output
operations in Python:

File Input Operations: File input operations involve reading data from files. Python provides
various methods and functions to read file contents:

1. Opening a File: To open a file for reading, you can use the built-in open() function. It takes
the file path and an optional mode argument (default is 'r' for reading) and returns a file
object.

file = open('file.txt', 'r')


Reading Data from a File: Once a file is open, you can read its contents using methods
provided by the file object. Some common methods are:
 read(): Reads the entire contents of the file as a string.
 readline(): Reads a single line from the file.
 readlines(): Reads all lines from the file and returns them as a list.
content = file.read() # Read the entire file
line = file.readline() # Read a single line
lines = file.readlines() # Read all lines as a list

Closing a File: After reading the file, it's essential to close it using the close() method to
release system resources associated with the file.
file.close()

File Output Operations: File output operations involve writing data to files. Python provides

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 7
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2021-22 solution

methods and functions to write data to files:

1. Opening a File: To open a file for writing, you can use the open() function with the mode
argument set to 'w' for writing.

file = open('file.txt', 'w')


Writing Data to a File: Once a file is open for writing, you can use the write() method of
the file object to write data. You can write strings or use the str() function to convert
non-string data to strings.

file.write('Hello, World!\n') # Write a string


file.write(str(123)) # Write a number (converted to string)

Closing a File: After writing to the file, it's important to close it using the close() method
to ensure that the data is properly written and the system resources are released.
file.close()

It's worth noting that using the with statement is a recommended approach for file I/O
operations in Python. It automatically takes care of opening and closing the file, ensuring
proper resource management and exception handling.
with open('file.txt', 'r') as file:
content = file.read()
# Perform operations with the file content

# File is automatically closed outside the `with` block

File I/O operations are fundamental for working with external data, such as reading
configuration files, processing data files, and saving program output to files. Understanding
and utilizing file input and output operations in Python enables effective interaction with
the file system and facilitates data persistence and communication with other programs or
users.
d. Explain Tuples and Unpacking Sequences in Python Data Structure. CO3
Soln. Tuples: A tuple is an immutable, ordered collection of elements in Python. It is similar to a
list, but unlike lists, tuples cannot be modified once created. Tuples are defined using
parentheses () or the tuple() constructor. Here are some key characteristics of tuples:

1. Immutable: Once a tuple is created, its elements cannot be changed. This means you
cannot add, remove, or modify individual elements of a tuple.
2. Ordered: Tuples preserve the order of their elements, meaning the elements have a specific
position or index within the tuple.
3. Heterogeneous: Tuples can contain elements of different data types. For example, a tuple
can have a combination of integers, strings, floats, and other objects.
4. Indexing and Slicing: You can access individual elements of a tuple using indexing or slicing
operations, similar to lists. Indexing starts from 0.

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 8
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2021-22 solution

my_tuple = (10, 'Hello', 3.14)


print(my_tuple[0]) # Output: 10
print(my_tuple[1]) # Output: 'Hello'
print(my_tuple[2]) # Output: 3.14

# Slicing
print(my_tuple[1:]) # Output: ('Hello', 3.14)

Unpacking Sequences: Unpacking sequences is a convenient feature in Python that allows


you to assign the elements of a sequence, such as a tuple or a list, to multiple variables in a
single line. It provides a concise way to assign values from a sequence to individual
variables. Here's an example:
my_tuple = ('John', 25, 'Developer')
name, age, profession = my_tuple

print(name) # Output: 'John'


print(age) # Output: 25
print(profession) # Output: 'Developer'

In this example, the elements of the my_tuple tuple are assigned to the variables name,
age, and profession in a single line. The number of variables on the left side of the
assignment must match the number of elements in the tuple.

Unpacking can be used with any iterable, not just tuples. It allows you to extract elements
from sequences such as lists, sets, and even strings.

my_list = [1, 2, 3]
a, b, c = my_list

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

my_set = {'apple', 'banana', 'cherry'}


x, y, z = my_set

print(x) # Output: 'banana'


print(y) # Output: 'apple'
print(z) # Output: 'cherry'

my_string = 'Hello'
a, b, c, d, e = my_string

print(a) # Output: 'H'


print(b) # Output: 'e'
print(c) # Output: 'l'
print(d) # Output: 'l'

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 9
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2021-22 solution

print(e) # Output: 'o'


Unpacking sequences is a powerful feature in Python that simplifies the assignment of
values from a sequence to individual variables, making the code more concise and
readable.

e. Solve the Tower of Hanoi problem for n= 3 disk and show all the steps. CO5
Soln. Sure! The Tower of Hanoi problem is a classic mathematical puzzle that involves moving a
stack of disks from one peg to another peg, using a temporary peg, while following specific
rules:

1. Only one disk can be moved at a time.


2. Each move consists of taking the upper disk from one of the stacks and placing it on top of
another stack or an empty peg.
3. No disk may be placed on top of a smaller disk.

For n = 3 disks, here are the step-by-step instructions to solve the Tower of Hanoi problem:

Step 1: Move disk 1 from the source peg (S) to the destination peg (D).

Step 2: Move disk 2 from the source peg (S) to the auxiliary peg (A).

Step 3: Move disk 1 from the destination peg (D) to the auxiliary peg (A).

Step 4: Move disk 3 from the source peg (S) to the destination peg (D).

Step 5: Move disk 1 from the auxiliary peg (A) to the source peg (S).

Step 6: Move disk 2 from the auxiliary peg (A) to the destination peg (D).

Step 7: Move disk 1 from the source peg (S) to the destination peg (D).

Here's a graphical representation of the steps:

Step 1:
S A D
--- --- ---
|1| | | | |
|2| | | | |
|3| | | | |

Step 2:
S A D
--- --- ---
| | |2| | |

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 10
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2021-22 solution

| | |1| | |
|3| | | | |

Step 3:
S A D
--- --- ---
| | | | |1|
| | | | |2|
|3| | | | |

Step 4:
S A D
--- --- ---
| | | | |1|
| | | | |2|
| | | | |3|

Step 5:
S A D
--- --- ---
| | |1| |2|
| | | | |3|
| | | | | |

Step 6:
S A D
--- --- ---
| | | | |2|
| | |1| |3|
| | | | | |

Step 7:
S A D
--- --- ---
| | | | | |
| | | | |1|
| | | | |2|
| | | | |3|

In the above representation, S represents the source peg, A represents the auxiliary peg,
and D represents the destination peg. Each disk is represented by its size (1, 2, or 3). The
goal is to move all the disks from the source peg to the destination peg using the auxiliary

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 11
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2021-22 solution

peg.

By following the steps above, you can successfully solve the Tower of Hanoi problem for n
=

Section C
3. Attempt any one part of the following: 5*1 = 5

a. Write a program in Python to execute the Selection sort algorithm. CO5


def selection_sort(arr):
n = len(arr)

# Traverse through all array elements


for i in range(n):
# Find the minimum element in the remaining unsorted part
min_index = i
for j in range(i + 1, n):
if arr[j] < arr[min_index]:
min_index = j

# Swap the found minimum element with the first element


arr[i], arr[min_index] = arr[min_index], arr[i]

# Example usage
numbers = [64, 25, 12, 22, 11]
selection_sort(numbers)
print("Sorted array:", numbers)
b. Explain why python is considered an interpreted language. CO1
Python is considered an interpreted language because it utilizes an interpreter to execute its
code directly, without the need for a separate compilation step. Here are a few key reasons
why Python is classified as an interpreted language:

1. Interpreter Execution: Python code is executed by an interpreter, which reads and processes
the code line by line. The interpreter translates each line of code into machine-readable
instructions and executes them immediately. This differs from compiled languages where the
source code is first converted into machine code through a separate compilation step before
execution.
2. Dynamic Typing: Python is dynamically typed, meaning variable types are determined and
checked at runtime. This dynamic type checking is facilitated by the interpreter, which allows
for flexibility but also introduces a performance trade-off compared to statically typed
compiled languages.
3. Interactive Shell: Python provides an interactive shell, commonly known as the Python REPL
(Read-Eval-Print Loop), where users can directly type and execute Python code statements.
The interpreter processes each line of code as it is entered, providing immediate feedback
and results. This interactive nature of Python further highlights its interpreted nature.

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 12
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2021-22 solution

4. Ease of Development and Debugging: Interpreted languages like Python offer advantages in
terms of development and debugging. Since there is no need for a separate compilation
step, Python code can be executed and tested more quickly, allowing for a rapid
development cycle. Additionally, Python provides tools and features that facilitate
debugging, such as interactive debugging with breakpoints, which are made possible by the
interpreter's ability to execute code step-by-step.
5. Portability and Cross-Platform Support: The interpreted nature of Python contributes to its
portability and cross-platform compatibility. Python code can run on any platform or
operating system that has a compatible Python interpreter installed, without the need for
recompilation. This allows for code to be written and executed on different systems without
modification, enhancing its versatility.

It's important to note that although Python is primarily interpreted, there are options
available to optimize its performance. Techniques like just-in-time (JIT) compilation and
ahead-of-time (AOT) compilation can be employed to translate Python code into machine
code to improve execution speed. However, the core concept of Python being an interpreted
language remains intact.

4. Attempt any one part of the following: 5 *1 = 5

a. Write a Python program to construct the following pattern, using a nested for loop. CO2
*
**
***
****
*****
* ***
***
**
*
for i in range(1, 6): # Outer loop for the number of rows
for j in range(i): # Inner loop for printing the asterisks
print("*", end=" ")
print() # Print a new line after each row

for i in range(4, 0, -1): # Outer loop for the remaining rows


for j in range(i): # Inner loop for printing the asterisks
print("*", end=" ")
print() # Print a new line after each row
b. Write a program to produce Fibonacci series in Python. CO2
def fibonacci(n):

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 13
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2021-22 solution

fib_series = [] # List to store the Fibonacci series

# Check if the input is valid


if n <= 0:
print("Invalid input! Please enter a positive integer.")
return fib_series

# First two numbers in the Fibonacci series


fib1, fib2 = 0, 1
fib_series.append(fib1) # Add the first number to the series

# Generate the Fibonacci series


for _ in range(1, n):
fib_series.append(fib2)
fib1, fib2 = fib2, fib1 + fib2

return fib_series

# Example usage
num_terms = 10
fibonacci_series = fibonacci(num_terms)
print("Fibonacci series up to", num_terms, "terms:", fibonacci_series)

5. Attempt any one part of the following: 5*1 = 5

a. Write a Python program to change a given string to a new string where the first and last chars have CO2
been exchanged.
def exchange_first_last(string):
# Check if the string has at least two characters
if len(string) < 2:
print("Invalid input! Please provide a string with at least two characters.")
return string

# Extract the first and last characters


first_char = string[0]
last_char = string[-1]

# Replace the first and last characters


new_string = last_char + string[1:-1] + first_char

return new_string

# Example usage
input_string = "Hello"
new_string = exchange_first_last(input_string)
print("Original string:", input_string)
print("Modified string:", new_string)

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 14
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2021-22 solution

b. W rite a Python program to add an item in a tuple. CO2


def add_to_tuple(tup, item):
# Convert the tuple to a list
list_tup = list(tup)

# Append the new item to the list


list_tup.append(item)

# Convert the list back to a tuple


new_tup = tuple(list_tup)

return new_tup

# Example usage
original_tuple = (1, 2, 3, 4)
new_item = 5
modified_tuple = add_to_tuple(original_tuple, new_item)
print("Original tuple:", original_tuple)
print("Modified tuple:", modified_tuple)

6. Attempt any one part of the following: 5*1 = 5

a. How to create and import a module in Python? CO2


To create and import a module in Python, you can follow these steps:

1. Create a Python File: Create a new Python file with a .py extension. This file will serve as
your module and contain the code you want to encapsulate.
2. Define Functions or Classes: Inside the module file, define the functions, classes, or
variables that you want to make accessible to other Python scripts. For example, you can
define a function called my_function:
def my_function():
print("Hello from my module!")

1. Save the Module: Save the module file with an appropriate name. For instance, if your
module file is named mymodule.py, make sure to save it as such.
2. Import the Module: In your Python script where you want to use the module, you can
import it using the import statement followed by the module name. For example:

import mymodule
This will import the entire module, and you can access its contents using the module
name as a prefix. For instance, you can call the my_function defined in the module like
this:
mymodule.my_function()
Output:
Hello from my module!

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 15
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2021-22 solution

Alternatively, you can import specific functions or classes from the module using the from
statement. For example:
from mymodule import my_function
This allows you to directly use the imported function without referencing the module
name:
my_function()
Hello from my module!

By following these steps, you can create a module in Python and import it into other
scripts for reusability and organization of code. Remember to ensure that the module file
is located in the same directory as the script that is importing it, or in a directory listed in
the Python module search path.
b. E xplain the algorithm Sieve of Eratosthene used in Python Programming. CO2
The Sieve of Eratosthenes is an algorithm used to find all prime numbers up to a given
limit. It efficiently eliminates composite numbers by iteratively marking their multiples.
Here's how the algorithm works:

1. Create a list of Boolean values: Initialize a list is_prime of size n+1 (where n is the limit)
and set all values to True. This list will serve as a sieve to track the primality of numbers.
2. Mark multiples as non-prime: Start with the first prime number, 2. Mark all its multiples as
non-prime by setting their corresponding indices in the is_prime list to False. The
multiples of 2 are 4, 6, 8, 10, and so on.
3. Find the next prime number: Scan through the is_prime list to find the next number
greater than the current prime number that is marked as prime (i.e., its value in the
is_prime list is True). This number will be the next prime number.
4. Mark its multiples as non-prime: Repeat the process of marking multiples as non-prime
for the newly found prime number. Mark all the multiples of this prime number as non-
prime by setting their corresponding indices in the is_prime list to False.
5. Repeat steps 3 and 4: Continue steps 3 and 4 until there are no more numbers to consider
(i.e., all numbers up to the limit have been processed).
6. Retrieve the prime numbers: The prime numbers are the indices in the is_prime list that
are still marked as True. Collect these indices and store them as the prime numbers.

Here's an example Python program that implements the Sieve of Eratosthenes algorithm:

def sieve_of_eratosthenes(n):
is_prime = [True] * (n + 1) # Initialize sieve list
primes = [] # List to store prime numbers

# 0 and 1 are not prime numbers


is_prime[0] = is_prime[1] = False

p = 2 # Start with the first prime number

while p * p <= n:

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 16
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2021-22 solution

if is_prime[p]:
# Mark all multiples of p as non-prime
for i in range(p * p, n + 1, p):
is_prime[i] = False
p += 1

# Collect prime numbers


for num in range(2, n + 1):
if is_prime[num]:
primes.append(num)

return primes

# Example usage
limit = 30
prime_numbers = sieve_of_eratosthenes(limit)
print("Prime numbers up to", limit, ":", prime_numbers)

Explanation:

 The sieve_of_eratosthenes function takes an integer n as input and returns a list


of prime numbers up to n.
 The is_prime list is initialized with True values for each index, indicating that all
numbers are initially assumed to be prime.
 The indices 0 and 1 in the is_prime list are set to False since they are not prime
numbers.
 The algorithm iteratively scans the is_prime list, starting with the first prime
number (p = 2), and marks all multiples of each prime number as non-prime.

7. Attempt any one part of the following: 5*1

a. Write a Recursive function in python BinarySearch(Arr,l,R,X) to search the given element X to be CO2
searched from the List Arr having R elements, where l represent slower bound and R represents the
upper bound.
def binary_search(arr, l, r, x):
# Check if the search range is valid
if r >= l:
mid = l + (r - l) // 2

# If the element is present at the middle


if arr[mid] == x:
return mid

# If the element is smaller than the middle element, search the left half
elif arr[mid] > x:
return binary_search(arr, l, mid - 1, x)

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 17
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2021-22 solution

# If the element is larger than the middle element, search the right half
else:
return binary_search(arr, mid + 1, r, x)

# If the element is not present in the list


else:
return -1

# Example usage
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
x=5

result = binary_search(arr, 0, len(arr) - 1, x)

if result != -1:
print("Element", x, "found at index", result)
else:
print("Element", x, "not found in the list")
b. E xplain the terms Merge List and Merge Sort in Python Programming. CO2
In Python programming, the terms "Merge List" and "Merge Sort" are related to a sorting
algorithm called Merge Sort. Let's explain these terms in detail:

Merge List: A "Merge List" refers to the process of merging two sorted lists into a single
sorted list. In the context of Merge Sort, when dividing a list into smaller sublists, the
individual sublists are sorted independently. Then, during the merge step, these sorted
sublists are combined (or merged) together to form a larger sorted list.

Merge Sort: Merge Sort is a popular and efficient sorting algorithm that follows the
divide-and-conquer approach. It works by recursively dividing the list into smaller sublists,
sorting them, and then merging them back together to produce a sorted list. The steps of
the Merge Sort algorithm are as follows:

1. Divide: The list is divided into two halves until the sublists contain only one element or are
empty. This process is performed recursively.
2. Conquer: The individual sublists are sorted using the same Merge Sort algorithm. This
involves dividing each sublist further into smaller sublists and sorting them.
3. Merge: The sorted sublists are merged together to create a single sorted list. The merge
operation compares elements from the sublists and places them in the correct order.
4. Repeat: Steps 1 to 3 are repeated until the entire list is sorted.

The key step in Merge Sort is the merging of two sorted sublists into a single sorted list.
This is achieved by comparing the elements from each sublist and selecting the smallest
element to place in the merged list. The process continues until all elements from both

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 18
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2021-22 solution

sublists are merged.

Merge Sort has a time complexity of O(n log n), making it an efficient sorting algorithm
for large datasets. It is stable (preserves the relative order of equal elements) and can
handle various data types.

Here's an example implementation of the Merge Sort algorithm in Python:

def merge_sort(arr):
if len(arr) <= 1:
return arr

# Divide the list into two halves


mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]

# Recursively sort the two halves


left_half = merge_sort(left_half)
right_half = merge_sort(right_half)

# Merge the sorted halves


return merge(left_half, right_half)

def merge(left, right):


merged = []
i=j=0

# Compare elements from the left and right halves and merge them
while i < len(left) and j < len(right):
if left[i] <= right[j]:
merged.append(left[i])
i += 1
else:
merged.append(right[j])
j += 1

# Append the remaining elements from either the left or right sublist
while i < len(left):
merged.append(left[i])
i += 1
while j < len(right):
merged.append(right[j])
j += 1

return merged

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 19
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2021-22 solution

# Example usage
arr = [5, 3, 8, 2, 1, 9, 4, 7, 6]
sorted_arr = merge_sort(arr)
print("Sorted list:", sorted_arr)

Sorted list: [1, 2, 3, 4, 5, 6, 7, 8, 9]


In this example, the merge_sort function recursively divides the input list arr into smaller
halves and calls itself on each half. The base case is reached when the sublist contains only
one element or is empty. The merge function merges the sorted sub

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 20
Printed Page: 1 of 1
Subject Code: KNC402
0Roll No: 0 0 0 0 0 0 0 0 0 0 0 0 0

BTECH
(SEM IV) THEORY EXAMINATION 2021-22
PYTHON PROGRAMMING
Time: 3 Hours Total Marks: 50
Note: Attempt all Sections. If you require any missing data, then choose suitably.

SECTION A
1. Attempt all questions in brief. 2.5*4 = 10
Qno Questions CO
(a) Discuss why Python is called as dynamic and strongly typed language? 1
(b) How pass statement is different from a comment? 2
(c) Write a for loop that prints numbers from 0 to 57, using range function. 2
(d) What is the difference between Python Arrays and Lists? 3
SECTION B
2. Attempt any two of the following: 4*2 = 8
Qno Questions CO
(a) Write a python function named ComputeAverage to find average of a list of 3
numbers. It should handle the exception if the list is empty and return 0 in
that case.
(b) Implement the binary search technique. 5
(c) Explain the use of break and continue with a suitable example. 2

SECTION C
3. Attempt any two part of the following: 4*2 = 8
Qno Questions CO
(a) What do you mean by operator precedence and associativity. Explain. 1
(b) Write short notes on 1
i. The programming cycle for python
ii. Type conversion in python
(c) Write Python program to swap two numbers without 1 using
Intermediate/Temporary variables. Prompt the user for input.
4. Attempt any two part of the following: 4*2 = 8
Qno Questions CO
(a) Write a program to check an input number is prime or not. 2
(b) Write a program that accepts a sentence and calculate the number of digits, 2
uppercase and lowercase letters.
(c) Write a program to check an input year is leap year or not. 2
5. Attempt any two part of the following: 4*2 = 8
Qno Questions CO
(a) There is a file named Input.Txt. Enter some positive numbers into the file 4
named Input.Txt. Read the contents of the file and if it is an odd number
write it to ODD.TXT and if the number is even, write it to EVEN.TXT
(b) Discuss Exceptions and Assertions in Python. Explain with a 4suitable
example. Explain any two built-in exceptions.
(c) What is the significance of module in Python? What are the methods of 4
importing a module? Explain with suitable example
6. Attempt any two part of the following: 4*2 = 8
Qno Questions CO
(a) What do you mean by recursion? Write a recursive function to compute the 5
factorial of an input number N.
(b) Implement selection sort using Python 5
(c) What are different types of inheritance supported by Python? Explain. 4
AKTU
Python AKTU
THEORY EXAMINATION 2021-22

Solution
SUBJECT CODE: KNC-402
B.TECH.(CSE /CS IT/ CS AI ML) SEMESTER -IV

Academic Session: 2022-23, Even Semester


Faculty
Dr. Aadarsh Malviya
(Associate Professor Department of CSE)

Dronacharya Group of Institutions


Plot No. 27, Knowledge Park-3, Greater Noida, Uttar Pradesh 201308

Affiliated to

Dr. A P J Abdul Kalam Technical University


Lucknow, Uttar Pradesh 226031
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

.SECTION A
1. Attempt all questions in brief. 2.5*4 = 10

a. Discuss why Python is called as dynamic and strongly typed language? CO1
Soln. Python is called a dynamic and strongly typed language because of the way it handles
variable types and allows for flexible programming.

1. Dynamic Typing: In Python, you don't need to declare the type of a variable explicitly. The
type of a variable is determined dynamically based on the value assigned to it. You can
assign a value of any type to a variable, and the type of the variable can change during
runtime. This flexibility is a characteristic of dynamic typing. For example:

x=5
print(type(x)) # Output: <class 'int'>

x = "Hello"
print(type(x)) # Output: <class 'str'>

1. In the above code, the variable x is initially assigned an integer value and its type is int.
Later, it is assigned a string value, and its type becomes str. Python allows this flexibility,
as variables are associated with objects, and their types can be determined at runtime.
2. Strong Typing: Python is also considered a strongly typed language because it enforces
strict type checking and does not perform implicit type conversions in most cases.
Operations between incompatible types will raise an error. For example:

x=5
y = "Hello"
z = x + y # Raises TypeError: unsupported operand type(s) for +: 'int' and 'str'

1. In this code, an attempt is made to add an integer (x) and a string (y). Since the types are
incompatible for addition, Python raises a TypeError.
Strong typing ensures that variables and operations are performed with their intended
types. It promotes code clarity and helps prevent subtle errors that can occur due to
implicit type conversions.

The combination of dynamic typing and strong typing in Python allows for flexibility in
variable assignment and type changes during runtime while still maintaining strict type
checks. This flexibility and type enforcement contribute to Python's ease of use and
readability.

b. How pass statement is different from a comment?


Soln. The pass statement and comments serve different purposes in Python.

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 1
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

1. pass statement:
 The pass statement is a placeholder statement that does nothing. It is used when a
statement is syntactically required but you don't want to perform any action or write
any code.
 It is often used as a placeholder for unfinished code or code that will be
implemented later.
 The pass statement is useful in situations where Python syntax requires a statement,
such as in an empty function or class definition.
 Example:

def my_function():

pass # Placeholder for the function body

class MyClass:

pass # Placeholder for the class body

1. In the above examples, the pass statement acts as a placeholder inside the function and
class definitions, indicating that the body of the function or class is intentionally left empty.
2. Comments:
 Comments in Python are used to provide explanations, descriptions, or
documentation within the code. They are ignored by the Python interpreter and
have no impact on the execution of the program.
 Comments are meant for human readers to understand the code better, including
its purpose, functionality, or any other relevant information.
 Comments start with the # symbol and continue until the end of the line.
 Example:

# This is a single-line comment

"""

This is a multi-line comment

spanning multiple lines.

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 2
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

"""

# Code with comments

x = 5 # Assign 5 to variable x

1. In the code snippet above, comments are used to provide additional information or
explanations. They are ignored by the interpreter and have no effect on the execution of
the code.

In summary, the pass statement is used as a placeholder for syntactical requirements,


indicating that no action is needed, while comments are used to provide explanations or
documentation within the code, for the benefit of human readers.

c. Write a for loop that prints numbers from 0 to 57, using range function.
Soln. for loop that prints numbers from 0 to 57 using the range() function:

for num in range(58):


print(num)
In this code, the range(58) function generates a sequence of numbers from 0 to 57 (58 is
excluded). The for loop iterates over each number in the sequence, and the print()
function is used to display each number
d. What is the difference between Python Arrays and Lists?
Soln. In Python, arrays and lists are both used to store and manipulate collections of elements.
However, there are some differences between them in terms of functionality and usage.
Here are the main differences:

1. Data Type:
 Arrays: Arrays in Python are provided by the array module. They are homogeneous,
meaning all elements must have the same data type. Arrays are implemented at a
lower level and are more efficient in terms of memory usage and performance.
 Lists: Lists in Python are a built-in data type and can store elements of different data
types. They are more flexible and versatile compared to arrays.
2. Mutable vs. Immutable:
 Arrays: Arrays in Python are mutable, which means you can modify their elements
after creation.
 Lists: Lists are also mutable, allowing you to add, remove, or modify elements.
3. Functionality:
 Arrays: Arrays provide a collection of methods for performing various operations,

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 3
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

such as appending, inserting, removing, and searching for elements. They also
support array-specific operations like slicing and concatenation.
 Lists: Lists offer a wide range of built-in methods and functions for working with
collections, including adding elements, removing elements, sorting, searching, and
more.
4. Memory Efficiency:
 Arrays: Arrays are more memory-efficient compared to lists, as they store elements
in a contiguous block of memory.
 Lists: Lists require additional memory overhead as they store not only the elements
but also other metadata, such as the size and references to other objects.
5. Usage:
 Arrays: Arrays are commonly used when there is a need for numerical computations
or working with large datasets that require efficient memory usage and
performance, such as scientific computing, data analysis, and numerical simulations.
 Lists: Lists are widely used for general-purpose programming and when flexibility is
desired, such as storing different types of data or dynamically changing the size of
the collection.

In summary, arrays are more specialized, efficient, and suitable for numerical computations,
while lists provide more flexibility and functionality for general-purpose programming and
working with collections of varying data types.

Section B
2 Attempt any two of the following: 4*2 = 8

a. Write a python function named ComputeAverage to find average of a list of numbers. It should CO1
handle the exception if the list is empty and return 0 in
that case.
Soln.
Python function named ComputeAverage that calculates the average of a list of numbers
and handles the exception if the list is empty:

def ComputeAverage(numbers):

try:

total = sum(numbers)

average = total / len(numbers)

return average

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 4
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

except ZeroDivisionError:

return 0

# Example usage

list1 = [2, 4, 6, 8, 10]

list2 = []

average1 = ComputeAverage(list1)

average2 = ComputeAverage(list2)

print(average1) # Output: 6.0

print(average2) # Output: 0

In this example, the ComputeAverage function takes a list of numbers as input. Inside the
function, it tries to calculate the sum of the numbers using the sum() function and then
divides it by the length of the list to compute the average.

If the list is not empty and the division by zero error doesn't occur, it returns the computed
average. However, if the list is empty and a ZeroDivisionError occurs, it catches the
exception and returns 0 as the average value.

In the example usage, we have two lists, list1 with numbers and list2 that is empty. We
call the ComputeAverage function with both lists and print the results. The average of
list1 is calculated as 6.0, while the average of list2 is 0 due to the exception handlin

b. Implement the binary search technique. CO2


Soln. def binary_search(arr, target):
low = 0
high = len(arr) - 1

while low <= high:

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 5
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

mid = (low + high) // 2


if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1

return -1 # Target element not found

# Example usage
my_list = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]

target = 23
index = binary_search(my_list, target)
if index != -1:
print("Element", target, "found at index", index)
else:
print("Element", target, "not found in the list")

the step-by-step instructions for performing a binary search:

1. Start with a sorted list: Binary search requires the input list to be sorted in ascending order.
2. Initialize the low and high indices: Set the low index to 0, representing the start of the list,
and the high index to len(arr) - 1, representing the end of the list.
3. Calculate the middle index: Compute the middle index by taking the average of the low
and high indices. Use integer division (//) to get the floor value.
4. Compare the middle element with the target:
 If the element at the middle index is equal to the target, the search is successful, and
the target is found at the middle index.
 If the element at the middle index is less than the target, it means the target can
only be present in the right half of the list. Update the low index to mid + 1.
 If the element at the middle index is greater than the target, it means the target can
only be present in the left half of the list. Update the high index to mid - 1.
5. Repeat steps 3 and 4: Continue the process of recalculating the middle index and
comparing the middle element with the target until one of the following conditions is met:
 The target element is found, in which case the search is successful and the index is
returned.
 The low index becomes greater than the high index, indicating that the target is not
present in the list. In this case, the search is unsuccessful, and -1 is returned.
6. Return the result: If the target element is found, return its index. Otherwise, return -1 to
indicate that the target is not present in the list.

Binary search follows a divide-and-conquer approach, reducing the search space in half
Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 6
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

with each iteration. This makes it an efficient algorithm for searching in large sorted lists.

Note: Binary search assumes that the input list is already sorted. If the list is unsorted,
binary search will not produce correct results, and it may be necessary to perform a sorting
algorithm before using binary search.

c. Explain the use of break and continue with a suitable example. CO4
Soln. The break and continue statements are control flow statements in Python that alter the
normal flow of a loop. They are used to control the execution of loops based on specific
conditions.

1. The break statement:


 The break statement is used to exit or terminate a loop prematurely.
 When the break statement is encountered within a loop, the loop is immediately
terminated, and the program execution continues with the next statement after the
loop.
 It is commonly used when a specific condition is met, and you want to exit the loop
early.
 Example:

# Print numbers from 1 to 10, but exit the loop when 5 is encountered
for num in range(1, 11):
if num == 5:
break
print(num)

1
2
3
4

1. In the above example, the for loop iterates from 1 to 10. When the value of num becomes
5, the break statement is executed, and the loop is terminated. As a result, only the
numbers 1 to 4 are printed.
2. The continue statement:
 The continue statement is used to skip the remaining code within a loop for the
current iteration and move to the next iteration.
 When the continue statement is encountered, it jumps back to the beginning of the
loop, skipping the remaining code below it for the current iteration.
 It is commonly used when you want to skip certain iterations based on a specific
condition and continue with the next iteration.
 Example:

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 7
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

# Print only the odd numbers from 1 to 10


for num in range(1, 11):
if num % 2 == 0:
continue
print(num)

1
3
5
7
9

1. In the above example, the for loop iterates from 1 to 10. When an even number is
encountered (num % 2 == 0), the continue statement is executed, and the remaining code
within the loop for that iteration is skipped. As a result, only the odd numbers are printed.

Both break and continue statements provide control over the flow of loops and allow you
to customize the behavior based on specific conditions.

d. What do you mean by operator precedence and associativity. Explain. CO3


Soln. In programming, operator precedence and associativity determine the order in which
operators are evaluated in an expression. They define the rules for how different operators
interact with each other when they appear together in an expression.

1. Operator Precedence:
 Operator precedence determines the priority or order of evaluation for operators in
an expression.
 It defines which operators have higher precedence and are evaluated first, and
which operators have lower precedence and are evaluated later.
 Operators with higher precedence are evaluated before operators with lower
precedence.
 For example, in the expression 2 + 3 * 4, the multiplication operator * has higher
precedence than the addition operator +. Therefore, the multiplication is performed
first, resulting in 2 + 12, and the final result is 14.
 Python follows a specific set of rules for operator precedence. For example,
multiplication and division have higher precedence than addition and subtraction.
2. Associativity:
 Associativity determines the order in which operators with the same precedence are
evaluated.
 It defines whether operators are evaluated from left to right (left-associative) or
from right to left (right-associative) when they have the same precedence.
 For example, the subtraction operator - is left-associative, so in the expression 10 -
4 - 2, it is evaluated as (10 - 4) - 2, resulting in 4.

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 8
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

 On the other hand, the exponentiation operator ** is right-associative, so in the


expression 2 ** 3 ** 2, it is evaluated as 2 ** (3 ** 2), resulting in 512.

It's important to understand operator precedence and associativity to write expressions


correctly and predict the outcome of complex expressions. When in doubt, you can use
parentheses to explicitly specify the order of evaluation.

In Python, you can refer to the documentation or resources that provide a complete table
of operator precedence for all operators supported by the language. Understanding
operator precedence and associativity helps ensure that expressions are evaluated in the
intended order, leading to accurate and expected results.

e. Write short notes on CO5


i. The programming cycle for python
ii. Type conversion in python
Soln. i. The Programming Cycle for Python:

The programming cycle, also known as the software development life cycle, is a systematic
process followed by programmers to develop software applications. Here are the key
stages of the programming cycle:

1. Problem Analysis: Understand the problem statement and requirements of the application.
Analyze the problem domain and gather necessary information.
2. Design: Plan and design the structure and behavior of the application. Create algorithms,
flowcharts, or pseudocode to outline the logic and sequence of operations.
3. Implementation: Write the actual code in a programming language, in this case, Python.
Implement the design by translating the algorithms and logic into executable code.
4. Testing and Debugging: Test the application to ensure it functions correctly and produces
the expected outputs. Identify and fix any bugs or errors encountered during testing.
5. Documentation: Document the code and its functionality. Provide clear comments,
explanations, and instructions for other developers or users to understand and use the
code effectively.
6. Maintenance and Updates: Maintain the codebase by performing regular updates, bug
fixes, and improvements as needed. Monitor the application's performance and address
any issues that arise.

The programming cycle is an iterative process, meaning that it often involves going back
and forth between stages, refining and improving the code as necessary.

ii. Type Conversion in Python:

Type conversion, also known as type casting or type coercion, refers to the process of

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 9
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

converting a value from one data type to another in Python. Python provides built-in
functions and methods for performing type conversions. Here are some commonly used
type conversion functions:

1. int(): Converts a value to an integer data type. For example, int("10") converts the string
"10" to the integer 10.
2. float(): Converts a value to a floating-point data type. For example, float("3.14")
converts the string "3.14" to the float 3.14.
3. str(): Converts a value to a string data type. For example, str(42) converts the integer 42
to the string "42".
4. list(): Converts an iterable (such as a tuple or string) to a list data type. For example,
list((1, 2, 3)) converts the tuple (1, 2, 3) to the list [1, 2, 3].
5. tuple(): Converts an iterable (such as a list or string) to a tuple data type. For example,
tuple([1, 2, 3]) converts the list [1, 2, 3] to the tuple (1, 2, 3).

Type conversion is often necessary when working with different data types or when
performing operations that require matching data types. It allows for seamless
interoperability and manipulation of data across different types in Python.

f. Write Python program to swap two numbers without Intermediate/Temporary


variables. Prompt the user for input

# Prompt the user for input

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

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

print("Before swapping:")

print("Number 1 =", num1)

print("Number 2 =", num2)

# Swapping the numbers

num1, num2 = num2, num1

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 10
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

print("After swapping:")

print("Number 1 =", num1)

print("Number 2 =", num2)

In this program, we use the input() function to prompt the user to enter two numbers.
The numbers are stored as strings in the variables num1 and num2.

Next, we print the numbers before swapping. Then, using the concept of multiple
assignments, we swap the values of num1 and num2 without using an intermediate variable.
The line num1, num2 = num2, num1 simultaneously assigns the value of num2 to num1 and
the value of num1 to num2, effectively swapping their values.

Finally, we print the numbers after swapping to verify the result.

Note that since the user input is treated as strings, the swapping is done at the string level.
If you want to perform arithmetic operations with the numbers, you'll need to convert
them to the appropriate numeric data type using functions like int() or float().

4. Attempt any two part of the following: 4*2 = 8

a. Write a program to check an input number is prime or not. CO2


# Function to check if a number is prime
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True

# Prompt the user for input


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

# Check if the number is prime


if is_prime(number):
print(number, "is a prime number.")

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 11
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

else:
print(number, "is not a prime number.")

In this program, we define a function is_prime() that takes a number as an argument


and checks if it's prime. The function uses a basic primality test by iterating from 2 to the
square root of the number and checking for divisibility. If the number is divisible by any
integer in that range, it is not prime. Otherwise, it is prime.

We prompt the user to enter a number using the input() function, and then convert it to
an integer using int().

Next, we call the is_prime() function with the input number as an argument and check
the returned value. If the function returns True, we print that the number is prime.
Otherwise, we print that the number is not prime.

Feel free to try out different numbers to check if they are prime or not.

b. Write a program that accepts a sentence and calculate the number of digits, uppercase and CO2
lowercase letters.
# Prompt the user for input
sentence = input("Enter a sentence: ")

# Initialize counters
digit_count = 0
uppercase_count = 0
lowercase_count = 0

# Iterate over each character in the sentence


for char in sentence:
# Check if the character is a digit
if char.isdigit():
digit_count += 1
# Check if the character is an uppercase letter
elif char.isupper():
uppercase_count += 1
# Check if the character is a lowercase letter
elif char.islower():
lowercase_count += 1

# Print the results


print("Number of digits:", digit_count)
print("Number of uppercase letters:", uppercase_count)
print("Number of lowercase letters:", lowercase_count)

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 12
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

In this program, we prompt the user to enter a sentence using the input() function and
store it in the sentence variable.

We initialize three counters: digit_count, uppercase_count, and lowercase_count to


keep track of the respective counts.

Next, we iterate over each character in the sentence using a for loop. For each character,
we check its type using the isdigit(), isupper(), and islower() string methods.

If the character is a digit, we increment the digit_count variable. If it's an uppercase


letter, we increment the uppercase_count variable. If it's a lowercase letter, we increment
the lowercase_count variable.

Finally, we print the counts of digits, uppercase letters, and lowercase letters.

Feel free to enter different sentences and observe the counts of digits and letters in each
case.

c. Write a program to check an input year is leap year or not.

5. Attempt any two part of the following: 4*2 = 8

a. There is a file named Input.Txt. Enter some positive numbers into the file CO2
named Input.Txt. Read the contents of the file and if it is an odd number write it to ODD.TXT and
if the number is even, write it to EVEN.TXT

# Open the input file in read mode


with open("Input.txt", "r") as input_file:
numbers = input_file.readlines()

# Create two output files: ODD.TXT and EVEN.TXT


odd_file = open("ODD.TXT", "w")
even_file = open("EVEN.TXT", "w")

# Process each number and write to the appropriate file


for number in numbers:
number = int(number.strip()) # Convert the number from string to integer and remove any
trailing whitespace

if number % 2 == 0:
even_file.write(str(number) + "\n")
Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 13
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

else:
odd_file.write(str(number) + "\n")

# Close the output files


odd_file.close()
even_file.close()

print("Numbers have been written to ODD.TXT and EVEN.TXT.")

In this program, we start by opening the "Input.txt" file in read mode using a with
statement. The contents of the file are read using the readlines() method, which returns
a list of lines.

We then create two output files: "ODD.TXT" and "EVEN.TXT" using the open() function in
write mode.

Next, we iterate over each number in the numbers list. For each number, we convert it
from a string to an integer using int() and remove any trailing whitespace using
strip().

If the number is even (i.e., divisible by 2), we write it to the "EVEN.TXT" file. Otherwise, we
write it to the "ODD.TXT" file. We add a newline character ("\n") after each number to
separate them in the output file.

Finally, we close both the input and output files, and print a message indicating that the
numbers have been written to the respective files.

Make sure to create the "Input.txt" file and enter positive numbers into it before running
the program.

b. Discuss Exceptions and Assertions in example. Explain any two built-in CO2
exceptions.
Exceptions and assertions are mechanisms in Python used to handle and manage errors or
exceptional situations that may occur during program execution. Here's a brief
explanation of exceptions and assertions along with examples of two built-in exceptions in
Python:

1. Exceptions:
 Exceptions are events that occur during the execution of a program that disrupt the
normal flow of code. They can be caused by various factors such as invalid inputs,
runtime errors, or exceptional conditions.
 When an exception occurs, it generates an exception object that contains

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 14
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

information about the error, including its type and message.


 Exceptions can be handled using try-except blocks. The code within the try block is
executed, and if an exception occurs, it is caught by the except block, which
handles the exception gracefully.
 Here's an example that demonstrates catching and handling an exception:
try:
num = int(input("Enter a number: "))
result = 10 / num
print("Result:", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except ValueError:
print("Error: Invalid input. Please enter a valid number.")

In this example, the program prompts the user to enter a number. If the user enters 0, a
ZeroDivisionError exception will be raised when dividing by zero. If the user enters a non-
numeric value, a ValueError exception will be raised when converting the input to an
integer. The respective except blocks catch and handle these exceptions by printing
appropriate error messages.

2. Assertions:
 Assertions are statements that check if a given condition is true and raise an
AssertionError if it is false. They are used to enforce certain assumptions or
constraints within the code.
 Assertions are typically used during development and debugging to detect and
identify logical errors or unexpected conditions.
 Here's an example that demonstrates the use of assertions:
def divide(a, b):
assert b != 0, "Error: Division by zero."
return a / b

num1 = 10
num2 = 0

result = divide(num1, num2)


print("Result:", result)

In this example, we define a divide() function that takes two arguments and performs
division. Before performing the division, we assert that the second argument ( b) is not
equal to zero. If the condition is false (i.e., b is zero), an AssertionError will be raised, and
the program will terminate with an error message.

Note: It is important to handle exceptions appropriately and use assertions judiciously in


Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 15
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

your code to ensure robustness and maintain program integrity.

Regarding the built-in exceptions, here are brief explanations of two commonly used
exceptions:

1. ZeroDivisionError: This exception is raised when attempting to divide a number by zero.


For example:

result = 10 / 0 # Raises ZeroDivisionError

ValueError: This exception is raised when a function receives an argument of the correct
type but an inappropriate value. For example:

num = int("abc") # Raises ValueError because "abc" cannot be converted to an integer


These are just two examples of the numerous built-in exceptions available in Python. Each
exception serves a specific purpose and can be caught and handled as needed in your
code.
c. What is the significance of module in Python? What are the methods of importing a
module? Explain with suitable example

In Python, a module is a file containing Python definitions, functions, and statements. It


serves as a way to organize and reuse code, making it easier to manage and maintain
larger programs. Modules can include variables, classes, and functions that can be
accessed and used in other Python programs by importing them.

The significance of modules in Python can be summarized as follows:

1. Code Organization: Modules allow you to organize related code into separate files,
making it easier to manage and maintain large projects. By dividing code into modules,
you can improve code readability and make it more modular.
2. Code Reusability: Modules provide a way to reuse code across multiple programs. Instead
of rewriting the same code in different scripts, you can create a module and import it
wherever needed. This promotes code reusability and reduces redundancy.
3. Namespace Separation: Modules help create separate namespaces, which prevent naming
conflicts. By importing specific modules, you can access their functions and variables
without worrying about naming clashes with other parts of your program.

Now, let's discuss the methods of importing a module in Python with suitable examples:

1. Importing the Entire Module:


 To import the entire module, you can use the import statement followed by the
module name.

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 16
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

 Example:

import math

result = math.sqrt(25)

print("Square root of 25:", result)

In this example, the math module is imported, and the sqrt() function from the module is
used to calculate the square root of 25.

2. Importing Specific Items from a Module:


 If you only need specific functions or variables from a module, you can import
them individually using the from keyword.
 Example:

from math import sqrt, pi

result = sqrt(16)

print("Square root of 16:", result)

circumference = 2 * pi * 5

print("Circumference of a circle with radius 5:", circumference)

In this example, only the sqrt() function and the value of pi are imported from the math
module. This allows you to directly use these specific items without referencing the
module name.

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 17
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

3. Importing a Module with an Alias:


 You can assign an alias to a module while importing it using the as keyword. This is
useful when working with modules with long names or to avoid naming conflicts.
 Example:

import numpy as np

array = np.array([1, 2, 3, 4, 5])

print("Array:", array)

In this example, the numpy module is imported with the alias np. The alias is used to access
functions and objects from the module, as shown in the creation of a NumPy array.

These are some common methods of importing modules in Python. Depending on the
specific requirements of your code, you can choose the most suitable method to import
and use modules effectively.

6. Attempt any two part of the following: 4*2 = 8

a. What do you mean by recursion? Write a recursive function to compute the factorial of an input CO2
number N.
Recursion is a programming technique where a function calls itself to solve a smaller
subproblem of the same type. In other words, a recursive function is a function that
defines itself in terms of a simpler version of itself.

To compute the factorial of a number using recursion, we can define a recursive function
that breaks down the problem into smaller subproblems until we reach the base case,
which is the simplest form of the problem.

Here's an example of a recursive function to compute the factorial of a number:

def factorial(n):
# Base case: factorial of 0 or 1 is 1
if n == 0 or n == 1:
return 1
else:
# Recursive case: factorial of n is n multiplied by factorial of (n-1)
return n * factorial(n - 1)

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 18
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

# Prompt the user for input


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

# Call the recursive function to compute factorial


result = factorial(num)

print("Factorial of", num, "is", result)

In this example, the factorial() function takes an input parameter n and computes the
factorial of n. The base case is when n is 0 or 1, where the factorial is defined as 1. For any
other value of n, the function calls itself recursively with the argument (n-1) and
multiplies it by n. This process continues until the base case is reached.

The program prompts the user to enter a number, and then calls the factorial()
function to compute the factorial of that number. The result is then displayed on the
screen.

Note: Recursive functions should always have a base case that terminates the recursion,
ensuring that the function does not call itself indefinitely.

b. Implement selection sort using Python CO2


def selection_sort(arr):

n = len(arr)

for i in range(n):

# Find the minimum element in the remaining unsorted portion of the array

min_idx = i

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

if arr[j] < arr[min_idx]:

min_idx = j

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 19
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

# Swap the minimum element with the first element in the unsorted portion

arr[i], arr[min_idx] = arr[min_idx], arr[i]

return arr

# Example usage:

nums = [64, 25, 12, 22, 11]

sorted_nums = selection_sort(nums)

print("Sorted array:", sorted_nums)

In this code, the selection_sort() function takes an array (arr) as input and sorts it
using the Selection Sort algorithm. The function iterates through the array and at each
iteration, finds the minimum element in the remaining unsorted portion of the array. It
then swaps the minimum element with the first element in the unsorted portion. This
process continues until the entire array is sorted.

In the example usage, we have an array nums with unsorted elements. We call the
selection_sort() function with nums as the argument, and it returns the sorted array.
Finally, we print the sorted array on the screen.

The output of the example will be:

Sorted array: [11, 12, 22, 25, 64]

This demonstrates the selection sort algorithm sorting the given array in ascending order.
c. What are different types of inheritance supported by Python? Explain.

In Python, the following types of inheritance are supported:

1. Single Inheritance:

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 20
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

 Single inheritance is the simplest form of inheritance where a class inherits from a
single base class.
 The derived class inherits all the attributes and methods of the base class.
 Example:

class Parent:

def __init__(self):

self.parent_attr = "Parent attribute"

def parent_method(self):

print("Parent method")

class Child(Parent):

def __init__(self):

super().__init__()

self.child_attr = "Child attribute"

def child_method(self):

print("Child method")

child_obj = Child()

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 21
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

child_obj.parent_method()

child_obj.child_method()

Multiple Inheritance:
 Multiple inheritance allows a class to inherit from multiple base classes.
 The derived class inherits attributes and methods from all the base classes.
 Example:

class Parent1:

def parent1_method(self):

print("Parent 1 method")

class Parent2:

def parent2_method(self):

print("Parent 2 method")

class Child(Parent1, Parent2):

def child_method(self):

print("Child method")

child_obj = Child()

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 22
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

child_obj.parent1_method()

child_obj.parent2_method()

child_obj.child_method()

Multilevel Inheritance:
 Multilevel inheritance involves a chain of inheritance where a derived class inherits
from another derived class.
 Each derived class in the chain inherits attributes and methods from its immediate
base class.
 Example:

class Grandparent:

def grandparent_method(self):

print("Grandparent method")

class Parent(Grandparent):

def parent_method(self):

print("Parent method")

class Child(Parent):

def child_method(self):

print("Child method")

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 23
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

child_obj = Child()

child_obj.grandparent_method()

child_obj.parent_method()

child_obj.child_method()

Hierarchical Inheritance:
 Hierarchical inheritance involves multiple derived classes inheriting from a single
base class.
 Each derived class inherits attributes and methods from the common base class.
 Example:

class Parent:

def parent_method(self):

print("Parent method")

class Child1(Parent):

def child1_method(self):

print("Child 1 method")

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 24
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution

class Child2(Parent):

def child2_method(self):

print("Child 2 method")

child1_obj = Child1()

child1_obj.parent_method()

child1_obj.child1_method()

child2_obj = Child2()

child2_obj.parent_method()

child2_obj.child2_method()

These are the different types of inheritance supported by Python. Each type allows for different
ways of reusing and extending code by creating relationships between classes.

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 25
AKTU
Python AKTU Question Paper 2022-23
Solution
SUBJECT CODE: KNC-402
B.TECH.(CSE /CS IT/ CS AI ML) SEMESTER -IV

Academic Session: 2022-23, Even Semester


Faculty
Dr. Aadarsh Malviya
(Associate Professor Department of CSE)

Dronacharya Group of Institutions


Plot No. 27, Knowledge Park-3, Greater Noida, Uttar Pradesh 201308

Affiliated to

Dr. A P J Abdul Kalam Technical University


Lucknow, Uttar Pradesh 226031
AKTU Python Programming KNC 402 session2021-22 solution

.SECTION A
1. Attempt all questions in brief. 2*5 = 10

a. Explain the Programming Cycle for Python in detail. CO1


Soln. The programming cycle, also known as the software development cycle or the software
development process, refers to the set of activities involved in creating, testing, and
maintaining a software application. It encompasses the entire life cycle of software
development, from the initial planning and analysis stages to deployment and
maintenance. Here's a detailed explanation of the programming cycle for Python:

1. Requirements Gathering and Analysis:


 In this stage, the requirements for the software are gathered by interacting with
stakeholders such as clients or end-users.
 The requirements are analyzed to understand the scope of the project, the problem
it aims to solve, and the desired functionalities of the software.
 The analysis phase helps identify the key features and constraints of the software.
2. Design:
 Once the requirements are gathered, the software design phase begins.
 The design process involves creating a high-level architectural design and breaking
it down into smaller modules or components.
 The design may include user interface design, database schema design, and
algorithm design.
 The design phase helps create a blueprint for the software's structure and
functionality.
3. Implementation:
 The implementation phase is where the actual coding takes place.
 Using Python, programmers write code based on the design specifications.
 The code is typically divided into functions, classes, and modules to enhance
modularity and maintainability.
 Best practices and coding standards are followed to ensure readability and
maintainability of the code.
4. Testing:
 In this phase, the developed software is tested to identify and fix any defects or
bugs.
 Various testing techniques, such as unit testing, integration testing, and system
testing, are employed to ensure the software behaves as expected.
 Python provides testing frameworks like pytest and unittest that facilitate the
creation and execution of test cases.
5. Deployment:
 Once the software passes the testing phase, it is ready for deployment.
 Deployment involves making the software available to end-users or deploying it to
production environments.

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 1
AKTU Python Programming KNC 402 session2021-22 solution

Python offers several deployment options, including standalone executables, web


applications using frameworks like Django or Flask, or packaging the software as
libraries or modules.
6. Maintenance and Updates:
 After deployment, the software enters the maintenance phase.
 During this phase, any issues reported by users are addressed, and updates or
enhancements are implemented as required.
 Maintenance may include bug fixes, performance optimizations, security updates, or
adding new features.
 The maintenance phase continues throughout the software's lifespan to ensure its
reliability and effectiveness.

It's important to note that the programming cycle is not strictly linear. It often involves
iterations and feedback loops, where developers revisit earlier stages to refine and improve
the software based on user feedback or changing requirements. This iterative nature allows
for flexibility and continuous improvement in the development process.

b. What will be the output of the following Python code? i = 0 while i< 3: print(i) i += 1 else: print(0)
Soln. 0
1
2
0
c. W hat will be the output of the following Python code? def cube(x): return x * x * x x = cube(3)
print x
Soln. 27
d. How do we define an Interface for an ADT?
Soln. In Python, there is no explicit language construct for defining interfaces like in some other
programming languages. However, you can define an interface for an Abstract Data Type
(ADT) in Python by using a combination of conventions and techniques. Here are some
common approaches:

1. Documentation: Clearly document the methods and their expected behavior that should be
implemented by classes adhering to the interface. Use docstrings to provide detailed
explanations of the purpose, parameters, and return values of each method.
2. Abstract Base Classes (ABCs): Python's abc module provides a mechanism for defining
abstract base classes, which can serve as interfaces. By inheriting from the ABC class and
using the @abstractmethod decorator, you can define abstract methods that must be
implemented by concrete classes.
from abc import ABC, abstractmethod

class MyInterface(ABC):
@abstractmethod
def method1(self):
pass

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 2
AKTU Python Programming KNC 402 session2021-22 solution

@abstractmethod
def method2(self, param):
pass
1. Classes that implement MyInterface will need to provide concrete implementations for
method1 and method2.
2. Duck Typing: In Python, the focus is on "duck typing," which means that if an object
behaves like a particular interface (even without explicitly declaring it), it can be considered
as implementing that interface. Instead of checking whether an object inherits from a
specific class or implements a particular interface, you can directly use the object and rely
on the presence of specific methods or attributes.
class MyInterface:
def method1(self):
raise NotImplementedError()

def method2(self, param):


raise NotImplementedError()
1. This approach relies on the developer's responsibility to ensure that any class claiming to
implement MyInterface must provide implementations for method1 and method2.
However, there is no strict enforcement by the language.

Remember that in Python, the focus is on the behavior of objects rather than their types.
So, even without formal interfaces, you can design your code in such a way that classes
adhere to a specific interface contract through documentation, naming conventions,
and/or the use of abstract base classes.

e. How do you perform a search in Python?

Soln. In Python, there are several ways to perform a search operation depending on the data
structure and the type of search you want to perform. Here are some common methods for
performing searches in Python:

1. List Search:
 If you have a list and want to find the index of a specific element, you can use the
index() method.

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

index = my_list.index(3)

print(index) # Output: 2

If you want to check if an element exists in a list, you can use the in operator.

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

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 3
AKTU Python Programming KNC 402 session2021-22 solution

exists = 3 in my_list

print(exists) # Output: True

String Search:
 To search for a substring within a string, you can use the find() method.

my_string = "Hello, World!"

index = my_string.find("World")

print(index) # Output: 7

To check if a substring exists in a string, you can use the in operator.

my_string = "Hello, World!"

exists = "World" in my_string

print(exists) # Output: True

Dictionary Search:
 If you have a dictionary and want to check if a key exists, you can use the in
operator

my_dict = {"name": "John", "age": 30}

exists = "name" in my_dict

print(exists) # Output: True

To retrieve the value associated with a key in a dictionary, you can use square brackets.

my_dict = {"name": "John", "age": 30}

value = my_dict["name"]

print(value) # Output: "John"

1. Customized Search:
 If you need to perform a more complex search, you can use iterative algorithms like
linear search or binary search.
 Linear Search: Iterate through a list or an iterable and check each element until a
match is found.
 Binary Search: Requires a sorted sequence and repeatedly divides the search space
in half until the target is found or determined to be absent.

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 4
AKTU Python Programming KNC 402 session2021-22 solution

It's important to choose the appropriate search algorithm based on the characteristics of
your data and the efficiency requirements of your program.

These are just a few examples of search operations in Python. The method you choose will
depend on the data structure and the specific requirements of your search task.

Section B
2. Attempt any three of the following: 5*3 = 15
a. What do you mean by Python IDE? Explain in detail CO1
Soln. An Integrated Development Environment (IDE) is a software application that provides
comprehensive tools and features to streamline the process of writing, testing, and
debugging code. It offers a dedicated environment for developing software applications
and makes the development process more efficient and productive. In the context of
Python, a Python IDE refers to an IDE specifically designed for Python programming. Here's
a detailed explanation of Python IDEs:

Features of Python IDEs:

1. Code Editor: Python IDEs typically provide a code editor with syntax highlighting, code
completion, and intelligent code suggestions. These features help developers write code
faster and with fewer errors.
2. Debugging Support: IDEs offer built-in debuggers that allow developers to set breakpoints,
step through the code, inspect variables, and analyze the program's execution flow. This
helps in identifying and resolving bugs and issues in the code.
3. Integrated Terminal: Python IDEs often include an integrated terminal or command prompt
within the IDE itself. This allows developers to execute Python code, run scripts, and
interact with the Python interpreter without leaving the IDE.
4. Project Management: IDEs provide project management capabilities, allowing developers
to organize their code into projects, manage dependencies, and navigate between project
files easily. They often have features like project templates, version control integration, and
project-specific configurations.
5. Testing Framework Integration: Python IDEs often support integration with testing
frameworks like pytest or unittest. This integration allows developers to easily create, run,
and analyze unit tests within the IDE.
6. Code Refactoring: IDEs provide tools for code refactoring, which enable developers to
efficiently restructure and improve their code without manually modifying each occurrence.
Examples of code refactoring include renaming variables, extracting methods, and
optimizing imports.
7. Documentation Integration: Many Python IDEs offer integration with documentation tools,
allowing developers to easily access Python's official documentation or other relevant
documentation sources within the IDE. This helps in quickly referring to function signatures,

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 5
AKTU Python Programming KNC 402 session2021-22 solution

library documentation, and usage examples.


8. Collaboration and Teamwork: Some Python IDEs support collaboration features, allowing
multiple developers to work on the same codebase simultaneously. These features can
include code sharing, real-time editing, and collaborative debugging.

Popular Python IDEs:

1. PyCharm: Developed by JetBrains, PyCharm is a widely used cross-platform Python IDE that
offers a comprehensive set of features for Python development.
2. Visual Studio Code (VS Code): Although not a dedicated Python IDE, VS Code provides
excellent Python support through extensions. It offers a lightweight and customizable
environment with powerful features for Python development.
3. Jupyter Notebook: Jupyter Notebook is an open-source web-based environment that
allows interactive Python coding, data analysis, and visualization. It supports Markdown,
code execution, and rich media integration.
4. Spyder: Designed specifically for scientific computing, Spyder is an open-source Python IDE
that provides a MATLAB-like environment with advanced features for data exploration,
analysis, and visualization.
5. IDLE: IDLE is a basic Python IDE that comes bundled with the standard Python distribution.
It offers a simple integrated environment suitable for beginners or quick scripting tasks.

These are just a few examples of Python IDEs, and there are many more available, each
with its own set of features and advantages. The choice of a Python IDE depends on
individual preferences, the complexity of the project, and specific requirements.

b. How can you randomize the items of a list in place in Python? CO2
Soln. To randomize or shuffle the items of a list in place (i.e., modifying the original list), you can
make use of the random module in Python. The random module provides functions for
generating random numbers and performing random operations. Specifically, the
shuffle() function from the random module can be used to shuffle the items of a list.
Here's an example:

import random

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

random.shuffle(my_list)

print(my_list)

The output will be a randomized order of the elements in the list, such as [3, 2, 1, 5,
4] or [4, 5, 1, 2, 3]. The original list is modified directly.

The random.shuffle() function shuffles the items of the list in a random order using the

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 6
AKTU Python Programming KNC 402 session2021-22 solution

Fisher-Yates algorithm. It rearranges the elements by swapping them repeatedly, resulting


in a random permutation.

Note that the random.shuffle() function modifies the list in place, and it doesn't return
any value. If you want to create a new randomized list without modifying the original list,
you can use the sample() function from the random module:

import random

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

randomized_list = random.sample(my_list, len(my_list))

print(randomized_list)
In this case, the random.sample() function returns a new list that contains a randomized
sample of the elements from the original list. The original list remains unmodified.
c. What are File input and output operations in Python Programming? CO4
Soln. File input and output operations, commonly referred to as file I/O operations, involve
reading data from files (input) and writing data to files (output) in Python programming.
These operations allow you to interact with files on the disk, enabling data persistence and
communication with external resources. Here's an overview of file input and output
operations in Python:

File Input Operations: File input operations involve reading data from files. Python provides
various methods and functions to read file contents:

1. Opening a File: To open a file for reading, you can use the built-in open() function. It takes
the file path and an optional mode argument (default is 'r' for reading) and returns a file
object.

file = open('file.txt', 'r')


Reading Data from a File: Once a file is open, you can read its contents using methods
provided by the file object. Some common methods are:
 read(): Reads the entire contents of the file as a string.
 readline(): Reads a single line from the file.
 readlines(): Reads all lines from the file and returns them as a list.
content = file.read() # Read the entire file
line = file.readline() # Read a single line
lines = file.readlines() # Read all lines as a list

Closing a File: After reading the file, it's essential to close it using the close() method to
release system resources associated with the file.
file.close()

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 7
AKTU Python Programming KNC 402 session2021-22 solution

File Output Operations: File output operations involve writing data to files. Python provides
methods and functions to write data to files:

1. Opening a File: To open a file for writing, you can use the open() function with the mode
argument set to 'w' for writing.

file = open('file.txt', 'w')


Writing Data to a File: Once a file is open for writing, you can use the write() method of
the file object to write data. You can write strings or use the str() function to convert
non-string data to strings.

file.write('Hello, World!\n') # Write a string


file.write(str(123)) # Write a number (converted to string)

Closing a File: After writing to the file, it's important to close it using the close() method
to ensure that the data is properly written and the system resources are released.
file.close()

It's worth noting that using the with statement is a recommended approach for file I/O
operations in Python. It automatically takes care of opening and closing the file, ensuring
proper resource management and exception handling.
with open('file.txt', 'r') as file:
content = file.read()
# Perform operations with the file content

# File is automatically closed outside the `with` block

File I/O operations are fundamental for working with external data, such as reading
configuration files, processing data files, and saving program output to files. Understanding
and utilizing file input and output operations in Python enables effective interaction with
the file system and facilitates data persistence and communication with other programs or
users.
d. Explain Tuples and Unpacking Sequences in Python Data Structure. CO3
Soln. Tuples: A tuple is an immutable, ordered collection of elements in Python. It is similar to a
list, but unlike lists, tuples cannot be modified once created. Tuples are defined using
parentheses () or the tuple() constructor. Here are some key characteristics of tuples:

1. Immutable: Once a tuple is created, its elements cannot be changed. This means you
cannot add, remove, or modify individual elements of a tuple.
2. Ordered: Tuples preserve the order of their elements, meaning the elements have a specific
position or index within the tuple.
3. Heterogeneous: Tuples can contain elements of different data types. For example, a tuple
can have a combination of integers, strings, floats, and other objects.
4. Indexing and Slicing: You can access individual elements of a tuple using indexing or slicing

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 8
AKTU Python Programming KNC 402 session2021-22 solution

operations, similar to lists. Indexing starts from 0.

my_tuple = (10, 'Hello', 3.14)


print(my_tuple[0]) # Output: 10
print(my_tuple[1]) # Output: 'Hello'
print(my_tuple[2]) # Output: 3.14

# Slicing
print(my_tuple[1:]) # Output: ('Hello', 3.14)

Unpacking Sequences: Unpacking sequences is a convenient feature in Python that allows


you to assign the elements of a sequence, such as a tuple or a list, to multiple variables in a
single line. It provides a concise way to assign values from a sequence to individual
variables. Here's an example:
my_tuple = ('John', 25, 'Developer')
name, age, profession = my_tuple

print(name) # Output: 'John'


print(age) # Output: 25
print(profession) # Output: 'Developer'

In this example, the elements of the my_tuple tuple are assigned to the variables name,
age, and profession in a single line. The number of variables on the left side of the
assignment must match the number of elements in the tuple.

Unpacking can be used with any iterable, not just tuples. It allows you to extract elements
from sequences such as lists, sets, and even strings.

my_list = [1, 2, 3]
a, b, c = my_list

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

my_set = {'apple', 'banana', 'cherry'}


x, y, z = my_set

print(x) # Output: 'banana'


print(y) # Output: 'apple'
print(z) # Output: 'cherry'

my_string = 'Hello'
a, b, c, d, e = my_string

print(a) # Output: 'H'


print(b) # Output: 'e'

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 9
AKTU Python Programming KNC 402 session2021-22 solution

print(c) # Output: 'l'


print(d) # Output: 'l'
print(e) # Output: 'o'
Unpacking sequences is a powerful feature in Python that simplifies the assignment of
values from a sequence to individual variables, making the code more concise and
readable.

e. Solve the Tower of Hanoi problem for n= 3 disk and show all the steps. CO5
Soln. Sure! The Tower of Hanoi problem is a classic mathematical puzzle that involves moving a
stack of disks from one peg to another peg, using a temporary peg, while following specific
rules:

1. Only one disk can be moved at a time.


2. Each move consists of taking the upper disk from one of the stacks and placing it on top of
another stack or an empty peg.
3. No disk may be placed on top of a smaller disk.

For n = 3 disks, here are the step-by-step instructions to solve the Tower of Hanoi problem:

Step 1: Move disk 1 from the source peg (S) to the destination peg (D).

Step 2: Move disk 2 from the source peg (S) to the auxiliary peg (A).

Step 3: Move disk 1 from the destination peg (D) to the auxiliary peg (A).

Step 4: Move disk 3 from the source peg (S) to the destination peg (D).

Step 5: Move disk 1 from the auxiliary peg (A) to the source peg (S).

Step 6: Move disk 2 from the auxiliary peg (A) to the destination peg (D).

Step 7: Move disk 1 from the source peg (S) to the destination peg (D).

Here's a graphical representation of the steps:

Step 1:
S A D
--- --- ---
|1| | | | |
|2| | | | |
|3| | | | |

Step 2:
S A D

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 10
AKTU Python Programming KNC 402 session2021-22 solution

--- --- ---


| | |2| | |
| | |1| | |
|3| | | | |

Step 3:
S A D
--- --- ---
| | | | |1|
| | | | |2|
|3| | | | |

Step 4:
S A D
--- --- ---
| | | | |1|
| | | | |2|
| | | | |3|

Step 5:
S A D
--- --- ---
| | |1| |2|
| | | | |3|
| | | | | |

Step 6:
S A D
--- --- ---
| | | | |2|
| | |1| |3|
| | | | | |

Step 7:
S A D
--- --- ---
| | | | | |
| | | | |1|
| | | | |2|
| | | | |3|

In the above representation, S represents the source peg, A represents the auxiliary peg,

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 11
AKTU Python Programming KNC 402 session2021-22 solution

and D represents the destination peg. Each disk is represented by its size (1, 2, or 3). The
goal is to move all the disks from the source peg to the destination peg using the auxiliary
peg.

By following the steps above, you can successfully solve the Tower of Hanoi problem for n
=

Section C
3. Attempt any one part of the following: 5*1 = 5

a. Write a program in Python to execute the Selection sort algorithm. CO5


def selection_sort(arr):
n = len(arr)

# Traverse through all array elements


for i in range(n):
# Find the minimum element in the remaining unsorted part
min_index = i
for j in range(i + 1, n):
if arr[j] < arr[min_index]:
min_index = j

# Swap the found minimum element with the first element


arr[i], arr[min_index] = arr[min_index], arr[i]

# Example usage
numbers = [64, 25, 12, 22, 11]
selection_sort(numbers)
print("Sorted array:", numbers)
b. Explain why python is considered an interpreted language. CO1
Python is considered an interpreted language because it utilizes an interpreter to execute its
code directly, without the need for a separate compilation step. Here are a few key reasons
why Python is classified as an interpreted language:

1. Interpreter Execution: Python code is executed by an interpreter, which reads and processes
the code line by line. The interpreter translates each line of code into machine-readable
instructions and executes them immediately. This differs from compiled languages where the
source code is first converted into machine code through a separate compilation step before
execution.
2. Dynamic Typing: Python is dynamically typed, meaning variable types are determined and
checked at runtime. This dynamic type checking is facilitated by the interpreter, which allows
for flexibility but also introduces a performance trade-off compared to statically typed
compiled languages.
3. Interactive Shell: Python provides an interactive shell, commonly known as the Python REPL
(Read-Eval-Print Loop), where users can directly type and execute Python code statements.

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 12
AKTU Python Programming KNC 402 session2021-22 solution

The interpreter processes each line of code as it is entered, providing immediate feedback
and results. This interactive nature of Python further highlights its interpreted nature.
4. Ease of Development and Debugging: Interpreted languages like Python offer advantages in
terms of development and debugging. Since there is no need for a separate compilation
step, Python code can be executed and tested more quickly, allowing for a rapid
development cycle. Additionally, Python provides tools and features that facilitate
debugging, such as interactive debugging with breakpoints, which are made possible by the
interpreter's ability to execute code step-by-step.
5. Portability and Cross-Platform Support: The interpreted nature of Python contributes to its
portability and cross-platform compatibility. Python code can run on any platform or
operating system that has a compatible Python interpreter installed, without the need for
recompilation. This allows for code to be written and executed on different systems without
modification, enhancing its versatility.

It's important to note that although Python is primarily interpreted, there are options
available to optimize its performance. Techniques like just-in-time (JIT) compilation and
ahead-of-time (AOT) compilation can be employed to translate Python code into machine
code to improve execution speed. However, the core concept of Python being an interpreted
language remains intact.

4. Attempt any one part of the following: 5 *1 = 5

a. Write a Python program to construct the following pattern, using a nested for loop. CO2
*
**
***
****
*****
* ***
***
**
*
for i in range(1, 6): # Outer loop for the number of rows
for j in range(i): # Inner loop for printing the asterisks
print("*", end=" ")
print() # Print a new line after each row

for i in range(4, 0, -1): # Outer loop for the remaining rows


for j in range(i): # Inner loop for printing the asterisks
print("*", end=" ")
print() # Print a new line after each row

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 13
AKTU Python Programming KNC 402 session2021-22 solution

b. Write a program to produce Fibonacci series in Python. CO2


def fibonacci(n):
fib_series = [] # List to store the Fibonacci series

# Check if the input is valid


if n <= 0:
print("Invalid input! Please enter a positive integer.")
return fib_series

# First two numbers in the Fibonacci series


fib1, fib2 = 0, 1
fib_series.append(fib1) # Add the first number to the series

# Generate the Fibonacci series


for _ in range(1, n):
fib_series.append(fib2)
fib1, fib2 = fib2, fib1 + fib2

return fib_series

# Example usage
num_terms = 10
fibonacci_series = fibonacci(num_terms)
print("Fibonacci series up to", num_terms, "terms:", fibonacci_series)

5. Attempt any one part of the following: 5*1 = 5

a. Write a Python program to change a given string to a new string where the first and last chars have CO2
been exchanged.
def exchange_first_last(string):
# Check if the string has at least two characters
if len(string) < 2:
print("Invalid input! Please provide a string with at least two characters.")
return string

# Extract the first and last characters


first_char = string[0]
last_char = string[-1]

# Replace the first and last characters


new_string = last_char + string[1:-1] + first_char

return new_string

# Example usage
input_string = "Hello"
new_string = exchange_first_last(input_string)

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 14
AKTU Python Programming KNC 402 session2021-22 solution

print("Original string:", input_string)


print("Modified string:", new_string)
b. W rite a Python program to add an item in a tuple. CO2
def add_to_tuple(tup, item):
# Convert the tuple to a list
list_tup = list(tup)

# Append the new item to the list


list_tup.append(item)

# Convert the list back to a tuple


new_tup = tuple(list_tup)

return new_tup

# Example usage
original_tuple = (1, 2, 3, 4)
new_item = 5
modified_tuple = add_to_tuple(original_tuple, new_item)
print("Original tuple:", original_tuple)
print("Modified tuple:", modified_tuple)

6. Attempt any one part of the following: 5*1 = 5

a. How to create and import a module in Python? CO2


To create and import a module in Python, you can follow these steps:

1. Create a Python File: Create a new Python file with a .py extension. This file will serve as
your module and contain the code you want to encapsulate.
2. Define Functions or Classes: Inside the module file, define the functions, classes, or
variables that you want to make accessible to other Python scripts. For example, you can
define a function called my_function:
def my_function():
print("Hello from my module!")

1. Save the Module: Save the module file with an appropriate name. For instance, if your
module file is named mymodule.py, make sure to save it as such.
2. Import the Module: In your Python script where you want to use the module, you can
import it using the import statement followed by the module name. For example:

import mymodule
This will import the entire module, and you can access its contents using the module
name as a prefix. For instance, you can call the my_function defined in the module like
this:
mymodule.my_function()

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 15
AKTU Python Programming KNC 402 session2021-22 solution

Output:
Hello from my module!
Alternatively, you can import specific functions or classes from the module using the from
statement. For example:
from mymodule import my_function
This allows you to directly use the imported function without referencing the module
name:
my_function()
Hello from my module!

By following these steps, you can create a module in Python and import it into other
scripts for reusability and organization of code. Remember to ensure that the module file
is located in the same directory as the script that is importing it, or in a directory listed in
the Python module search path.
b. E xplain the algorithm Sieve of Eratosthene used in Python Programming. CO2
The Sieve of Eratosthenes is an algorithm used to find all prime numbers up to a given
limit. It efficiently eliminates composite numbers by iteratively marking their multiples.
Here's how the algorithm works:

1. Create a list of Boolean values: Initialize a list is_prime of size n+1 (where n is the limit)
and set all values to True. This list will serve as a sieve to track the primality of numbers.
2. Mark multiples as non-prime: Start with the first prime number, 2. Mark all its multiples as
non-prime by setting their corresponding indices in the is_prime list to False. The
multiples of 2 are 4, 6, 8, 10, and so on.
3. Find the next prime number: Scan through the is_prime list to find the next number
greater than the current prime number that is marked as prime (i.e., its value in the
is_prime list is True). This number will be the next prime number.
4. Mark its multiples as non-prime: Repeat the process of marking multiples as non-prime
for the newly found prime number. Mark all the multiples of this prime number as non-
prime by setting their corresponding indices in the is_prime list to False.
5. Repeat steps 3 and 4: Continue steps 3 and 4 until there are no more numbers to consider
(i.e., all numbers up to the limit have been processed).
6. Retrieve the prime numbers: The prime numbers are the indices in the is_prime list that
are still marked as True. Collect these indices and store them as the prime numbers.

Here's an example Python program that implements the Sieve of Eratosthenes algorithm:

def sieve_of_eratosthenes(n):
is_prime = [True] * (n + 1) # Initialize sieve list
primes = [] # List to store prime numbers

# 0 and 1 are not prime numbers


is_prime[0] = is_prime[1] = False

p = 2 # Start with the first prime number

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 16
AKTU Python Programming KNC 402 session2021-22 solution

while p * p <= n:
if is_prime[p]:
# Mark all multiples of p as non-prime
for i in range(p * p, n + 1, p):
is_prime[i] = False
p += 1

# Collect prime numbers


for num in range(2, n + 1):
if is_prime[num]:
primes.append(num)

return primes

# Example usage
limit = 30
prime_numbers = sieve_of_eratosthenes(limit)
print("Prime numbers up to", limit, ":", prime_numbers)

Explanation:

 The sieve_of_eratosthenes function takes an integer n as input and returns a list


of prime numbers up to n.
 The is_prime list is initialized with True values for each index, indicating that all
numbers are initially assumed to be prime.
 The indices 0 and 1 in the is_prime list are set to False since they are not prime
numbers.
 The algorithm iteratively scans the is_prime list, starting with the first prime
number (p = 2), and marks all multiples of each prime number as non-prime.

7. Attempt any one part of the following: 5*1

a. Write a Recursive function in python BinarySearch(Arr,l,R,X) to search the given element X to be CO2
searched from the List Arr having R elements, where l represent slower bound and R represents the
upper bound.
def binary_search(arr, l, r, x):
# Check if the search range is valid
if r >= l:
mid = l + (r - l) // 2

# If the element is present at the middle


if arr[mid] == x:
return mid

# If the element is smaller than the middle element, search the left half

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 17
AKTU Python Programming KNC 402 session2021-22 solution

elif arr[mid] > x:


return binary_search(arr, l, mid - 1, x)

# If the element is larger than the middle element, search the right half
else:
return binary_search(arr, mid + 1, r, x)

# If the element is not present in the list


else:
return -1

# Example usage
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
x=5

result = binary_search(arr, 0, len(arr) - 1, x)

if result != -1:
print("Element", x, "found at index", result)
else:
print("Element", x, "not found in the list")
b. E xplain the terms Merge List and Merge Sort in Python Programming. CO2
In Python programming, the terms "Merge List" and "Merge Sort" are related to a sorting
algorithm called Merge Sort. Let's explain these terms in detail:

Merge List: A "Merge List" refers to the process of merging two sorted lists into a single
sorted list. In the context of Merge Sort, when dividing a list into smaller sublists, the
individual sublists are sorted independently. Then, during the merge step, these sorted
sublists are combined (or merged) together to form a larger sorted list.

Merge Sort: Merge Sort is a popular and efficient sorting algorithm that follows the
divide-and-conquer approach. It works by recursively dividing the list into smaller sublists,
sorting them, and then merging them back together to produce a sorted list. The steps of
the Merge Sort algorithm are as follows:

1. Divide: The list is divided into two halves until the sublists contain only one element or are
empty. This process is performed recursively.
2. Conquer: The individual sublists are sorted using the same Merge Sort algorithm. This
involves dividing each sublist further into smaller sublists and sorting them.
3. Merge: The sorted sublists are merged together to create a single sorted list. The merge
operation compares elements from the sublists and places them in the correct order.
4. Repeat: Steps 1 to 3 are repeated until the entire list is sorted.

The key step in Merge Sort is the merging of two sorted sublists into a single sorted list.
This is achieved by comparing the elements from each sublist and selecting the smallest

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 18
AKTU Python Programming KNC 402 session2021-22 solution

element to place in the merged list. The process continues until all elements from both
sublists are merged.

Merge Sort has a time complexity of O(n log n), making it an efficient sorting algorithm
for large datasets. It is stable (preserves the relative order of equal elements) and can
handle various data types.

Here's an example implementation of the Merge Sort algorithm in Python:

def merge_sort(arr):
if len(arr) <= 1:
return arr

# Divide the list into two halves


mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]

# Recursively sort the two halves


left_half = merge_sort(left_half)
right_half = merge_sort(right_half)

# Merge the sorted halves


return merge(left_half, right_half)

def merge(left, right):


merged = []
i=j=0

# Compare elements from the left and right halves and merge them
while i < len(left) and j < len(right):
if left[i] <= right[j]:
merged.append(left[i])
i += 1
else:
merged.append(right[j])
j += 1

# Append the remaining elements from either the left or right sublist
while i < len(left):
merged.append(left[i])
i += 1
while j < len(right):
merged.append(right[j])
j += 1

return merged

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 19
AKTU Python Programming KNC 402 session2021-22 solution

# Example usage
arr = [5, 3, 8, 2, 1, 9, 4, 7, 6]
sorted_arr = merge_sort(arr)
print("Sorted list:", sorted_arr)

Sorted list: [1, 2, 3, 4, 5, 6, 7, 8, 9]


In this example, the merge_sort function recursively divides the input list arr into smaller
halves and calls itself on each half. The base case is reached when the sublist contains only
one element or is empty. The merge function merges the sorted sub

Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 20
lOMoARcPSD|23934461

Python Programming KNC 302

Programming With Python -- (Dr. A.P.J. Abdul Kalam Technical University)

Studocu is not sponsored or endorsed by any college or university


Downloaded by Dr Aadarsh Malviya ([email protected])
lOMoARcPSD|23934461

Printed Page: 1 of 2
Subject Code: KNC302
0Roll No: 0 0 0 0 0 0 0 0 0 0 0 0 0

BTECH
(SEM III) THEORY EXAMINATION 2021-22
PYTHON PROGRAMMING
Time: 3 Hours Total Marks: 50
Note: Attempt all Sections. If you require any missing data, then choose suitably.

SECTION A
1. Attempt all questions in brief. 2*5 = 10
Qno Questions CO
(a) Explain the Programming Cycle for Python in detail. 1
(b) What will be the output of the following Python code? 2
i=0
while i< 3:
print(i)
i += 1
else:
print(0)
(c) What will be the output of the following Python code? 3
def cube(x):
return x * x * x

1
x = cube(3)

13
0
print x
29

(d) How do we define an Interface for an ADT? 4

2.
2_

(e) How do you perform a search in Python? 5

24
2P

5.
SECTION B

.5
P2

2. Attempt any three of the following: 5*3 = 15


17
Qno Questions CO
Q

|1

(a) What do you mean by Python IDE? Explain in detail. 1


(b) How can you randomize the items of a list in place in Python? 2
36

(c) Explain Tuples and Unpacking Sequences in Python Data Structure. 3


5:

(d) What are File input and output operations in Python Programming? 4
:2

(e) Solve the Tower of Hanoi problem for n= 3 disk and show all the steps. 5
13

SECTION C
2
02

3. Attempt any one part of the following: 5*1 = 5


Qno Questions CO
-2

(a) Write a program in Python to execute the Selection sort algorithm. 5


ar

(b) Explain why python is considered an interpreted language. 1


M
2-

4. Attempt any one part of the following: 5 *1 = 5


|2

Qno Questions CO
(a) Write a Python program to construct the following pattern, using a 2
nested for loop.

*
**
***
****
*****

QP22P2_290 | 22-Mar-2022 13:25:36 | 117.55.242.131


Downloaded by Dr Aadarsh Malviya ([email protected])
lOMoARcPSD|23934461

Printed Page: 2 of 2
Subject Code: KNC302
0Roll No: 0 0 0 0 0 0 0 0 0 0 0 0 0

BTECH
(SEM III) THEORY EXAMINATION 2021-22
PYTHON PROGRAMMING
****
***
**
*
(b) Write a program to produce Fibonacci series in Python. 4

5. Attempt any one part of the following: 5*1 = 5


Qno Questions CO
(a) Write a Python program to change a given string to a new string where 3
the first and last chars have been exchanged.
(b) Write a Python program to add an item in a tuple. 3

6. Attempt any one part of the following: 5*1 = 5


Qno Questions CO
(a) How to create and import a module in Python? 4
(b) Explain the algorithm Sieve of Eratosthene used in Python 4
Programming.

1
13
0
29

7. Attempt any one part of the following: 5*1 = 5

2.
2_

Qno Questions CO

24
(a) Write a Recursive function in python BinarySearch(Arr,l,R,X) to 5
2P

5.
search the given element X to be searched from the List Arr having R

.5
P2

elements, where l represent slower bound and R represents the upper 17


bound.
Q

(b) Explain the terms Merge List and Merge Sort in Python Programming. 5
|1
36
5:
:2
13
2
02
-2
ar
M
2-
|2

QP22P2_290 | 22-Mar-2022 13:25:36 | 117.55.242.131


Downloaded by Dr Aadarsh Malviya ([email protected])
Printed Page 1 of 2 Sub Code:KNC302
Paper Id: 199344 Roll No: 0 0 0 0 0 0 0 0 0 0 0 0 0

B. TECH.
(SEM III) THEORY EXAMINATION 2019-20
PYTHON PROGRAMMING
Time: 3 Hours Total Marks: 100
Note: 1. Attempt all Sections. If require any missing data; then choose suitably.
SECTION A

1. Attempt all questions in brief. 2 x 10 = 20


Qno. Question Marks CO
a. What is the difference between list and tuples in Python? 2 CO3

om
b. In some languages, every statement ends with a semi-colon (;). What 2 CO2
happens if you put a semi-colon at the end of a Python statement?
c. Mention five benefits of using Python. 2 CO4
d. How is Python an interpreted language? 2 CO2

c
e. What type of language is python? 2 CO1

s.
f. What are local variables and global variables in Python? 2 CO1
g. What is the difference between Python Arrays and lists? 2 CO3
h.
i.
j.
Define ADTinterface.
Define floor division with example.
on
Differentiate Fruitful functions and void functions.
2
2
2
CO4
CO5
CO3
iti
SECTION B
ttu

2. Attempt any three of the following: 3 x 10 = 30


Qno. Question Marks CO
en

a. Explain iterator. Write a program to demonstrate the tower of Hanoi 10 CO5


using function.
b. Discuss function in python with its parts and scope. Explain with 10 CO3
om

example. (Take Simple calculator with add, subtract, Division and


Multiplication).
c. Discuss ADT in python.How to define ADT? Write code for a student 10 CO4
information.
m

d. Explain all the Conditional statement in Python using small code 10 CO2
example.
st

e. What is Python? How Python is interpreted? What are the tools that help 10 CO1
to find bugs or perform static analysis? What are Python decorators?
la

SECTION C
3. Attempt any one part of the following: 1 x 10 = 10
Qno. Question Marks CO
a. Write short notes with example:The Programming Cycle for Python, 10 CO1
Elements of Python, Type Conversion in Python, Operator Precedence,
and Boolean Expression.
b. How memory is managed in Python? Explain PEP 8. Write a Python 10 CO1
program to print even length words in a string.

1|P a ge
Printed Page 2 of 2 Sub Code:KNC302
Paper Id: 199344 Roll No: 0 0 0 0 0 0 0 0 0 0 0 0 0

4. Attempt any one part of the following: 1 x 10 = 10


Qno. Question Marks CO
a. Explain Expression Evaluation & Float Representation with example. 10 CO2
Write a Python Program for How to check if a given number is
Fibonacci number.
b. Explain the purpose and working of loops. Discuss Break and continue 10 CO2
with example. Write a Python program to convert time from 12 hour to
24-hour format.

5. Attempt any one part of the following: 1 x 10 = 10

om
Qno. Question Marks CO
a. Explain higher order function with respect to lambda expression. Write a 10 CO3
Python code to Count occurrences of an element in a list.

c
b. Explain Unpacking Sequences, Mutable Sequences, and List 10 CO3

s.
Comprehension with example.Write a program to sort list of dictionaries
by values in Python – Using lambda function.

6.
Qno.
Attempt any one part of the following:
Question
on 1 x 10 = 10
Marks CO
iti
a. Discuss File I/O in python. How to perform open, read,write, and close 10 CO4
into a file? Write a Python program to read a file line-by-line store it into
ttu

a variable.
b. Discuss Exceptions and Assertions in python.How to handle Exceptions 10 CO4
with Try-Finally? Explain 5 Built-in Exceptions with example.
en

7. Attempt any one part of the following: 1 x 10 = 10


Qno. Question Marks CO
om

a. Discuss and differentiate Iterators & Recursion. Write a program for 10 CO5
Recursive Fibonacci series.
b. Discuss Sorting & Merging. Explain different types of sorting with 10 CO5
example.Write a Python Program for Sieve of Eratosthenes.
m
st
la

2|P a ge

You might also like