0% found this document useful (0 votes)
7 views33 pages

ETE Python Question 1 To 25

The document discusses various aspects of Python programming, including its simplicity compared to Java and C, the functionality of the random.seed() function, and the pickle module for object serialization. It also covers Python operators, specifically relational and logical operators, and provides examples of list manipulations and polymorphism in object-oriented programming. The content is structured as a series of questions and answers, providing detailed explanations and code examples for each topic.

Uploaded by

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

ETE Python Question 1 To 25

The document discusses various aspects of Python programming, including its simplicity compared to Java and C, the functionality of the random.seed() function, and the pickle module for object serialization. It also covers Python operators, specifically relational and logical operators, and provides examples of list manipulations and polymorphism in object-oriented programming. The content is structured as a series of questions and answers, providing detailed explanations and code examples for each topic.

Uploaded by

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

ETE PYTHON Question 1 to 25

Ques 1: Identify how python language is more simple other than Java and C. Give proper example.

Ans 1: Python is often considered a simpler language compared to Java and


C for several reasons. Here are some key factors that contribute to
Python's simplicity, along with examples:

1. Concise Syntax: Python has a clean and readable syntax that allows
developers to express concepts in fewer lines of code compared to
Java and C. For example, let's compare a basic "Hello, World!"
program in Python, Java, and C:
Python:
print("Hello, World!")

java:
class HelloWorld {

public static void main(String[] args) {


System.out.println("Hello, World!");
}
}

C:
#include <stdio.h>

int main() {
printf("Hello, World!\n");
return 0;
}}
In Python, the code is straightforward and requires only one
line. In Java and C, additional syntax and boilerplate code
are necessary.
1. Dynamic Typing: Python uses dynamic typing, which means
you don't have to declare variable types explicitly. This
flexibility simplifies code writing and allows for more concise
programs. For example:
Python:
x=x= x=5

x = "Hello"

Java:
int x = 5;
x = "Hello"; // Error: Incompatible typesError: Incompatible types
In Python, the variable x can hold different types without
explicitly specifying them. In Java, you need to declare the
type of x and cannot assign a string value later.
2. Built-in Data Structures and Libraries: Python comes with
built-in data structures like lists, dictionaries, and sets, as
well as a rich collection of libraries for various tasks. These
built-in features simplify common programming tasks and
reduce the need for writing complex data structures or
implementing algorithms from scratch. For example, let's
compare sorting a list of integers in Python and Java:
Python:
numbers = [3, 1, 4, 1, 5, 9]
sorted_numbers = sorted(numbers)
print(sorted_numbers)
Java:
import java.util.Arrays;

public class SortExample {


public static void main(String[] args) {
int[] numbers = {3, 1, 4, 1, 5, 9};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));
}
} (numbers)); } }
In Python, the sorted() function provides a simple way to sort
a list. In Java, you need to import a utility class, create an
array, and call a sorting method, making the code more
complex.

These examples demonstrate some of the ways Python simplifies


programming by offering concise syntax, dynamic typing, and
built-in features. However, it's important to note that the choice of
language depends on the specific requirements of a project, and
Java and C have their own strengths in different domains, such as
performance or low-level system programming.

Ques 2: Explain the working of random.seed() function

Ans 2: The random.seed() function in Python is used to initialize the


random number generator. It allows you to specify a starting point for
generating random numbers, ensuring that the sequence of random
numbers remains the same across multiple runs of a program, given the
same seed value. This function is part of the random module in Python's
standard library.

Here's an explanation of how random.seed() works:

1. Generating Random Numbers: Python's random module provides


various functions to generate random numbers. These functions use
a random number generator algorithm that produces a sequence of
seemingly unpredictable numbers.
2. Pseudo-random Number Generation: The random number generator
used in Python is known as a "pseudo-random number generator"
(PRNG). It means that the generated sequence is deterministic and
not truly random. The sequence is generated based on an initial
value called the seed.
3. Initializing the Seed: By calling random.seed(), you can specify the
seed value for the random number generator. This ensures that the
subsequent random numbers generated will follow the same
sequence each time the program runs with the same seed value.
4. Using Default Seed: If you call random.seed() without passing any
arguments, it uses the current system time as the seed value. This
results in a different sequence of random numbers on each program
run.
5. Reproducibility: To achieve reproducibility, you can explicitly pass a
specific seed value to random.seed(). By using the same seed value,
you can generate the same sequence of random numbers across
different runs of your program. This can be useful when you need to
debug or test a program that involves randomness, as it allows you
to reproduce specific scenarios.

Ques 3: ( a) Apply a comprehensive explanation of pickle module in Python and list out advantages
and limitations of using pickle to write binary files in Python.

(b) Explain what is range() function and how it is used in lists?

Ans 3: (a) The pickle module in Python provides a way to serialize and
deserialize Python objects. Serialization is the process of converting an
object into a byte stream, which can be written to a file or transmitted
over a network. Deserialization is the reverse process, where the byte
stream is converted back into an object.

Here's a comprehensive explanation of the pickle module:

1. Serializing Objects: The pickle module allows you to serialize Python


objects by converting them into a binary representation. You can
use the pickle.dump() function to write the serialized object to a file-
like object, such as a file or a network socket.
2. Deserializing Objects: The pickle module also provides the
pickle.load() function, which allows you to deserialize the binary
data and reconstruct the original Python object. This function reads
the serialized data from a file-like object and returns the
deserialized object.
3. Handling Complex Objects: pickle can handle various types of
Python objects, including built-in types (e.g., integers, lists,
dictionaries) and user-defined classes. It automatically handles
object references and retains their relationships during serialization
and deserialization.
4. Advantages of Using Pickle:
 Easy to Use: The pickle module provides a straightforward
way to serialize and deserialize objects without requiring
complex code.
 Retains Object Structure: Pickle preserves the structure and
relationships of objects, including references between objects,
making it suitable for handling complex data structures.
 Supports Custom Classes: You can serialize and deserialize
user-defined classes and their instances without writing
custom serialization code.
 Efficient Binary Format: Pickle uses a compact binary format,
which can be more space-efficient compared to other
serialization formats like JSON or XML.
5. Limitations of Using Pickle:
 Python-Specific: Pickle is specific to Python and may not be
compatible with other programming languages.
 Security Risks: Untrusted pickle data can potentially execute
arbitrary code during deserialization, making it a security risk.
It's important to only unpickle data from trusted sources.
 Version Compatibility: Pickle files can be affected by changes
in Python versions, making it difficult to deserialize objects if
the Python version or object structure has changed.

It's worth noting that there are alternative serialization libraries in Python,
such as JSON, MessagePack, or Protocol Buffers, which may offer different
advantages and limitations compared to pickle. The choice of serialization
method depends on factors like data portability, performance, and
security requirements.

(b) The range() function in Python is used to generate a sequence of


numbers within a specified range. It is commonly used in lists, loops, and
other situations where you need to iterate over a sequence of numbers.

Here's an explanation of how the range() function works in lists:

1. Syntax: The range() function has three different forms:


 range(stop) : Generates a sequence of numbers starting from 0
up to (but not including) the specified stop value.
 range(start, stop): Generates a sequence of numbers starting
from the specified start value up to (but not including) the
specified stop value.
 range(start, stop, step) : Generates a sequence of numbers
starting from the specified start value up to (but not including)
the specified stop value, incrementing by the specified step
value.
2. Generating a List of Numbers: The range() function is often used to
generate a list of numbers. You can convert the range object to a
list using the list() function. For example:
numbers = list(range(1, 6))
print(numbers) # Output: [1, 2, 3, 4, 5]
``

Ques 4: List the operators that python supports. Explain the relational and logical operators along
with their precedence while evaluating an expression.

Ans 4: Python supports a wide range of operators that allow you to perform
various operations on different types of data. Here is a list of operators in
Python:

1. Arithmetic Operators:
 Addition: +
 Subtraction: -
 Multiplication: *
 Division: /
 Floor Division: //
 Modulus (Remainder): %
 Exponentiation: **
2. Assignment Operators:
 Assignment: =
 Addition Assignment: +=
 Subtraction Assignment: -=
 Multiplication Assignment: *=
 Division Assignment: /=
 Floor Division Assignment: //=
 Modulus Assignment: %=
 Exponentiation Assignment: **=
3. Comparison (Relational) Operators:
 Equal to: ==
 Not equal to: !=
 Greater than: >
 Less than: <
 Greater than or equal to: >=
 Less than or equal to: <=
4. Logical Operators:
 Logical AND: and
 Logical OR: or
 Logical NOT: not
5. Bitwise Operators:
 Bitwise AND: &
 Bitwise OR: |
 Bitwise XOR: ^
 Bitwise NOT: ~
 Left Shift: <<
 Right Shift: >>
6. Membership Operators:
 in: Returns True if a value is found in a sequence
 not in: Returns True if a value is not found in a sequence
7. Identity Operators:
 is: Returns True if two variables refer to the same object
 is not: Returns True if two variables do not refer to the same
object
8. Unary Operators:
 Positive: +
 Negative: -

Relational operators are used to compare values and return a Boolean


result (True or False). Logical operators are used to combine or
manipulate Boolean values. Here's a brief explanation of relational and
logical operators:

 Relational Operators:
 Relational operators compare two values and return a Boolean
result based on the comparison.
 Relational operators have a lower precedence than arithmetic
and logical operators.
 Relational operators evaluate in the following order: <=, <, >,
>=, ==, !=.
 When evaluating an expression, relational operators are
typically used to compare values and determine conditions for
control structures (e.g., if statements, loops).
 Logical Operators:
 Logical operators are used to combine or negate Boolean
values.
 Logical operators have lower precedence than arithmetic
operators but higher precedence than relational operators.
 Logical operators evaluate in the following order: not, and, or.
 not is evaluated first, followed by and , and then or.
 Logical operators are commonly used in conditions to evaluate
multiple conditions and determine the overall truth value.

For example, consider the following expression:

result = (a > 5 and b < 10) or (c == 0)

In this expression, the relational operators ( >, <, ==) compare the values of
variables a, b, and c. The logical operators ( and, or) combine the results of
these comparisons to evaluate the overall expression. The precedence of the
operators ensures that the evaluations are performed correctly.

Ques 5: (a) Show the value of L after you run the code below?

L = ["life", "answer", 42, 0]

for thing in L:

if thing == 0:
L[thing] = "universe"

elif thing == 42:

L[1] = "everything"

(b) Show the value of L3 after you execute all the operations in the code below?

L1 = ['re']

L2 = ['mi']

L3 = ['do']

L4 = L1 + L2

L3.extend(L4)

L3.sort()

del(L3[0])

L3.append(['fa','la'])

Ans 5: (a) The corrected version of the code you provided is as follows:
L = ["life", "answer", 42, 0]
for thing in L:
if thing == 0:
L[thing] = "universe"
elif thing == 42:
L[1] = "everything"

After running this code, the value of L will be ['life', 'everything', 42,
'universe'].

Explanation:

 The loop iterates over each element in the list L.


 When thing is equal to 0, L[thing] (i.e., L[0]) is updated to
"universe".
 When thing is equal to 42, L[1] is updated to "everything".
 The resulting updated list is ['life', 'everything', 42, 'universe'] .

(b) After executing all the operations in the code provided, the value of L3
will be ['do', 'fa', 'la', 'mi', 're'] .

Explanation:

 Initially, L3 is ['do'].
 L4 is formed by concatenating L1 and L2, resulting in ['re', 'mi'].
 L3.extend(L4) extends L3 by appending all elements of L4 to it. L3
becomes ['do', 're', 'mi'] .
 L3.sort() sorts the elements of L3 in ascending order. After sorting,
L3 becomes ['do', 'mi', 're'] .
 del(L3[0]) deletes the first element of L3, resulting in ['mi', 're'].
 L3.append(['fa', 'la']) appends the list ['fa', 'la'] as a single element
at the end of L3. The final value of L3 is ['mi', 're', ['fa', 'la']] .

Ques 6: Categorize and discuss the types of Polymorphism in details with proper example

Ques 6: Polymorphism is a fundamental concept in object-oriented


programming (OOP) that allows objects of different classes to be treated
as objects of a common superclass. It provides a way to write code that
can work with objects of various types, offering flexibility and extensibility
to software systems. In this discussion, I'll categorize and explain the two
main types of polymorphism: compile-time (or static) polymorphism and
runtime (or dynamic) polymorphism.

1. Compile-time Polymorphism: Compile-time polymorphism is


achieved through function overloading and operator overloading. It
is determined during the compilation phase, where the appropriate
function or operator implementation is selected based on the types
and number of arguments. Let's explore each form:
a. Function Overloading: Function overloading allows multiple
functions with the same name but different parameters to exist in a
class. The compiler determines the appropriate function to call
based on the arguments used. Consider the following example:

class Calculator {
public:
int add(int a, int b) {
return a + b;
}

double add(double a, double b) {


return a + b;
}
};

int main() {
Calculator calc;
int result1 = calc.add(2, 3);
double result2 = calc.add(2.5, 3.7);
// ...
}

In the above example, the add function is overloaded with different


parameter types (integers and doubles). Depending on the argument
types used, the appropriate add function is called at compile time.
b. Operator Overloading: Operator overloading enables the use of
operators (+, -, *, etc.) with user-defined types. It allows defining how
operators should behave when applied to objects of a class. Here's an
example using the addition operator:

class Vector2D {
public:
int x;
int y;

Vector2D operator+(const Vector2D& other) {


Vector2D result;
result.x = this->x + other.x;
result.y = this->y + other.y;
return result;
}
};

int main() {
Vector2D v1{2, 3};
Vector2D v2{4, 1};
Vector2D v3 = v1 + v2; // Operator overloading
// ...
}

In this example, the addition operator is overloaded for the Vector2D class,
allowing two Vector2D objects to be added using the + operator.

b. Runtime Polymorphism: Runtime polymorphism is achieved through


inheritance and virtual functions. It allows different classes to have the
same function names, but with different implementations. The selection of
the appropriate function occurs dynamically at runtime, based on the
actual type of the object being referred to. Let's explore the key aspects:
a. Inheritance: Inheritance allows a class to inherit properties and
behaviors from another class, establishing an "is-a" relationship.
Polymorphism is often associated with inheritance as it enables a derived
class to be treated as its base class. Consider the following example:
class Shape {
public:
virtual void draw() {
// Default implementation
}
};

class Circle : public Shape {


public:
void draw() override {
// Implementation for drawing a circle
}
};

class Square : public Shape {


public:
void draw() override {
// Implementation for drawing a square
}
};

int main() {
Shape* shape1 = new Circle();
1. Shape

Ques 7 : Analyze a Numpy array filled with all zeros. (b) Analyze reverse a
Numpy array.

Ans 7: (a) Analyzing a Numpy array filled with all zeros: A Numpy array is a
grid of values, all of the same type, and is indexed by a tuple of
nonnegative integers. When an array is filled with all zeros, it means that
every element in the array has a value of zero. Here are some key aspects
to consider:

 Creating a Numpy array filled with zeros: To create a Numpy array


filled with zeros, you can use the numpy.zeros() function. This
function takes the desired shape of the array as an argument and
returns a new array with all elements initialized to zero. Here's an
example:
 import numpy as np

 zeros_array = np.zeros((3, 4))
 print(zeros_array)

output:

[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]

 Properties of the zeros array:


 Shape: The shape of the zeros array determines the number
of rows and columns it contains. In the above example, the
shape is (3, 4), indicating 3 rows and 4 columns.
 Data type: By default, the numpy.zeros() function creates an
array of floating-point numbers. However, you can specify the
desired data type using the dtype parameter. For example,
np.zeros((3, 4), dtype=int) creates an array of integers filled
with zeros.
 Memory usage: The zeros array occupies memory space to
store all the zero values. The memory required depends on
the shape and data type of the array.
 Use cases:
 Initializing arrays: Creating an array filled with zeros is useful
when you want to initialize an array of a specific size before
populating it with actual values.
 Placeholder array: A zeros array can be used as a placeholder
in calculations or as an initial state for iterative algorithms.
(b) Analyzing reversing a Numpy array: Reversing a Numpy array involves
changing the order of its elements, flipping it horizontally or vertically.
Here's the analysis:

 Reversing a Numpy array using indexing: To reverse a Numpy array,


you can use indexing and slicing. By specifying a step value of -1,
you can reverse the order of elements. Here's an example:
 import numpy as np

 original_array = np.array([1, 2, 3, 4, 5])
 reversed_array = original_array[::-1]
 print(reversed_array)

 output:

[5 4 3 2 1]

Reversing a Numpy array along a specific axis: Numpy arrays can have multiple
dimensions. To reverse the array along a particular axis, you can use the
numpy.flip() function. It takes the array and the axis along which you want to flip
as arguments. Here's an example:

import numpy as np

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


reversed_array = np.flip(original_array, axis=0)
print(reversed_array)

output:

[[4 5 6]
[1 2 3]]

Use cases:
 Data manipulation: Reversing an array can be useful for data
manipulation tasks, such as reversing the order of elements in time
series data or reversing the order of images in computer vision
applications.
 Algorithmic operations: Reversing arrays

Ques 8 :Assuming the instructions given below, write a simple program


using a class()  A base class Person and a derived class Student
with Person as its base class.  Add two methods setname() (which
takes the parameter self and name)and getname() which prints the name
in the base class.  Add two methods in the derived class: setage()
(which takes the parameters self and age) which sets the age and
getage() which prints the age.  Create an instance of Student and
name it as s1.  Take name and age as inputs from the console.  Call
the setname() and setage() on this instance by passing the name and
age parameters.  Call the getname() and getage() on this class,
which prints the passed parameters
Ans 8: class Person:
def setname(self, name):
self.name = name

def getname(self):
print("Name:", self.name)

class Student(Person):
def setage(self, age):
self.age = age

def getage(self):
print("Age:", self.age)

s1 = Student()

name = input("Enter name: ")


age = input("Enter age: ")

s1.setname(name)
s1.setage(age)

s1.getname()
s1.getage()

In this program, we define a base class Person and a derived class


Student that inherits from Person. The Person class has setname() and
getname() methods to set and print the name, respectively. The Student
class extends Person and adds setage() and getage() methods to set and
print the age, respectively.

We create an instance of the Student class called s1. Then, we take inputs
from the console for the name and age. We call setname() and setage() on
the s1 instance, passing the name and age parameters. Finally, we call
getname() and getage() on the s1 instance to print the entered name and
age.

Quest 9 : n this program, we start by asking the user to enter their


percentage mark using the input() function. The input is converted to a
float using float() since percentage marks can include decimal values.

We then use a series of if-elif-else statements to determine the module


grade based on the percentage mark entered. Each condition checks the range
of the percentage mark and assigns the corresponding grade to the grade
variable.

If the percentage mark is 70 or above, the grade is set to "Distinction".


If the percentage mark is between 60 and 69 (inclusive), the grade is set
to "Merit".

If the percentage mark is between 40 and 59 (inclusive), the grade is set


to "Pass".

If the percentage mark is less than 40, the grade is set to "Fail".

Finally, we print the module grade using the grade variable.

Ans 9: Certainly! Here's a Python program that imports the abs() function from the
built-in module, displays its documentation, and finds the absolute value of -155:

import builtins

# Displaying documentation of abs() function


print("Documentation of abs() function:")
print(builtins.abs.__doc__)

# Finding the absolute value of -155


number = -155
absolute_value = abs(number)
print("Absolute value of", number, "is", absolute_value)

In this program, we import the builtins module, which provides a


collection of built-in functions and exceptions in Python. We access the
abs() function from the builtins module using builtins.abs .

To display the documentation of the abs() function, we use the __doc__


attribute of the function. It contains the docstring, which provides
information about the function's usage and parameters.

After that, we define a variable number and assign it the value -155. To
find the absolute value of number, we call abs(number) and store the
result in the absolute_value variable.

Finally, we print the documentation of the abs() function and the absolute
value of -155 using the absolute_value variable.

Ques 10:Develop a python program that asks users to enter their percentage
mark for a module of

study. The program prints the module grade as either distinction, merit,
pass or fail

depending on the percentage mark entered.

I. A mark of 70% and above is awarded a distinction.

II. A mark in the range of 60% through to 69% is awarded a merit.


III. A mark in the range of 40% through to 59% is awarded a pass.

IV. Marks less than 40% are awarded a fail

Ans 10: Certainly! Here's a Python program that asks the user to enter their percentage mark
for a module of study and prints the corresponding module grade based on the provided
criteria:

hpercentage = float(input("Enter your percentage mark: "))

if percentage >= 70:


grade = "Distinction"
elif 60 <= percentage <= 69:
grade = "Merit"
elif 40 <= percentage <= 59:
grade = "Pass"
else:
grade = "Fail"

print("Module Grade:", grade)

n this program, we start by asking the user to enter their percentage mark
using the input() function. The input is converted to a float using float()
since percentage marks can include decimal values.

We then use a series of if-elif-else statements to determine the module


grade based on the percentage mark entered. Each condition checks the
range of the percentage mark and assigns the corresponding grade to the
grade variable.

 If the percentage mark is 70 or above, the grade is set to


"Distinction".
 If the percentage mark is between 60 and 69 (inclusive), the grade
is set to "Merit".
 If the percentage mark is between 40 and 59 (inclusive), the grade
is set to "Pass".
 If the percentage mark is less than 40, the grade is set to "Fail".

Finally, we print the module grade using the grade variable.

Ques 11: a) Assume fruits = ("apple", "banana", "cherry", "orange", "kiwi",


"melon", "mango")

write the print statement using a range of indexes to print the third,
fourth, and fifth item

in the tuple.
(b) Assume fruits = ("apple", "banana", "cherry") write the python code
using negative

indexing to print the last item in the tuple

ans 11 : (a) To print the third, fourth, and fifth items in the fruits tuple using a range of
indexes, you can use the following print statement:

fruits = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")

# Print the third, fourth, and fifth items


print(fruits[2:5])

output:

('cherry', 'orange', 'kiwi')

In Python, indexing starts from 0, so the third item has an index of 2, the
fourth item has an index of 3, and the fifth item has an index of 4. By
using the range of indexes [2:5], we specify to print items starting from
index 2 up to, but not including, index 5.

(b) To print the last item in the fruits tuple using negative indexing, you
can use the following Python code

fruits = ("apple", "banana", "cherry")

# Print the last item


print(fruits[-1])

output:

cherry

In Python, negative indexing allows you to access elements from the end of a sequence.
The last item in the tuple has an index of -1, so using fruits[-1] retrieves the last item
from the tuple.

Ques 12: A permutation is simply a name for a reordering. So the


permutations of the string „abc‟ are „abc‟, „acb‟, „bac‟, „bca‟, „cab‟, and
„cba‟. Note that a sequence is a permutation of itself (the trivial
permutation). Take the permutation of the string in the list and write
python program for a recursive function (get_permutations) that takes a
string and returns a list of all its permutations

Ans 12 : To generate all permutations of a given string using a recursive function in


Python, you can implement a recursive algorithm known as backtracking. Here's an
example program that defines a function called get_permutations :

def get_permutations(string):
# Base case: If the string is empty or has only one character, return the string
itself as a single permutation
if len(string) <= 1:
return [string]

# List to store permutations


permutations = []

# Iterate through each character in the string


for i in range(len(string)):
# Extract the current character
current_char = string[i]

# Generate all permutations of the remaining characters


remaining_chars = string[:i] + string[i + 1:]
sub_permutations = get_permutations(remaining_chars)

# Append the current character to each permutation of the remaining


characters
for sub_permutation in sub_permutations:
permutations.append(current_char + sub_permutation)

# Return the list of permutations


return permutations

# Test the get_permutations function


string = "abc"
permutations = get_permutations(string)
print(permutations)

output:

['abc', 'acb', 'bac', 'bca', 'cab', 'cba']

In this program, the get_permutations function takes a string as input and


returns a list of all its permutations. It follows the recursive backtracking
approach to generate the permutations.

The function starts with a base case: if the length of the string is less than
or equal to 1, it returns the string itself as a single permutation.

For strings with more than one character, the function iterates through
each character in the string. It extracts the current character and
generates all permutations of the remaining characters recursively by
calling get_permutations on the remaining substring.

Then, for each sub-permutation, the current character is appended to it,


and the resulting permutation is added to the permutations list.

Finally, the list of permutations is returned.


In the provided example, when the input string is "abc", the function
generates all possible permutations of the string and returns ['abc', 'acb',
'bac', 'bca', 'cab', 'cba'] .

. ques 13 :Explain different rules about to define an identifier in python.


If the age of Ram, Sam, and Khan are input through the keyboard, write a
python program to determine the eldest and youngest of the three.

Ans 13: In Python, identifiers are used to name variables, functions, classes,
modules, and other objects. Here are the rules for defining identifiers in
Python:

1. Valid characters: Identifiers can consist of letters (both lowercase


and uppercase), digits, and underscores (_). However, they must
start with a letter or an underscore.
2. Case sensitivity: Python is case-sensitive, so identifiers like
"myVariable" and "myvariable" are considered different.
3. Length: Identifiers can be of any length.
4. Reserved words: You cannot use reserved words (keywords) as
identifiers. For example, you cannot use "if", "for", "while", or "def"
as variable names.
5. PEP 8 style guide: It is recommended to follow the Python
Enhancement Proposal 8 (PEP 8) style guide for naming
conventions. It suggests using lowercase letters and underscores for
variable and function names (e.g., my_variable), and using
uppercase letters for class names (e.g., MyClass).
6. Meaningful names: It is good practice to choose meaningful and
descriptive names for your identifiers to enhance code readability.

Now, let's write a Python program to determine the eldest and youngest
among Ram, Sam, and Khan based on their ages:

ram_age = int(input("Enter Ram's age: "))


sam_age = int(input("Enter Sam's age: "))
khan_age = int(input("Enter Khan's age: "))

# Determine the eldest


if ram_age >= sam_age and ram_age >= khan_age:
eldest = "Ram"
elif sam_age >= ram_age and sam_age >= khan_age:
eldest = "Sam"
else:
eldest = "Khan"

# Determine the youngest


if ram_age <= sam_age and ram_age <= khan_age:
youngest = "Ram"
elif sam_age <= ram_age and sam_age <= khan_age:
youngest = "Sam"
else:
youngest = "Khan"

# Print the results


print("Eldest:", eldest)
print("Youngest:", youngest)

In this program, we first take the input of ages for Ram, Sam, and Khan
using the input() function and convert them to integers using int().

To determine the eldest, we compare the ages using if and elif conditions.
If Ram's age is greater than or equal to both Sam's and Khan's ages, Ram
is considered the eldest, and so on.

Similarly, to determine the youngest, we compare the ages using if and


elif conditions. If Ram's age is less than or equal to both Sam's and Khan's
ages, Ram is considered the youngest, and so on.

Finally, we print the results using the print() function.

ques 14: Write a Python program to find the exponentiation of a number

ans 14: python code

base = float(input("Enter the base number: "))


exponent = int(input("Enter the exponent: "))

result = base ** exponent

print("Result:", result)

In this program, we take the input of the base number using input() and
convert it to a float using float(). We also take the input of the exponent
and convert it to an integer using int().

We calculate the exponentiation using the ** operator, where the base is


raised to the power of the exponent. The result is stored in the result
variable.

Finally, we print the result using the print() function.

.Ques 15: Identify the string method used to implement the following. I. To count the
number of characters in the string.

II. To change the first character of the string in capital letter.

Ans 15: I. To count the number of characters in a string, you can use the
string method len(). Here's an example:
text = "Hello, World!"

# Count the number of characters in the string


count = len(text)

print("Number of characters:", count)

output:

Number of characters: 13

In this example, len(text) returns the length of the string text, which
represents the number of characters in the string.

ii part . To change the first character of a string to uppercase, you can use
the string method capitalize(). Here's an example:

text = "hello, world!"

# Change the first character to uppercase


modified_text = text.capitalize()

print("Modified string:", modified_text)

output:

Modified string: Hello, world!

in this example, text.capitalize() returns a new string where the first


character of text is changed to uppercase. The rest of the characters
remain unchanged.

It's important to note that the capitalize() method only capitalizes the first
character of the string. If you want to capitalize all the words in a string,
you can use the title() method instead.

Ques 16: Define SciPy, Scrapy, Scikit-learn, PyGame, PyTorch, PyBrain and Keras.
Ans 16:
1. SciPy:
 SciPy is an open-source library for scientific computing in
Python.
 It provides functionality for numerical integration,
optimization, interpolation, linear algebra, statistics, signal
processing, and more.
 SciPy builds on top of NumPy, another popular Python
library, and provides additional tools for scientific and
technical computing.
2. Scrapy:
 Scrapy is an open-source web scraping framework written in
Python.
 It provides a high-level API for extracting data from websites
and web pages.
 Scrapy allows you to define how to navigate websites,
extract data from HTML or XML documents, and store the
scraped data.
3. Scikit-learn:
 Scikit-learn (or sklearn) is a machine learning library for
Python.
 It provides a wide range of algorithms and tools for various
machine learning tasks such as classification, regression,
clustering, and dimensionality reduction.
 Scikit-learn is built on top of other scientific computing
libraries such as NumPy and SciPy and is known for its user-
friendly and consistent API.
4. PyGame:
 PyGame is a cross-platform set of Python modules designed
for game development.
 It provides functionality for creating 2D games and
multimedia applications.
 PyGame abstracts low-level details and provides a high-level
interface for game development, including handling
graphics, input events, sound, and more.
5. PyTorch:
 PyTorch is an open-source machine learning framework
primarily developed by Facebook's AI Research lab (FAIR).
 It provides a flexible and dynamic approach to building and
training neural networks.
 PyTorch allows for easy experimentation, supports dynamic
computation graphs, and has gained popularity in the field
of deep learning.
6. PyBrain:
 PyBrain is a library for machine learning and artificial
intelligence in Python.
 It provides tools and algorithms for various machine learning
tasks, including neural networks, reinforcement learning,
unsupervised learning, and more.
 PyBrain aims to be a simple and easy-to-use library for
educational purposes and rapid prototyping.
7. Keras:
 Keras is a high-level deep learning library written in Python.
 It provides a user-friendly and modular API for building and
training deep neural networks.
 Keras is known for its simplicity and ease of use, making it a
popular choice for beginners and experienced researchers
alike.
 It can run on top of other machine learning frameworks such
as TensorFlow and Theano.

Ques 17: (a) Show the output of the following Python code?

d = {"john":40, "peter":45}

d["john"]

b) Is tuple comparison possible? Explain how with example.

Ans 17: The output of the following Python code would be:
d = {"john": 40, "peter": 45}

print(d["john"])

output:

40

In this code, a dictionary d is defined with key-value pairs. The key "john"
has a corresponding value of 40. By accessing d["john"], we retrieve the
value associated with the key "john" from the dictionary, which is 40.
Hence, the output is 40.

(b) Yes, tuple comparison is possible in Python. Tuples can be compared


using the comparison operators ( <, <=, >, >=, ==, !=) just like other
types of objects.

When comparing tuples, the comparison is performed element-wise,


starting from the first element of each tuple. If the first elements of the
tuples are equal, the comparison moves on to the second elements, and
so on. The comparison stops as soon as a mismatch is found or when all
elements have been compared.

Here's an example to illustrate tuple comparison:

tuple1 = (1, 2, 3)
tuple2 = (1, 2, 4)
tuple3 = (1, 2, 3)

print(tuple1 < tuple2) # Output: True


print(tuple1 == tuple3) # Output: True
print(tuple2 > tuple3) # Output: True

In this example, we have three tuples: tuple1, tuple2, and tuple3.

 When comparing tuple1 and tuple2, the first two elements (1 and 2)
are equal, but the third element in tuple2 (4) is greater than the
corresponding element in tuple1 (3). Therefore, the comparison
tuple1 < tuple2 evaluates to True.
 When comparing tuple1 and tuple3, all elements in both tuples are
equal. Hence, the comparison tuple1 == tuple3 evaluates to True.
 When comparing tuple2 and tuple3, the first two elements (1 and 2)
are equal, but the third element in tuple2 (4) is greater than the
corresponding element in tuple3 (3). Therefore, the comparison
tuple2 > tuple3 evaluates to True.

Tuple comparison can be useful in various scenarios, such as sorting


tuples or comparing values in multi-element tuples.

Ques 18 : Assume the given instructions while writing the program

 Use the Module_Imp3 which contains functions that can be imported.

 Use from Module_Imp3 import *

 Take an integer as input from user and store it in the variable side.

 Call the function calculatearea(side,side)

 Call the function calculatediameter(side)

 Call the function pivalue()

 print shapes[1:2]

Ans 18: Based on the given instructions, here's a Python program that
imports functions from Module_Imp3 and performs the specified tasks:

from Module_Imp3 import *

side = int(input("Enter the length of the side: "))

area = calculatearea(side, side)


print("Area:", area)

diameter = calculatediameter(side)
print("Diameter:", diameter)
pi = pivalue()
print("Pi Value:", pi)

shapes = ["square", "circle", "triangle", "rectangle", "hexagon"]

print("Selected shape:", shapes[1:2])

In this program, we import all the functions from Module_Imp3 using the
from Module_Imp3 import * statement.

We take an integer as input from the user and store it in the variable side
using the input() function and int() conversion.

We then call the calculatearea() function with side as arguments to


calculate the area of a square with the given side length. The result is
stored in the variable area and printed.

Next, we call the calculatediameter() function with side as an argument to


calculate the diameter of a circle with the given radius (which is the same
as the side length for a square). The result is stored in the variable
diameter and printed.

We call the pivalue() function to get the value of pi. The result is stored in
the variable pi and printed.

Finally, we have a list shapes and print a slice of it using shapes[1:2],


which prints the element at index 1 (inclusive) and index 2 (exclusive) of
the list.

Ques 19: Analyze a Python class that has two methods: get_String and print_String ,
get_String accept a string from the user and print_String prints the string in upper case.

Ans 19:Here's an analysis of a Python class that has two methods,


get_String and print_String :

class StringManipulator:
def get_String(self):
self.string = input("Enter a string: ")

def print_String(self):

print(self.string.upper())

This class, named StringManipulator, has two methods:


1. get_String(self): This method accepts a string input from the user
and stores it in the instance variable self.string. It uses the input()
function to prompt the user for input and assigns the input value to
self.string.
2. print_String(self): This method prints the string stored in self.string
in uppercase letters. It uses the upper() method to convert the
string to uppercase before printing it.

To use this class, you would create an instance of StringManipulator and


call its methods:

# Create an instance of the class


obj = StringManipulator()

# Call the get_String method to get a string from the user


obj.get_String()

# Call the print_String method to print the string in uppercase

obj.print_String()

This would prompt the user to enter a string, store it in the string instance
variable, and then print the uppercase version of that string.

Ques 20: List below are the following conditions to write a program to display only those
numbers

(a) The number must be divisible by five

(b) If the number is greater than 150, then skip it and move to the next number

(c) If the number is greater than 500, then stop the loop

(d) Input: numbers = [12, 75, 150, 180, 145, 525, 50]

(e) Output:

75

145

150
Ans 20: To meet the given conditions and display only the numbers that
satisfy them, you can use a loop and conditional statements. Here's a
Python program that achieves this:

numbers = [12, 75, 150, 180, 145, 525, 50]

for num in numbers:


if num % 5 == 0: # Condition (a): Number must be divisible by five
if num > 150: # Condition (b): Skip if number is greater than 150
continue
elif num > 500: # Condition (c): Stop loop if number is greater than 500
break
else:

print(num) # Print the number that satisfies the conditions

output:
75
145
150

In this program, we iterate over each number in the numbers list using a for loop.

Within the loop, we first check if the number is divisible by 5 using the condition num
% 5 == 0. If it is, we proceed to the next set of conditions.

If the number is greater than 150, we use the continue statement to skip the current
iteration and move to the next number without printing it.

If the number is greater than 500, we use the break statement to exit the loop since
the condition (c) states to stop the loop in this case.

If none of the above conditions are met, we print the number using print(num).

As a result, only the numbers 75, 145, and 150 satisfy the given conditions and are
displayed as output.

Ques 21 : (a) Identify the steps to create a 1D array and 2D array.


(b) Apply Python programming to compute the row wise counts of all possible values in an array

Ans 21: (a) Steps to create a 1D array and 2D array:

1. Creating a 1D Array:
 Import the required module, such as NumPy.
 Use the module's array function to create a 1D array by
passing a sequence of values as an argument.
Code:
import numpy as np

# Create a 1D array
arr1D = np.array([1, 2, 3, 4, 5])
Creating a 2D Array:
 Import the required module, such as NumPy.
 Use the module's array function to create a 2D array by passing a
sequence of sequences (e.g., lists or tuples) as an argument.
Example:

import numpy as np

# Create a 2D array
arr2D = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

(b) Python program to compute the row-wise counts of all possible values in an
array:

Code:

import numpy as np

# Create a 2D array
arr2D = np.array([[1, 1, 2], [3, 2, 1], [3, 3, 2], [1, 2, 2]])

# Get the unique values in the array


unique_values = np.unique(arr2D)

# Compute the row-wise counts of unique values


row_wise_counts = np.apply_along_axis(lambda x: np.bincount(x,
minlength=len(unique_values)), axis=1, arr=arr2D)

print(row_wise_counts)

output:
[[0 2 1]
[1 1 1]
[0 1 2]
[1 2 0]]

In this program, we first create a 2D array arr2D using NumPy. The array
contains values from 1 to 3.

Next, we use the np.unique function to get the unique values present in
the array. These unique values will be the columns in the output.

Then, we use the np.apply_along_axis function to apply a function along


each row of the array. The function we use is a lambda function that uses
np.bincount to compute the counts of unique values in each row. We pass
the minlength parameter to ensure that the output counts have the same
length as the number of unique values.

Finally, we print the row_wise_counts, which gives the counts of unique


values for each row in the original array.
Ques 22 : (a) Compare the differences between a python dictionary and a python set,
including the syntax, parameters, and output of each.

(b) Analyze the "fromkeys" method in python dictionaries, including its syntax, parameters,
and output.

(c) Write a simple program to convert given number into string, char and hexadecimal and
complex number.

Ans 22: (a) Differences between a Python dictionary and a Python set:

1. Syntax:
 Dictionary: A dictionary is defined using curly braces {} or the
dict() constructor. It consists of key-value pairs separated by
colons (:). Example: my_dict = {'key1': 'value1', 'key2':
'value2'}
 Set: A set is defined using curly braces {} or the set()
constructor. It contains unique elements separated by
commas. Example: my_set = {'element1', 'element2',
'element3'}
2. Purpose:
 Dictionary: A dictionary is an unordered collection of key-value
pairs, where each key is unique. It is used to store and
retrieve data based on keys.
 Set: A set is an unordered collection of unique elements. It is
used to store a collection of items without any duplicates and
perform set operations such as union, intersection, etc.
3. Parameters:
 Dictionary: Dictionaries consist of key-value pairs. Keys must
be unique and immutable (such as strings, numbers, or
tuples), while values can be of any data type.
 Set: Sets consist of unique elements. Elements in a set must
be immutable. Common data types used in sets are numbers,
strings, and tuples.
4. Output:
 Dictionary: When accessing a value from a dictionary using its
key, the output is the corresponding value associated with
that key. If the key is not found, it raises a KeyError or returns
a default value specified using the get() method.
 Set: Sets are primarily used to check membership and
perform set operations. The output depends on the specific
operation performed. For example, when checking
membership using the in operator, the output is a Boolean
value (True or False).

(b) Analysis of the "fromkeys" method in Python dictionaries:


Syntax: dict.fromkeys(seq, value)

Parameters:

 seq (required): It specifies the sequence of keys to be used in the


dictionary.
 value (optional): It specifies the value to be assigned to each key in
the dictionary. If not provided, the default value is None.

Output: The fromkeys method returns a new dictionary with the given
keys and the specified value for each key.

Example:

keys = ['key1', 'key2', 'key3']


value = 'default'

my_dict = dict.fromkeys(keys, value)

print(my_dict)

output:

{'key1': 'default', 'key2': 'default', 'key3': 'default'}

In this example, the fromkeys method is used to create a new dictionary


my_dict with keys from the keys list and the value 'default' assigned to
each key. The output is a dictionary where each key is mapped to the
specified value.

(c) Simple program to convert a given number into a string, character,


hexadecimal, and complex number:

number = 42

# Convert to string
string_value = str(number)
print("String:", string_value)

# Convert to character
char_value = chr(number)
print("Character:", char_value)

# Convert to hexadecimal
hex_value = hex(number)
print("Hexadecimal:", hex_value)

# Convert to complex number


complex_value = complex(number)

print("Complex Number:", complex_value)

Output:

String: 42
Character: *
Hexadecimal: 0x2a

Complex Number: (42+0j)

In this program, we have a given number 42. We use different conversion


functions to convert it

Ques 23 : (a) Assume the string "This is my first String". Write a program to print the following:
print the string, print the character f using forward indexing, and print the character S using
negative/backward indexing.
(b) Test for two inputs from the user using input() function, one is string str and another one is
integer n. Write a program to print the given string str n times. Print the result as shown in the
example.
Ans 23 :
(a) Program to print specific characters from a strin g:
 my_string = "This is my first String"

 # Print the entire string
 print("String:", my_string)

 # Print the character 'f' using forward indexing
 print("Character 'f':", my_string[8])

 # Print the character 'S' using negative/backward indexing
 print("Character 'S':", my_string[-7])

output:

String: This is my first String


Character 'f': f
Character 'S': S

In this program, we have the string "This is my first String". We use


indexing to access specific characters from the string.

To print the entire string, we use print("String:", my_string) .


To print the character 'f', we use forward indexing with my_string[8],
where the character at index 8 is 'f'.

To print the character 'S', we use negative/backward indexing with


my_string[-7] , where the character at index -7 (counting from the end) is
'S'.

(b) Program to print a given string n times:

str_input = input("Enter a string: ")


n = int(input("Enter the number of times to print: "))

result = str_input * n

print("Result:", result)

output:

Enter a string: Hello


Enter the number of times to print: 3

Result: HelloHelloHello

In this program, we use the input() function to get two inputs from the
user: a string str_input and an integer n.

We then create a variable result and assign it the value of str_input


multiplied by n. This concatenates the string str_input n times.

Finally, we print the result as the output.

Ques 24: Assume the given below instructions to define a base class Car and a derived
class

Accord.

 Car class has two methods which sets and gets the method brandname.

 Accord is a derived class of the base class Car, which has two methods which sets

and gets the brandname.

 Accord also has the model set and get methods.

 Now create an instance of Accord and set the brandname to the user given input.

 Set the input model for the same instance.

 Now print the output by calling the methods getbrandname() and getmodel() on
Accord instance

Ans 24 : code:

class Car:
def set_brandname(self, brandname):
self.brandname = brandname

def get_brandname(self):
return self.brandname

class Accord(Car):
def set_model(self, model):
self.model = model

def get_model(self):
return self.model

accord_instance = Accord()

brandname_input = input("Enter the brand name: ")


accord_instance.set_brandname(brandname_input)

model_input = input("Enter the model: ")


accord_instance.set_model(model_input)

print("Brand Name:", accord_instance.get_brandname())

print("Model:", accord_instance.get_model())

output:
Enter the brand name: Honda
Enter the model: Accord 2022
Brand Name: Honda

Model: Accord 2022

In this program, we define a base class Car with two methods:


set_brandname() and get_brandname() . The set_brandname() method sets
the brand name of the car, and the get_brandname() method retrieves the
brand name.

We then define a derived class Accord that inherits from the Car class.
Accord has two additional methods: set_model() and get_model(). These
methods set and retrieve the model of the car.
We create an instance of Accord called accord_instance. We prompt the
user to enter the brand name and set it using set_brandname(). Similarly,
we prompt the user to enter the model and set it using set_model().

Finally, we print the output by calling get_brandname() and get_model() on


the accord_instance to display the brand name and model of the Accord
instance.

Question 25: Recall and discuss different kind of keywords in python. Write a source code
in python to explain bitwise operators available in python programming language

Ans 25 :
In Python, there are several types of keywords that have specific
meanings and functionalities. Here are some of the different kinds of
keywords in Python:

1. Reserved Keywords: These keywords are part of the Python


language and have predefined meanings. Examples include if, else,
for, while, def, class, return, import, from, etc. These keywords
cannot be used as variable names or identifiers.
2. Built-in Keywords: These keywords are predefined and built-in
Python functions or objects. Examples include print(), len(), input(),
range(), str(), int(), list(), dict(), set(), type(), True, False, None, etc.
3. Special Keywords: These keywords have special meanings in
specific contexts. Examples include global, nonlocal, assert, yield,
async, await, with, try, except, finally, lambda, etc.
4. Contextual Keywords: These keywords have a specific meaning only
within a specific context. Examples include self (used in class
methods to refer to the instance itself), super (used to call methods
from a parent class), classmethod, staticmethod, property, etc.

Now, let's move on to explaining bitwise operators in Python:

Bitwise operators are used to perform operations on individual bits of


binary numbers. In Python, the following bitwise operators are available:

1. Bitwise AND (&): Performs a bitwise AND operation on the


corresponding bits of two numbers.
2. Bitwise OR (|): Performs a bitwise OR operation on the
corresponding bits of two numbers.
3. Bitwise XOR ( ^): Performs a bitwise XOR (exclusive OR) operation
on the corresponding bits of two numbers.
4. Bitwise NOT ( ~): Flips the bits of a number, changing 1s to 0s and 0s
to 1s.
5. Left Shift (<<): Shifts the bits of a number to the left by a specified
number of positions.
6. Right Shift (>>): Shifts the bits of a number to the right by a
specified number of positions.

Here's an example source code that demonstrates the use of bitwise


operators in Python:

# Bitwise operators example

# Bitwise AND
num1 = 10 # 1010 in binary
num2 = 7 # 0111 in binary
result_and = num1 & num2
print("Bitwise AND:", result_and) # Output: 2 (0010 in binary)

# Bitwise OR
result_or = num1 | num2
print("Bitwise OR:", result_or) # Output: 15 (1111 in binary)

# Bitwise XOR
result_xor = num1 ^ num2
print("Bitwise XOR:", result_xor) # Output: 13 (1101 in binary)

# Bitwise NOT
result_not = ~num1
print("Bitwise NOT:", result_not) # Output: -11 (-1011 in binary)

# Left Shift
result_left_shift = num1 << 2
print("Left Shift:", result_left_shift) # Output: 40 (101000 in binary)

# Right Shift
result_right_shift = num1 >> 2

print("Right Shift:", result_right_shift) # Output: 2 (10 in binary)

In this example, we have two numbers num1 and num2. We perform


various bitwise operations using the &, |, ^, ~, <<, and `

End

You might also like