Chapter-1 Review of Python Basics
Unsolved Questions-
Q1.What are the advantages of the Python programming language?
Answer:
The advantages of the python programming language are as following:
1. Easy to learn2. Less lines of code
3. Cross Platform Language
4. Open source Language
5. Wide range of Libraries
6. Support OOPs Concepts
7. Portable and Interactive
8. Used for AI and Machine Learning based models
Q2.In how many different ways can you work in python?
Answer:
The two ways to work in python are:
1) Interactive Mode2) Script Mode
Q3.What are the advantages/disadvantages of working in the interactive mode in Python?
Answer:
Advantages:
1) Display the output quickly2) Display the list of error then and there only
3) User can run single line code efficiently
4) No need to save the code and run the program separately
5) Support copy paste commands
Disadvantages:
1) Can’t save the program for future use
2) Large programs can’t written on interactive mode
3) Doesn’t allow to edit the written commands
4) Doesn’t allow to type a new command until errors are rectified
Q4.Write Python statement for the following in interactive mode:
(a) To display sum of 3, 8.0, 6*12 (b) To print sum of 16, 5.0, 44.0Answer:
a) 3 + 8 + 6*12 or 3 + 8 + (6*12)
b) print(16+5.0+44.0)Q5.What are operators? Give examples of some unary and binary operators.
Answer:
The operators are the symbols used in the program that performs some specific task.
The unary and binary operators are as following:i) Unary Operators:+, -, Not
ii) Binary Operators: Arithmetic operators, Relational operators, Assignment Operators etc.
Q6. What is an expression and a statement?
Answer:
An expression is a combination of valid symbols in python that represents a value.
A statement is a formal instruction that performs a specific task.Q7. What all components can a Python program contain?
Answer:
The components of python program are as following:
i) Expressionii) Statement
iii) Indentation
iv) Block
v) Comments
vi) Functions
Q8. What are variables? How are they important for a program?
Answer:
Variables are names used in the program that holds a value for future use.
Variables are very important in the python program. Variables are the value holder for a program. They can be used as a container for the program and holds the input and output data values.Q9. Write the output of the following:
(i) for i in '123':
print("guru99", i)
Output-
guru99 1
guru99 2
guru99 3
(ii) for i in [ 100, 200, 300] :
print(i)
Output-
100
200
300
200
300
(iii) for j in range (10, 6, -2):
print (j * 2)
Output-
20
16
(iv) for x in range (1, 6):
for y in range (1, x+1) :
print (x,' ', y )
Output-
1 1
2 1
2 2
3 1
3 2
3 3
4 1
4 2
4 3
4 4
5 1
5 2
5 3
5 4
5 5
2 1
2 2
3 1
3 2
3 3
4 1
4 2
4 3
4 4
5 1
5 2
5 3
5 4
5 5
(v) for x in range (10, 20):
if (x == 15):
break print (x)
Output-
10
11
12
13
14
11
12
13
14
(vi) for x in range (10, 20) :
if (x % 2 == 0) :
continue print (x)
Output-
11
13
15
17
19
13
15
17
19
Q10. Write the output of the following program on execution if x = 50
if x > 10:
if x > 25:
print("ok")
if x 60 :
print("good")
elif x 40 :
print("average")
else:
print("no output")
Answer- Output: ok
Q11. What are the various ways of creating a list?
Answer:
The various ways of creating a list are are follows:
1. Empty List: [] –> Empty lists can be created when you need add values later or size is not fixed2. List of numeric values: [11,22,33,44,55] –> This list contains numbers as elements.
3. List of mixed numbers: [11,22.22,33.33,44] –> This list is a collection of integers and float numbers.
4. List of letters: [‘x’,’y’,’z’] –> This list is collection of letters or alphabets
5. List of words: [‘Hello’,’How’,’are’,’you’] –> This list is collection few words
6. List of mix different data types: [‘00001′,’Sagar’,10001,’12/12/2005′] –> This list is collection of a student record with different data values.
Q12. What are the similarities between strings and lists?
Answer:
String and lists are similar in the following ways:
1. They are created from a sequence
2. The individual elements can be accessed with index
3. Modified or traverse using slices
1. They are created from a sequence
2. The individual elements can be accessed with index
3. Modified or traverse using slices
Q13. Why are lists called a mutable data type?
Answer:
List elements can be modified directly so they are mutable data type.
Q14. What is the difference between insert() and append() methods of a list?
Answer:
The insert() method is used to insert an element at specifies index.
The append() method is used to insert an element to the end of the list.
Q15. Write a program to calculate the mean of a given list of numbers.
Answer:
List = []
n=int(input("Enter the no. of elements:"))
for i in range(n):
val=int(input("Enter the value to insert in the list:"))
List.append(val)
s = 0
for i in List:
s = s + i
mean = s/len(List)
print("The mean is:",mean)
Q16.Write a program to calculate the minimum element of a given list of numbers.
Answer:
List = []
n=int(input("Enter the no. of elements:"))
for i in range(n):
val=int(input("Enter the value to insert in the list:")
List.append(val)
mini =List[0]
for i in List:
if i < mini:
mini= i
print("The mean is:", mini)
Q17. Write a code to calculate and display total marks and percentage of a student from a given list storing the marks of a student.
Answer:
List = []
n=int(input("Enter the no. of subjects:"))
mm=int(input("Enter Maximum makrs for each subject:"))
for i in range(n):
val=int(input("Enter marks of subject "+str(i+1)+" out of "+str(mm)+":"))
List.append(val)
s = 0
for i in List:
s=s+i
per=(s/(mm*len(List)))*100
print("The mean is:%.2f",per)
Q18. Write a Program to multiply an element by 2 if it is an odd index for a given list containing both numbers and strings.
Answer:
List = []
n=int(input("Enter the no. of elements:"))
for i in range(n):
val=int(input("Enter the value to insert in the list:"))
List.append(val)
s = 0
for i in range(len(List)):
if i==0:
pass
elif i%2!=0:
List[i]*=2
print("New List is:")
for i in range(len(List)):
print("List[",i,"]:",List[i])
Q19. Write a Program to count the frequency of an element in a given list.
Answer:
lst = eval(input("Enter a list :-"))
for i in lst :
feq = lst.count(i)
print("Frequency of ",i,"=",feq)
Q20. Write a Program to shift elements of a list so that the first element moves to the second index and second index moves to the third index, and so on, and the last element shifts to the first position.
Suppose the list is [10, 20, 30, 40]
After shifting, it should look like: [40, 10, 20, 30]
Answer:
lst = eval(input("Enter a list="))
print("New list=",[lst[-1]]+lst[0:-1])
Q21. A list Num contains the following elements:
3, 25, 13, 6, 35, 8, 14, 45
Write a function to swap the content with the next value divisible by 5 so that the resultant list will look like:
25, 3, 13, 35, 6, 8, 45, 14
Answer:
num=[3, 25, 13, 6, 35, 8, 14, 45]
for i in range(len(num) -1):
if num[i+1] % 5 == 0:
num[i],num[i+1]=num[i+1],num[i]
print(num)
Q22. Write a program to accept values from a user in a tuple. Add a tuple to it and display its elements one by one. Also display its maximum and minimum value.
Answer:
tup = eval(input("Enter a tuple :-"))
for i in tup :
print(i)
print(tup)
print("maximum value :- ", max(tup))
print("minimum value :- ", min(tup))
Q23. Write a program to input any values for two tuples. Print it, interchange it and then compare them.
Answer:
t1 = eval(input("Enter tuple 1:"))
t2 = eval(input("Enter tuple 2:"))
t1,t2 = t2,t1
print("Tuple 1:",t1)
print("Tuple 2: ",t2)
print("Result of Tuple 1 < Tuple 2:",t1 < t2)
print("Result of Tupl1 > Tuple 2:",t1 > t2)
print("Tuple 1 and Tuple 2 are equal?:",t1 == t2)
Q24. Write a Python program to input ‘n’ classes and names of their class teachers to store them in a dictionary and display the same. Also accept a particular class from the user and display the name of the class teacher of that class.
Answer:
dic = {}
while True :
clas = int(input("Enter class :-"))
teach = input("Enter class teacher name :-")
dic[clas]= teach
a = input("Do you want to enter more records enter (Yes/ No)")
if a == "No" or a == "no":
break
clas = int(input("Enter class which you want to search"))
print("class teacher name",dic[clas])
Q25. Write a program to store student names and their percentage in a dictionary and delete a particular student name from the dictionary. Also display the dictionary after deletion.
Answer:
dic = {}
while True :
nam = input("Enter name :- ")
per = float(input("Enter percentage :- "))
dic[nam] = per
a = input("Do you want to enter more records enter (Yes/ No) :- ")
print()
if a == "No" or a == "no":
break
clas = input("Enter name which you want to delete :- ")
del dic[clas]
print("Dictionary",dic)
Q26. Write a Python program to input names of 'n' customers and their details like items bought, cost and phone number, etc., store them in a dictionary and display all the details in a tabular form.
Answer:
dic = {}
while True :
nam = input("Enter name :- ")
phone = float(input("Enter phone number :- "))
cost = float(input("Enter cost :- "))
item = input("Enter item :- ")
dic[ nam ] = [ phone , item , cost ]
a = input("Do you want to enter more records enter (Yes/ No) :- ")
if a == "No" or a == "no":
break
#dic[nam]=[phone,cost,item]
#print(dic)
for i in dic :
print()
print("Name : ", i )
print("Phone : ", dic[ i ][ 0 ] , "\t", "Cost : ", dic[ i ][ 1 ] , "\t", "Item : ", dic[ i ][ 2 ])
Q27.Write a Python program to capitalize first and last letters of each word of a given string.
Answer:
string = input("Enter a string :-")
new_str = string[0].upper()+string[1:-1]+string[-1].upper()
print(new_str)
Q28. Write a Python program to remove duplicate characters of a given string.
Answer:
string = input("Enter a string :- ")
new_str = ""
for i in string:
if i not in new_str :
new_str += i
print(new_str)
Q29. Write a Python program to compute sum of digits of a given string.
Answer:
txt=input("Enter the string in digit:")
sod=0
for i in txt:
if i.isdigit():
d=int(i)
sod=sod+d
else:
print("Enter the string in digits")
print("Sum of digit:",sod)
Q30. Write a Python program to find the second most repeated word in a given string.
Answer:
string = input("Enter a string :-")
lst = string.split()
max = 0
for i in lst:
if lst.count(i) >= max :
max = lst.count(i)
secmaxvalue = i
print("Second most repeated word :-", secmaxvalue )
Q31. Write a Python program to change a given string to a new string where the first and last chars have been exchanged.
Answer:
string = input("Enter a string :-")
new_str = string[-1] + string[1:-1] + string[0]
print(new_str)
Q32. Write a Python program to multiply all the items in a list.
Answer:
lst = eval(input("Enter a list :-"))
mul = 1
for i in lst :
mul *= i
print(mul)
Q33. Write a Python program to get the smallest number from a list.
Answer:
lst = eval(input("Enter a list :-"))
lst.sort()
print("Smallest number :-", lst[0] )
Q34. Write a Python program to append a list to the second list.
Answer:
lst1 = eval(input("Enter Frist list :-"))
lst2 = eval(input("Enter Second list :-"))
lst1 += lst2
print(list(lst1))
Q35. Write a Python program to generate and print a list of first and last 5 elements where the values are square of numbers between 1 and 30 (both included).
Answer:
lst = [ ]
for i in range(1,6):
lst += [ i**2 ]
for i in range(6,26):
lst += [ i ]
for i in range(26,31):
lst += [ i**2 ]
print(lst)
Q36. Write a Python program to get unique values from a list.
Answer:
lst = eval (input("Enter a list :-"))
for i in lst:
if lst.count(i) == 1 :
print(i)
Q37. Write a Python program to convert a string to a list.
Answer:
string = list(input("Enter a string :-"))
print(string)
Q38. Write a Python script to concatenate the following dictionaries to create a new one:
d1 = {‘A’: 1, ‘B’: 2, ‘C’: 3}, d2 = {‘D’: 4}
Output should be: {‘A’: 1, ‘B’: 2, ‘C’: 3, ‘D’: 4}
Answer:
d1 = {"A": 1, "B": 2, "C": 3}
d2 = {"D": 4}
d1.update(d2)
print(d1)
Q39.Write a Python script to check if a given key already exists in a dictionary.
Answer:
d={}
n=int(input("Enter no. of elements:"))
for i in range(n):
name=input("Enter name "+str(i+1)+":")
bt=int(input("Enter items bought:"))
co=float(input("Cost of item:"))
ph_no=input("Enter Phone number:")
d[name]=[bt,co,ph_no]
key_search=input("Enter key to search:")
for i in d:
if key_search==i:
print("Items Bought:",d[i][0])
print("Items Cost:",d[i][1])
print("Phone Number:",d[i][2])
else:
print("Key is not present in the dictionery")
Q40. Write a Python script to print a dictionary where the keys are numbers between 1 and 15 (both included) and the values are squares of keys.
Sample Dictionary{1:1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 225}
Answer:
dic={}
for i in range(1,16):
dic[i] = i**2
print(dic)
Q41. Write a Python script to merge two Python dictionaries.
Answer:
d1 = eval(input("Enter first dictionary :- "))
d2 = eval(input("Enter second dictionary :- "))
d1.update(d2)
print(d1)
Q42. Write a Python program to sort a dictionary by key.
Answer:
d={}
n=int(input("Enter no. of elements:"))
for i in range(n):
name=input("Enter name "+str(i+1)+":")
bt=int(input("Enter items bought:"))
co=float(input("Cost of item:"))
ph_no=input("Enter Phone number:")
d[name]=[bt,co,ph_no]
for i in sorted(d.keys()):
print(i)
Q43. Write a Python program to combine two dictionary adding values for common keys.
d1 = {'a': 100, 'b': 200, 'c': 300}, d2 = {'a': 300, 'b': 200, 'd': 400}
Sample output:
Counter ({'a': 400, 'b': 400, 'c': 300, 'd': 400})
Answer:
d1 = {'a': 100, 'b': 200, 'c': 300}
d2 = {'a': 300, 'b': 200, 'd': 400}
print("Before operation \n",d1,"\n",d2)
for i in d2 :
if i in d1 :
d1[ i ] = d1[ i ] +d2[ i ]
else :
d1[ i ] = d2[ i ]
print("After Operation \n",d1)
Q44.Write a Python program to find the highest 3 values in a dictionary.
Answer:
d={'Shreya':10,'Ashita':20,'Vriddhi':30,'Ramandeep':40}
list1=list(d.values())
list1.sort()
print("Elements in the dictionary: \n",d)
print("Highest 3 values are:",list1[-1:-4:-1])
Q45. Write a Python program to sort a list alphabetically in a dictionary.
Answer:
dic = {}
lst = eval(input("Enter a alphabetically list :-"))
lst.sort()
for i in range(len(lst)):
dic[i+1] = lst[i]
print(dic)
Q46. Write a Python program to count number of items in a dictionary value that is a list.
Answer:
dic = eval (input("Enter a Dictionary:"))
lst = list( dic.values() )
print("Number of items:",len(lst))
Q47. Consider the following unsorted list: 105, 99, 10, 43, 62, 8. Write the passes of bubble sort for sorting the list in ascending order till the 3rd iteration. (Not in Syllabus 2023-24)
Answer:
lst = eval(input("Enter a list:"))
for j in range ( 3 ):
for i in range ( 2) :
if lst [ i ] > lst [ i + 1 ] :
lst [ i ] , lst [ i + 1 ] = lst [ i + 1 ] , lst [ i ]
print(lst)
Q48.What will be the status of the following list after the First, Second and Third pass of the insertion sort method used for arranging the following elements in descending order?(Not in Syllabus 2023-24)
28, 44, 97, 34, 50, 87
Answer:
def Bsort(l):
count = 0
for i in range(len(l) - 1, 0, -1):
for j in range(i):
if l[j] > l[j + 1]:
l[j],l[j+1] = l[j+1],l[j]
print(l)
count += 1
if count == 3:
break
lst = [105, 99, 10, 43, 62, 8]
Bsort(lst)
print()
print("Upto three iterations list will look like: " ,lst)
Q49.Evaluate the following expressions:
(a) 6*3+4**2//5-8 (b) 10>5 and 7>12 or not 18>3
Answer:
(a)13 (b) False
Q50. What is type casting?
Answer:
Type Casting is the method to convert the Python variable datatype into a certain data type in order to perform the required operation by users.
There can be two types of Type Casting in Python:
Python Implicit Type Conversion:
a=7
b=3.0
c=a+b
print(c)
print(type(c)) # Python automatically converts c to float as it is a float addition
Python Explicit Type Conversion:
a=5
n = float(a)
print(n)
print(type(n)) #type cast to float explicitly
Q51. What are comments in Python? How is a comment different from indentation?
Answer:
Indentation is used to indicate the block of code that belongs to a particular control structure, such as a for loop or an if statement. Comments are used to add notes and explanations to your code.
Indentation & Comments example:
for a in range(10):
print(a) #print(a) is leaving some space from left side and it is explained with the help of comment.
Post a Comment
Post a Comment