Python Programming Questions and Answers
Q1. Output of the code
c = 10
def add():
global c
c=c+2
print(c, end='#')
add()
c = 15
print(c, end='%')
Output: 12#15%
Explanation:
- Global variable 'c' is modified in the function to 12.
- Then reassigned to 15 and printed.
Q2. Mutable vs Immutable
- Mutable: Can be changed (e.g., list, dict)
- Immutable: Cannot be changed (e.g., tuple, str)
From: (1,2), [1,2], {1:1,2:2}, '123'
- Mutable: [1,2], {1:1,2:2}
- Immutable: (1,2), '123'
Q3. List Functions
[Link](4) - Count 4s in L1
[Link]() - Sort L1
[Link](L2) - Add L2 to end of L1
[Link]() - Reverse L2
Q4. Random Output and Range
Python Programming Questions and Answers
import random
a = 'Wisdom'
b = [Link](1,6)
for i in range(0,b,2):
print(a[i], end='#')
b ranges from 1 to 6
Possible outputs: W#, W#i#, W#i#s#
Q5. Tuple Swap (Corrected)
def swap_first_last(tup):
if len(tup) < 2:
return tup
new_tup = (tup[-1],) + tup[1:-1] + (tup[0],)
return new_tup
result = swap_first_last((1,2,3,4))
print('Swapped tuple:', result)
Q6. Words with @cmail
def find_cmail():
with open('[Link]') as file:
for line in file:
for word in [Link]():
if '@cmail' in word:
print(word)
Q7. Words > 5 chars from '[Link]'
def long_words():
Python Programming Questions and Answers
with open('[Link]') as file:
for line in file:
for word in [Link]():
if len(word) > 5:
print(word)
Q8. CSV '[Link]'
(I) def display_high_population():
with open('[Link]') as file:
for row in [Link](file):
if int(row[1]) > 5000000:
print(row)
(II) def count_records():
with open('[Link]') as file:
print(sum(1 for _ in [Link](file)))
Q9. Binary File for Candidates
(I) add_candidate(): get user input, pickle and append to file
(II) update_senior_managers(): change designation to 'Senior Manager' if exp > 10
(III) display_non_senior(): show all except Senior Managers
Q10. CSV '[Link]' Handling
Accept(): Write column headers and student records
wonCount(): Count and display rows where Result == 'Won'