0% found this document useful (0 votes)
9 views80 pages

Python Subjective

The document contains a series of subjective questions related to Python programming, covering topics such as type conversion, error correction in code, operator classification, and stack operations. It includes tasks to identify and fix syntax errors in provided code snippets, explain various types of operators, and implement functions for stack manipulation. Additionally, it addresses logical errors in pseudocode and requires the rewriting of code to ensure correct execution.

Uploaded by

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

Python Subjective

The document contains a series of subjective questions related to Python programming, covering topics such as type conversion, error correction in code, operator classification, and stack operations. It includes tasks to identify and fix syntax errors in provided code snippets, explain various types of operators, and implement functions for stack manipulation. Additionally, it addresses logical errors in pseudocode and requires the rewriting of code to ensure correct execution.

Uploaded by

rishav raj
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python

Subjective Questions
Q Explain the difference between explicit and implicit type conversion in Python with suitable examples.
Q The following Python program is intended to accept a student’s name and marks, and then display them. However, the
code contains syntax and logical errors related to input–output operations.
Identify the errors and rewrite the corrected code.

name = input("Enter Name")


marks = input("Enter Marks:")
print "Student Name:", name
print("Marks" marks)
Q While writing Python programs, operators play an important role in performing operations on data.
Explain the term Operator in Python.
Classify Python operators and explain any four types with suitable examples.
Q The following Python code uses different operators but contains errors.
Identify and correct the errors and rewrite the correct code.

x = 10

y=5

if x = y:

print(x && y)
Q Arithmetic and Assignment operators are widely used in Python programs.
(a) Explain Arithmetic operators and Assignment operators with suitable examples.
(b) Identify and correct the error(s) in the following code:

x = 10
y=3
x+=y
print(x)
Q Relational and Logical operators are widely used in decision-making statements in Python.
Explain Relational operators and Logical operators. Differentiate between them and illustrate your answer with suitable
examples.
Q. In Python, operators are not only used for calculations but also for comparison and evaluation of expressions.
Explain Identity operators, Membership operators, and Operator Precedence with suitable examples.
Also justify why operator precedence is important in Python programs.
Q Rewrite the following Python code after removing all syntax errors. Clearly underline each correction made in the code.

Value = 30
for VAL in range(0, Value)
If val % 4 == 0:
print(VAL * 4)
Elseif val % 5 == 0:
print(VAL + 3)
else
print(VAL + 10)
Q A Python code fragment shown below has been deliberately corrupted with multiple syntax mistakes and formatting issues. Your task is to
carefully inspect the snippet, repair all syntactical faults, and rewrite the program so that it executes correctly. While presenting the corrected
version, clearly underline every change or correction that you make in the code.

num1, num2 = 10, 45


While num1 % num2 == 0
num1+= 20
num2+= 30
Else:
print('hello')
Q The code given below accepts a number as an argument and returns its reverse. Carefully examine the program and
rewrite it after removing all syntax and logical errors. Clearly underline every correction made in the code.
define revNumber(num):
rev = 0
rem = 0
While num > 0:
rem == num % 10
rev = rev*10 + rem
num = num // 10
return rev
print(revNumber(1234))
Q Explain the difference between break and continue statements in Python with suitable examples.
Q. A student has written the following Python pseudocode to display the sum of all even numbers from 1 to 20.
However, the program contains some syntactical and logical errors.

sum = 0
for i in range(1, 20)
if i % 2 = 0:
sum = sum + i
print "Sum is", sum

Answer the following:


(i) Identify any two errors in the pseudocode.
(ii) Rewrite the correct Python code after removing all errors.
Q Write a Python function POP(Arr) where Arr represents a stack implemented using a list of numbers. The function should
return the value deleted from the stack.
Q Write a Python function PUSH(Arr) where Arr is a list of numbers. From this list, push all numbers divisible by 5 into a stack
implemented using a list. Display the stack if it contains at least one element; otherwise, display an appropriate error message.
Q You have a stack named BooksStack that stores records of books. Each record is represented as a list containing
book_title, author_name, publication_year.
Write the following user-defined functions in Python:
push_book(BooksStack, new_book) – Accepts the stack and a new book record as arguments and pushes the
new book onto the stack.
pop_book(BooksStack) – Pops the topmost book record from the stack and returns it. If the stack is empty, display
"Underflow".
peep(BooksStack) – Displays the topmost element of the stack without removing it. If the stack is empty, display
"None".
Q Write a user-defined function push_even(N) that accepts a list of integers N and pushes all even numbers from the list
into a stack named EvenNumbers.

Write function pop_even() to pop and return the topmost number from the stack. If the stack is empty, display "Empty".
Write function Disp_even() to display all elements of the stack without deleting them. If the stack is empty, display "None".

Example:
If the list VALUES = [10, 5, 8, 3, 12]
then the stack EvenNumbers should contain:

[10, 8, 12]
Q A list of product records is given as:

L = [("Laptop", 90000), ("Mobile", 30000), ("Pen", 50), ("Headphones", 1500)]

Write the following user-defined functions to perform operations on a stack named Product:

Push_element() – Push the items (product name and price) of those products costing more than 50 into the stack.
After pushing, the stack should contain:

[('Laptop', 90000), ('Mobile', 30000), ('Headphones', 1500)]

Pop_element() – Pop all the items from the stack and display them. Also display "Stack Empty" when there are no elements
left in the stack.

Output:

('Headphones', 1500)
('Mobile', 30000)
('Laptop', 90000)
Stack Empty
Q A list NList contains records as list elements in the form:
[City, Country, Distance from Delhi]
These records together form a nested list. Write the following user-defined functions in Python to perform operations on a stack named travel.

(i) Push_element(NList)
This function takes the nested list as an argument and pushes a list containing city and country names into the stack for those records where
the city is not in India and the distance from Delhi is less than 3500 km.

(ii) Pop_element()
This function pops elements from the stack and displays them. Also, the function should display "Stack Empty" when the stack has no
elements.
Example:If the nested list contains:
NList = [["New York","U.S.A.",11734],
["Naypyidaw","Myanmar",3219],
["Dubai","UAE",2194],
["London","England",6693],
["Gangtok","India",1580],
["Columbo","Sri Lanka",3405]]

After executing Push_element(), the stack should contain:


['Naypyidaw','Myanmar']
['Dubai','UAE']
['Columbo','Sri Lanka']
After executing Pop_element(), the output should be:
['Columbo','Sri Lanka']
['Dubai','UAE']
['Naypyidaw','Myanmar']
Stack Empty
Q Explain the difference between break and continue statements in Python with suitable examples.
Q. A student has written the following Python pseudocode to display the sum of all even numbers from 1 to 20.
However, the program contains some syntactical and logical errors.

sum = 0
for i in range(1, 20)
if i % 2 = 0:
sum = sum + i
print "Sum is", sum

Answer the following:


(i) Identify any two errors in the pseudocode.
(ii) Rewrite the correct Python code after removing all errors.
Q Write a Python function POP(Arr) where Arr represents a stack implemented using a list of numbers. The function should
return the value deleted from the stack.
Q Write a Python function PUSH(Arr) where Arr is a list of numbers. From this list, push all numbers divisible by 5 into a stack
implemented using a list. Display the stack if it contains at least one element; otherwise, display an appropriate error message.
Q You have a stack named BooksStack that stores records of books. Each record is represented as a list containing
book_title, author_name, publication_year.
Write the following user-defined functions in Python:
push_book(BooksStack, new_book) – Accepts the stack and a new book record as arguments and pushes the
new book onto the stack.
pop_book(BooksStack) – Pops the topmost book record from the stack and returns it. If the stack is empty, display
"Underflow".
peep(BooksStack) – Displays the topmost element of the stack without removing it. If the stack is empty, display
"None".
Q Write a user-defined function push_even(N) that accepts a list of integers N and pushes all even numbers from the list
into a stack named EvenNumbers.

Write function pop_even() to pop and return the topmost number from the stack. If the stack is empty, display "Empty".
Write function Disp_even() to display all elements of the stack without deleting them. If the stack is empty, display "None".

Example:
If the list VALUES = [10, 5, 8, 3, 12]
then the stack EvenNumbers should contain:

[10, 8, 12]
Q A list of product records is given as:

L = [("Laptop", 90000), ("Mobile", 30000), ("Pen", 50), ("Headphones", 1500)]

Write the following user-defined functions to perform operations on a stack named Product:

Push_element() – Push the items (product name and price) of those products costing more than 50 into the stack.
After pushing, the stack should contain:

[('Laptop', 90000), ('Mobile', 30000), ('Headphones', 1500)]

Pop_element() – Pop all the items from the stack and display them. Also display "Stack Empty" when there are no elements
left in the stack.

Output:

('Headphones', 1500)
('Mobile', 30000)
('Laptop', 90000)
Stack Empty
Q A list NList contains records as list elements in the form:
[City, Country, Distance from Delhi]
These records together form a nested list. Write the following user-defined functions in Python to perform operations on a stack named travel.

(i) Push_element(NList)
This function takes the nested list as an argument and pushes a list containing city and country names into the stack for those records where
the city is not in India and the distance from Delhi is less than 3500 km.

(ii) Pop_element()
This function pops elements from the stack and displays them. Also, the function should display "Stack Empty" when the stack has no
elements.
Example:If the nested list contains:
NList = [["New York","U.S.A.",11734],
["Naypyidaw","Myanmar",3219],
["Dubai","UAE",2194],
["London","England",6693],
["Gangtok","India",1580],
["Columbo","Sri Lanka",3405]]

After executing Push_element(), the stack should contain:


['Naypyidaw','Myanmar']
['Dubai','UAE']
['Columbo','Sri Lanka']
After executing Pop_element(), the output should be:
['Columbo','Sri Lanka']
['Dubai','UAE']
['Naypyidaw','Myanmar']
Stack Empty
Q. A school maintains two sets: A contains students who play Cricket and B contains students who play Football.
Write a Python program to:
(i) Display students who play both games.
(ii) Display students who play only Cricket.
(iii) Display students who play at least one game.
Q A teacher stores marks of students in a tuple.
She wants to display only those marks which are greater than 60 using a loop.
Write a Python program to perform the task.
Q Predict the output of the following Python code:

emp = {"Arv": (85000,90000), "Ria": (78000,88000),


"Jay": (72000,80000), "Tia": (80000,70000)}

selected = []
for name in emp:
salary = emp[name]
average = (salary[0] + salary[1]) / 2
if average > 80000:
[Link](name)

print(selected)
Q Design a Python function dispBook(BOOKS) that receives a dictionary named BOOKS and displays, in uppercase, the
titles of only those books whose names begin with a consonant.

For example, consider the dictionary:


BOOKS = {1:"Python", 2:"Internet Fundamentals", 3:"Networking",
4:"Oracle sets", 5:"Understanding HTML"}
The output should be:
PYTHON
NETWORKING
Q A dictionary Stu_dict stores the marks of students in three test series in the form
Stu_ID : (TS1, TS2, TS3) as key–value pairs.
Write a Python program using the following user-defined functions to perform operations on a stack named Stu_Stk.

(i) Push_elements(Stu_Stk, Stu_dict): This function should push the IDs of those students from the dictionary into the stack
Stu_Stk who have scored greater than or equal to 80 marks in TS3.

(ii) Pop_elements(Stu_Stk): This function should remove all elements from the stack in LIFO order and display them. When
the stack becomes empty, the message "Stack Empty" should be displayed. Call both functions to execute the operations.

Example:
If Stu_dict = {5:(87,68,89), 10:(57,54,61), 12:(71,67,90), 14:(66,81,80), 18:(80,48,91)}
After executing Push_elements(), the stack should contain: [5, 12, 14, 18]
After executing Pop_elements(), the output should be:
18
14
12
5
Stack Empty

Solution is on next slide


Q Write a Python program to display the alternate characters of a string my_str.
For example, if my_str = "Computer Science"
the output should be: Cmue cec
The following Python code is intended to remove the first and last characters of a given string and return the resulting string.
However, the code contains syntax and logical errors. Rewrite the corrected program and underline all the corrections made.

define remove_first_last(str):
if len(str) < 2:
return str
new_str = str[1:-2]
return new_str

result = remove_first_last("Hello")
Print("Resulting string: " result)
Q (Answer using Python built-in methods/functions only)
i) Write a statement to find the index of the first occurrence of the substring "good" in a string named review.
ii) Write a statement to sort the elements of list L1 in descending order.
Q Predict the output of the following Python code:

text = "Learn Python with fun and practice"


print([Link]("with"))
print([Link]("a"))
Q Write a Python program that defines a function FindWord(STRING, SEARCH) which accepts two arguments — STRING
and SEARCH — and prints the number of times the word SEARCH occurs in STRING. Also write suitable statements to
call the function.
For example, if STRING = "Learning history helps to know about history with interest in history"
SEARCH = "history"
The program should display: The word history occurs 3 times.
Q Write a Python function lenWords(STRING) that takes a string as an argument and returns a tuple containing the length of each word
in the string.
For example, if STRING = "Come let us have some fun"
the function should return: (4, 3, 2, 4, 4, 3)
Q Write a Python function countNow(PLACES) that accepts a dictionary PLACES as an argument and displays the
names of those places in UPPERCASE whose names are longer than 5 characters.
For example, consider: PLACES = {1:"Delhi", 2:"London", 3:"Paris", 4:"New York", 5:"Doha"}
The output should be: LONDON
NEW YORK
Q Write a Python function remove_element() that accepts a
list L and a number n. If the number n exists in the list, it
should be removed. If it does not exist, print the message
"Element not found".
Q Write a Python function add_contact() that accepts a
dictionary phone_book, a name, and a phone number. The
function should add the name and phone number to the
dictionary. If the name already exists, print "Contact already
exists" instead of updating it.
Q. While writing Python programs, programmers may encounter different types of errors.
Explain the types of errors in Python.
Illustrate any three types with suitable examples.
Q. A programmer has written the following Python code to divide two numbers entered by the user:

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


b = int(input("Enter another number: "))
print(a/b)
print("Division Successful")

(i) Identify the possible exceptions that may occur during execution.
(ii) Rewrite the program using exception handling so that it handles errors gracefully and displays a suitable message for
each exception.
(iii) Explain the role of the else block in exception handling.
Q Differentiate between actual parameters and formal parameters with a suitable example for each.
Q Carefully observe the Python program given below and determine the exact output produced after execution. Consider the effect of
the global keyword, list mutability, and the end parameter of the print() function while writing your answer.
L = [5,10,15,1]
G=4
def Change(X):
global G
N=len(X)
for i in range(N):
X[i] += G
Change(L)
for i in L:
print(i,end='$')
Q Explain the use of the global keyword in a Python function with the help of a suitable example.
Q (i) Define the term Constraint in the context of an RDBMS and give a suitable example.
(ii) Sameera maintains a database named STORE which contains a table ITEM with the following structure:
Ino (Item number) – Integer
Iname (Item Name) – String
Price (Item Price) – Float
Discount (Discount) – Float
Connection details:
Username: root
Password: tiger
Host: localhost
Help her to delete the record from the table ITEM for a particular item name entered by the user.
import [Link] as mysql
con1 = [Link](host='localhost', user='root', password='__', database='STORE') # Statement-1
mycursor = ________ # Statement-2
item_name = input("Enter the Item name to remove the record : ")
query = ______________ # Statement-3
[Link](query)
con1.____ # Statement-4
print('Data Deleted successfully')
[Link]()
Answer the following with reference to the code above:
a) Complete Statement-1 to establish the database connection.
b) Write Statement-2 to create the cursor object.
c) Complete Statement-3 to delete the record from table ITEM using the item name entered by the user.
d) Complete Statement-4 to save the changes in the table.
Q (i) Write one difference between a Candidate Key and an Alternate Key.
(ii) A table named ITEM exists in the database STORE with the following structure:
Ino (Item number) – Integer
Iname (Item Name) – String
Price (Item Price) – Float
Discount (Discount) – Float
Connection details:
Username: root
Password: tiger
Host: localhost
The table needs to be accessed using Python. The incomplete code is given below:
______ # Line 1
con1 = [Link](host='localhost', user='root', password='tiger', database='STORE')
mycursor = con1.____ # Line 2
query = 'SELECT * FROM ITEM where Price > {}'.format(___) # Line 3
[Link](query)
data = mycursor.___ # Line 4
for rec in data:
print(rec)
[Link]()
Answer the following:
a) Complete Line 1 to import the required module.
b) Complete Line 2 to create the cursor object.
c) Complete Line 3 to display records of items whose price is more than 5000.
d) Complete Line 4 to fetch all the records.
Q Kabir wants to write a Python program to insert a record into the table Student in the MySQL database SCHOOL with
the following fields:
rno (Roll Number) – Integer
name (Name) – String
DOB (Date of Birth) – Date
fee (Fee) – Float
Connection details to establish Python–MySQL connectivity:
Username: root
Password: tiger
Host: localhost
The values of rno, name, DOB, and fee must be accepted from the user. Write the Python program to insert the record
into the table.
Q Differentiate between the database cursor methods fetchone() and fetchall() with suitable examples for each..
Q Explain the file handling functions seek() and tell() in Python. State any two differences between them. Also mention one
situation where each function is used.
Q Write a Python function AMCount() that reads a text file
"[Link]" and counts as well as displays the occurrences
of alphabets A and M (including both uppercase and
lowercase).

Example: If the file contains:


Updated information As simplified by official websites.

The output should be:

A or a: 4
M or m: 2
Q Write and call a Python function that reads lines from
a text file [Link] and displays those lines that
do not start with a vowel (A, E, I, O, U), irrespective of
case.
Q Write a Python function that reads a text file
"[Link]" and counts the number of times the
words "Me" or "My" appear in the file.

Example: If the file contains:


My first book was Me and My Family. It gave me a
chance to be Known to the world.

The output should be:

Count of Me/My in file: 4


Q Write a Python function that reads a text file "[Link]" and displays the number of times the word "Python" appears in the
file.
Q Write a Python function COUNT() that reads the contents of a text file named "[Link]" and displays the number of
occurrences of the letter 'e' in each line of the file.
Example: If the file contains the following text:
Gratitude is a humble heart's radiant glow,
A timeless gift that nurtures and bestows.
It's the appreciation for the love we're shown,
In moments big and small, it's truly known.
The function should display the output as:
Line 1 : 3
Line 2 : 4
Line 3 : 6
Line 4 : 1
Q Write a Python function Start_with_I() that reads the text file "[Link]" and displays only those lines that start with
the letter 'I'.
Example: If the file contains:
Gratitude is a humble heart's radiant glow,
A timeless gift that nurtures and bestows.
It's the appreciation for the love we're shown,
In moments big and small, it's truly known.
Then the output should be:
It's the appreciation for the love we're shown,
In moments big and small, it's truly known.
Q Write a Python function vowelCount() that reads the text file [Link] and counts as well as displays the total number
of vowels present in the file.
Q A data analyst imports student marks stored earlier in Excel into Python using Pandas.
The data is first converted into a NumPy array, then into a Pandas Series for analysis.

(a) Explain why Pandas is preferred over Excel for large datasets.
(b) Differentiate between a NumPy array and a Pandas Series.
(c) Write Python statements to display the first 3 and last 2 values of the Series.
Q The following Pandas code is intended to read data from a CSV file and display selected rows, but it contains errors:
import panda as pd
df = pd.read_csv("[Link]")
print([Link])
print(df[0:3, ["Name","Marks"]])

(a) Identify and correct any three errors in the code.


(b) Rewrite the corrected code.
(c) State the difference between head() and tail() functions.
Q A dataset shows monthly attendance (%) of students for one year.

(a) Differentiate between a Line Chart and a Bar Chart (any two points).
(b) Which chart is more suitable here and why?
(c) State one situation where the other chart would be misleading.

Attendance %
90 | *
80 | *
70 | *
60 |*
------------------
Jan Feb Mar Apr
Months
Q A student uses a Pie Chart to show marks obtained in 6 subjects:
Maths, Science, English, CS, Hindi, SST.

(a) Is the chart suitable? Justify your answer.


(b) Name a better chart and give one reason.
(c) Write one limitation of Pie Charts.

Marks
90 | █
80 | █ █
70 | █ █
--------------------
M S E CS H SST
Q Two bar charts represent the same data, but one starts the Y-axis from 50 instead of 0.

(a) Why can this be misleading?


(b) Name this type of visualization issue.
(c) State one rule to avoid such errors.
Q A Pandas DataFrame df stores students’ marks.

import [Link] as plt


subjects = ["Maths", "Science", "English", "CS"]
marks = [72, 88, 65, 90]
[Link](subjects, marks)
[Link]("Subjects")
[Link]("Marks")
[Link]("Student Marks")
[Link]()

Answer the following:

(a) Identify the mistake in the chart selection.


(b) Name the most suitable chart for this data.
(c) Rewrite the correct code using the appropriate chart.
(d) State one reason why the selected chart is better.
Q A data analyst is visualizing students’ marks using Matplotlib.
The following code runs without syntax error, but the output graph is misleading.

import [Link] as plt

subjects = ["Maths", "Science", "English", "CS"]


marks = [78, 85, 85, 92]

[Link](marks, subjects)
[Link]("Student Performance")
[Link]("Marks")
[Link]("Subjects")
[Link]()

Answer the following:

(a) Identify two logical errors in the visualization.


(b) Write the corrected code to fix the graph.
(c) State one reason why incorrect visualization can lead to wrong conclusions.
(d) Name the most suitable chart type if subject-wise comparison is required and justify your choice.
Marks
100 |
90 | █
80 | █ █
70 | █
-------------------------
Maths Sci Eng CS
Subjects

You might also like