ETE Python Question 1 To 25
ETE Python Question 1 To 25
Ques 1: Identify how python language is more simple other than Java and C. Give proper example.
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 {
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;
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.
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.
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.
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:
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.
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?
for thing in L:
if thing == 0:
L[thing] = "universe"
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:
(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
class Calculator {
public:
int add(int a, int b) {
return a + b;
}
int main() {
Calculator calc;
int result1 = calc.add(2, 3);
double result2 = calc.add(2.5, 3.7);
// ...
}
class Vector2D {
public:
int x;
int y;
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.
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:
output:
[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
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
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
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()
s1.setname(name)
s1.setage(age)
s1.getname()
s1.getage()
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.
If the percentage mark is less than 40, the grade is set to "Fail".
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
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
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:
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.
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
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:
output:
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
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.
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]
output:
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.
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:
Now, let's write a Python program to determine the eldest and youngest
among Ram, Sam, and Khan based on their ages:
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.
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().
.Ques 15: Identify the string method used to implement the following. I. To count the
number of characters in the string.
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!"
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:
output:
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"]
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.
tuple1 = (1, 2, 3)
tuple2 = (1, 2, 4)
tuple3 = (1, 2, 3)
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.
Take an integer as input from user and store it in the variable side.
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:
diameter = calculatediameter(side)
print("Diameter:", diameter)
pi = pivalue()
print("Pi Value:", pi)
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 call the pivalue() function to get the value of pi. The result is stored in
the variable pi and printed.
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.
class StringManipulator:
def get_String(self):
self.string = input("Enter a string: ")
def print_String(self):
print(self.string.upper())
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
(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:
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.
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]])
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.
(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).
Parameters:
Output: The fromkeys method returns a new dictionary with the given
keys and the specified value for each key.
Example:
print(my_dict)
output:
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)
Output:
String: 42
Character: *
Hexadecimal: 0x2a
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:
result = str_input * n
print("Result:", result)
output:
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.
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
Now create an instance of Accord and set the brandname to the user given input.
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()
print("Model:", accord_instance.get_model())
output:
Enter the brand name: Honda
Enter the model: Accord 2022
Brand Name: Honda
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().
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:
# 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
End