Ilovepdf Merged
Ilovepdf Merged
Python AKTU
(SEM III) THEORY EXAMINATION 2019-20
Solution
SUBJECT CODE: KNC-302
B.TECH.(CSE /CS IT/ CS AI ML) SEMESTER -IV
Affiliated to
.SECTION A
1. Attempt all questions in brief. 2 x 10 = 20
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.
# Lists
my_list = [1, 2, 3]
my_list[0] = 10
# 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
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.
# Using a semi-colon at the end of the statement (valid but not commonly used)
print("Hello"); # Output: Hello
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
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.
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.
Here are some key characteristics that define Python as a programming language:
Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 4
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution
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
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
print(x)
my_function() # Output: 15
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.
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.
# Using lists
my_list = [1, 2, 3]
my_list.append(4)
import numpy as np
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.
class StackInterface:
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):
def size(self):
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.
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 ( //).
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
Here are a few more examples to showcase the behavior of floor division:
print(15 // 4) # Output: 3
print(-10 // 3) # Output: -4
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.
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:
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):
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
if n > 0:
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.
Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 12
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution
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:
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
result = calculator('subtract', 5, 3)
print(result) # Output: 2
result = calculator('multiply', 5, 3)
print(result) # Output: 15
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.
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.
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 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
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.
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
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.
# 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
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.
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
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
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.
# 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.
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
# 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.
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:
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}
]
[{'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.
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.
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:
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:
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:
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:
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:
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.
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")
numbers = [1, 2, 3]
result = numbers + "abc"
numbers = [1, 2, 3]
result = numbers[4]
Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 29
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution
result = 10 / 0
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:
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:
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
*
**
***
****
*****
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
Affiliated to
.SECTION A
1. Attempt all questions in brief. 2*5 = 10
Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 1
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2021-22 solution
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
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.
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
String Search:
To search for a substring within a string, you can use the find() method.
index = my_string.find("World")
print(index) # Output: 7
Dictionary Search:
If you have a dictionary and want to check if a key exists, you can use the in
operator
To retrieve the value associated with a key in a dictionary, you can use square brackets.
value = my_dict["name"]
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
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:
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.
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]
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.
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
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.
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 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
# Slicing
print(my_tuple[1:]) # Output: ('Hello', 3.14)
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_string = 'Hello'
a, b, c, d, e = my_string
Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 9
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2021-22 solution
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:
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).
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
# 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.
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
Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 13
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2021-22 solution
return fib_series
# Example usage
num_terms = 10
fibonacci_series = fibonacci(num_terms)
print("Fibonacci series up to", num_terms, "terms:", fibonacci_series)
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
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
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)
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
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
return primes
# Example usage
limit = 30
prime_numbers = sieve_of_eratosthenes(limit)
print("Prime numbers up to", limit, ":", prime_numbers)
Explanation:
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 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)
# Example usage
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
x=5
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
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.
def merge_sort(arr):
if len(arr) <= 1:
return arr
# 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)
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
Affiliated to
.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.
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():
class MyClass:
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:
"""
Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 2
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution
"""
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.
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:
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)
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
list2 = []
average1 = ComputeAverage(list1)
average2 = ComputeAverage(list2)
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
Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 5
AKTU Python Programming KNC 302 session THEORY EXAMINATION 2019-20 solution
# 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")
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.
# 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
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.
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
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.
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.
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.
print("Before swapping:")
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:")
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.
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().
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.")
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
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.
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.
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.
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
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")
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
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
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.
Regarding the built-in exceptions, here are brief explanations of two commonly used
exceptions:
ValueError: This exception is raised when a function receives an argument of the correct
type but an inappropriate value. For example:
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:
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)
In this example, the math module is imported, and the sqrt() function from the module is
used to calculate the square root of 25.
result = sqrt(16)
circumference = 2 * pi * 5
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
import numpy as np
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.
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.
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
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.
n = len(arr)
for i in range(n):
# Find the minimum element in the remaining unsorted portion of the array
min_idx = i
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
return arr
# Example usage:
sorted_nums = selection_sort(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.
This demonstrates the selection sort algorithm sorting the given array in ascending order.
c. What are different types of inheritance supported by Python? Explain.
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):
def parent_method(self):
print("Parent method")
class Child(Parent):
def __init__(self):
super().__init__()
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")
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
Affiliated to
.SECTION A
1. Attempt all questions in brief. 2*5 = 10
Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 1
AKTU Python Programming KNC 402 session2021-22 solution
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()
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.
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
String Search:
To search for a substring within a string, you can use the find() method.
index = my_string.find("World")
print(index) # Output: 7
Dictionary Search:
If you have a dictionary and want to check if a key exists, you can use the in
operator
To retrieve the value associated with a key in a dictionary, you can use square brackets.
value = my_dict["name"]
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:
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
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
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]
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.
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.
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 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
# Slicing
print(my_tuple[1:]) # Output: ('Hello', 3.14)
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_string = 'Hello'
a, b, c, d, e = my_string
Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 9
AKTU Python Programming KNC 402 session2021-22 solution
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:
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).
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
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
# 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.
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
Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 13
AKTU Python Programming KNC 402 session2021-22 solution
return fib_series
# Example usage
num_terms = 10
fibonacci_series = fibonacci(num_terms)
print("Fibonacci series up to", num_terms, "terms:", fibonacci_series)
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
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
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)
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
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
return primes
# Example usage
limit = 30
prime_numbers = sieve_of_eratosthenes(limit)
print("Prime numbers up to", limit, ":", prime_numbers)
Explanation:
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 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
# If the element is larger than the middle element, search the right half
else:
return binary_search(arr, mid + 1, r, x)
# Example usage
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
x=5
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.
def merge_sort(arr):
if len(arr) <= 1:
return arr
# 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)
Dr. AAdarsh Malviya Department of CSE, Dronacharya Group of Institutions- DGI Page 20
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
2.
2_
24
2P
5.
SECTION B
.5
P2
|1
(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
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
1
13
0
29
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
(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
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
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
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
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
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