0% found this document useful (0 votes)
21 views4 pages

Python Coding Questions and Solutions

The document contains a series of Python-related questions and tasks, including code snippets to analyze, outputs to predict, and functions to complete. It covers topics such as string manipulation, list operations, global variables, and database connectivity. The questions are designed to test knowledge of Python programming concepts and syntax.

Uploaded by

rohanmurali8
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)
21 views4 pages

Python Coding Questions and Solutions

The document contains a series of Python-related questions and tasks, including code snippets to analyze, outputs to predict, and functions to complete. It covers topics such as string manipulation, list operations, global variables, and database connectivity. The questions are designed to test knowledge of Python programming concepts and syntax.

Uploaded by

rohanmurali8
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 Important Questions

2. Identify the correct output of the following code snippet from the options given:
S="ELEVATE YOURSELF"
S=[Link]('EL','@')
print(S)
a) @EVATE YOURS@F
b) @VATE YOURS@F
c) @LEVATE YOURS@LF
d) @LEVATE YOURS@F

3. Evaluate the following expression:


bool((not True and int(False)) + (not(False and True)))

4. Wahim want to execute the following code and get the desired output as: “R*o*g*e*r”
But his code is incomplete. Help him to complete the code by filling the missing line, so that the
above output could be printed.
a = "Roger"
print(______________)

5. Read the following python code and write the output.


Str="World Peace"
print(Str[:6][1:-2])
a) dlro
b) orl
c) orld
d) Wrd P

7. Consider the following code snippet and identify the value that could be stored in L after
execution of the code.
L= [ [10]*3 ]
[Link](3, 4)
a) [[10],[10],[10],4]
b) [[10,10,10],4]
c) [10,10,10,4]
d) [[10,4],[10,4],[10,4]]

8. What is the use of id() function in python?


a) returns the data type of object
b) returns the size of the object
c) returns the identity of object
d) None of the above

9. Pick one of the following statements to correctly complete the function body in the given code
snippet.
def f(number):
# Missing function body
print(f(5))
a) return "number"
b) print(number)
c) print("number")
d) return number

13. What will the following statement print?


print(max("[Link]".split('.')))

20. Assertion (A): For changes made to a variable defined within a function to be visible outside the
function, it should be declared as global.
Reason (R): Variables defined within a function are local to that function by default, unless explicitly
specified with the global keyword.

22. i) Write a python statement to print the sum of least and most significant digit of a 4-digit number
assigned to a variable B.
For example, if B is 2345 then output should be 2+5=7.

ii) Write python statement for the following:


a) to find the number of occurrences of alphabet ‘c’ in a string S
OR
b) to find the position of letter ‘c’ in S

23. i) Find the output generated by the following code:


mystr = "hello this is an application to apply and demonstrate split, slicing"
print([Link]()[5:-2][-1:5])

ii) If L1= [19,23,17,13,71] and L2=[21,5,11,31,55]


a) Merge L1 with L2 so that they merge to become a single list in the name L1.
OR
b) Arrange the elements of L1 and L2 in ascending order.

24. Identify the possible outputs of the following program from the given below options: Also write
the minimum and maximum value generated.
import random
color = ['Black','White','Yellow','Blue']
for i in range([Link](0,2)):
print(color[i], end="*")
print()
a) Black*White*
b) Black*
c) Black*White*Yellow*
d) No output

25. i) Ravi, a python programmer, is working on a project. For some requirement, he has to define a
function with name CalculateInterest(), he defined it as:
def CalculateInterest(Principal, Rate=.06, Time):
# code
But this code is not working. Can you help Ravi to identify the error in the above function and what
is the solution?

ii) Consider the following code:


def check():
global num
num=1000
print(num)
num=100
print(num)
check()
print(num)
How does the statement “global num” influence the program? Explain.

30. A) Predict the output of the following program:


def change(s):
d = {"UPPER" : 0, "LOWER" : 0 }
for c in s:
if [Link]():
d["UPPER"] += 1
elif [Link]():
d["LOWER"] += 1
print("Upper case count :", d["UPPER"])
print("Lower case count :", d["LOWER"])

change("School Days are Happy")

OR

B) Predict the output of the following program:


def makenew(m):
news=""
count=0
for i in m:
if count%2==0:
news=news+[Link]()
else:
if [Link]():
news=news+[Link]()
else:
news="-".join(news+i)
count+=1
news=news+m[:3]
print("The new string is:",news)

makenew("STRING76")

33. Write a function def Television() in Python to read all the records from the file "[Link]"
which stores the records of various products such as Television, Refrigerator, Air-Conditioner etc.,
under different fields as mentioned below:
Code Item Company Price Quantity
T/01 Television LG 42000 15
T/02 Television Sony 45000 20
F/01 Refrigerator LG 55000 25
... ... ... ... ...

Now, Display the details of all televisions of various companies from the file, also display the total
cost of all televisions. [Assume that the file is already present in the hard disk].

35. Kathir wants to write a program in Python to do the following in the table named Student in
MYSQL database SCHOOL:
• rno (Roll number) integer
• name (Name) string
• DOB (Date of birth) Date
• Fee float

Note the following to establish connectivity between Python and MySQL:


• Username - root
• Password - tiger
• Host - localhost

i) The values of fields rno, name, DOB and Fee has to be accepted from the user and appended to
the table Student.
ii) To increase the Fee of the all the students by 10%.
Help Kathir to complete the program in Python.

Common questions

Powered by AI

Assertions are used to set conditions that must hold true, aiding debugging. For variables scoped outside functions, using 'global' ensures they're accessible and modifiable within functions. Without 'global', inner function modifications create isolated versions, causing scope confusion unless explicitly declared for overriding .

The loop runs from 0 to a random upper bound (between 0 and 2 inclusive), causing the program to print colors with asterisks. Possible outputs are 'Black*', 'Black*White*', or no output, as the loop may not execute if 'random.randint(0,2)' returns 0. Thus, minimum and maximum outputs reflect these potential iterations .

Inserting an element into a list with 'insert(3, 4)' means that '4' is added at index 3. In a list `[ [10]*3 ]`, representing nested lists, inserting '4' results in a structure like `[[10,10,10],4]`, maintaining sequence integrity by not altering existing sub-lists but adding another element at position 3 .

Python's 'csv' module facilitates reading and processing CSV files. Using 'csv.reader', data can be looped over to extract specific fields like 'Television' and summing values like 'Price * Quantity' provides the total cost. 'open()' function should be used to access and read file content effectively .

In the provided example code, the statement 'global num' indicates that 'num' refers to a global variable. Thus, changes to 'num' within the function 'check()' affect its value outside the function as well. Initially, 'num' is set to 1000, and then to 100 within 'check()'. As a result, when 'check()' is called and subsequently when 'print(num)' is executed outside the function, 'num' retains the value 100 from the last assignment .

To achieve an output like 'R*o*g*e*r', one can employ the 'join()' method by passing an asterisk and splitting 'Roger' into individual characters using 'list(a)'. Using 'print('*'.join(a))' produces the desired format by concatenating list elements with an interspersing '*' .

The function 'CalculateInterest()' does not work because it specifies a non-default argument 'Time' after a default argument 'Rate', which is contrary to Python's rule that default arguments must follow non-default arguments. To resolve this, the order of parameters should be changed to 'def CalculateInterest(Principal, Time, Rate=.06)' ensuring non-default arguments precede default ones .

The program iterates over each character in a string. For each uppercase and lowercase character, it increments 'UPPER' or 'LOWER' in a dictionary. The final print reports the count of such cases, revealing character case statistics within the string based on conditions (e.g., .isupper(), .islower()).

The code 'print(mystr.split()[5:-2][-1:5])' first splits 'mystr' into a list of words. The slice [5:-2] extracts elements from the sixth to the third last word, inclusive. Then '[-1:5]' takes characters from the empty single-element result (due to slicing after '-1'). Thus, the program doesn't return meaningful output as it trims the list to an empty state .

The 'id()' function in Python returns the unique identity number of an object, which acts as a memory address reference. It helps differentiate between memory spaces allocated for objects, confirming whether two variables refer to the same object (i.e., they share the same ID).

You might also like