Type C: Programming Practice / Knowledge-Based Questions
Question – 7: Swap values of two variables.
Answer:
#Que 7 - Swaping values of two variables
first = "Jimmy"
second = "Johny"
print("-"*10)
print("Before Swap")
print("-"*10)
print("First = ",first)
print("Second = ",second)
first, second = second, first
print("-"*10)
print("After Swap")
print("-"*10)
print("First = ",first)
print("Second = ",second)
Output:
————–
Before Swap
————–
Jimmy
Johny
————–
After Swap
————–
Johny
Jimmy
Question – 8: Tuples storing the first 9 terms of the Fibonacci series.
Answer:
#Que 8 - Tuples storing the first 9 terms of Fibonacci series
first = 0 #first term
second = 1 #second term
count = 2 # counter is 2 initially
fibterm = first, second #appending first two to tuples
while count < 9:
third = first + second
fibterm += third, #appending third terms to tuple
count += 1
first, second = second, third #swapping
print("Fibonacci Series up to 9th terms ")
print(fibterm)
Output:
Fibonacci Series up to 9th terms
(0, 1, 1, 2, 3, 5, 8, 13, 21)
Question – 9: Dictionary Month and Days. Manipulation of Dictionary
Answer:
month_day = {'Jan':31, 'Feb':28, 'Mar':31, 'Apr':30,
'May':31, 'Jun':30, 'Jul':31, 'Aug':31,
'Sep':30, 'Oct':31, 'Nov':30, 'Dec':31}
#a
month = input("Enter Month Name : ")
print("Number of Days : ", month_day[month])
#b
print("Keys in alphabetical order => ")
month = sorted(month_day.keys())
print(month)
#c
print("Months having 31 days = > ")
for k in month_day:
if month_day[k] == 31:
print(k)
#d
days = sorted(month_day.values())
unique = []
for val in days:
if val not in unique:
unique.append(val)
for val in unique:
for k in month_day:
if month_day[k] == val:
print(k, val)
Output:
Enter Month Name: Jan
Number of Days: 31
Keys in alphabetical order =>
[‘Apr’, ‘Aug’, ‘Dec’, ‘Feb’, ‘Jan’, ‘Jul’, ‘Jun’, ‘Mar’, ‘May’, ‘Nov’, ‘Oct’, ‘Sep’]
Months having 31 days = >
Jan
Mar
May
Jul
Aug
Oct
Dec
Feb 28
Apr 30
Jun 30
Sep 30
Nov 30
Jan 31
Mar 31
May 31
Jul 31
Aug 31
Oct 31
Dec 31
Question – 10: Function to Add Two Dictionary, computes the union of two dictionaries
Answer:
#Que 10 - Create a Function addDict() to add two dictionary
def addDict(dict1, dict2):
dict1.update(dict2)
return dict1
d1 = {1 : 'one', 2 :'two'}
d2 = {3 : 'three', 4 : 'four', 1 :'ten'}
print('d1 =>',d1)
print('d2 =>',d2)
d3 = addDict(d1, d2)
print('d3 =>',d3)
Output:
d1 => {1: ‘one’, 2: ‘two’}
d2 => {3: ‘three’, 4: ‘four’, 1: ‘ten’}
d3 => {1: ‘ten’, 2: ‘two’, 3: ‘three’, 4: ‘four’}
Question – 11: Sort dictionary keys using Bubble sort and produce the sorted keys as a list
Answer: uploading soon
Question – 12: Sort dictionary values using Bubble sort and produce the sorted values as a list
Answer: uploading soon