0% found this document useful (0 votes)
8 views10 pages

Chapter 1 Solution (Class 12)

The document provides a comprehensive review of Python basics, covering topics such as advantages of Python, modes of operation, operators, expressions, statements, variables, lists, and dictionaries. It includes various programming exercises and examples to illustrate concepts like list manipulation, tuple operations, and dictionary usage. The document serves as a foundational guide for understanding Python programming and its key components.

Uploaded by

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

Chapter 1 Solution (Class 12)

The document provides a comprehensive review of Python basics, covering topics such as advantages of Python, modes of operation, operators, expressions, statements, variables, lists, and dictionaries. It includes various programming exercises and examples to illustrate concepts like list manipulation, tuple operations, and dictionary usage. The document serves as a foundational guide for understanding Python programming and its key components.

Uploaded by

kainatsjs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Ch-1: REVIEW OF PYTHON BASICS

Unsolved Questions
1. What are the advantages of python programming language?
Ans 1. Python offers the following advantages:
(a)Platform-independent: It is platform-independent and can run across different
platforms like Windows, Linux/Unix, Mac OS and other operating systems. Thus, we can say that
Python is a portable language.
(b)Readability: Python programs use clear, simple, concise and English-like instructions
that are easy to read and understand even by non-programmers or people with no substantial
programming background.
(c)Object-oriented Language: It is an interactive, interpreted and object-oriented
programming language.
(d)GUI Programming: Python supports GUI applications that can be created and ported to
many system calls, libraries and window systems such as Windows MFC (Microsoft Foundation
Class Library), Macintosh and the X Window system of UNIX.

2. In how many ways different ways can you work in python?

Ans 2. In Python, we can work in two ways—Interactive mode (Shell) and Script mode.

3. What are the advantages /disadvantages of working in interactive mode in python?


Ans 3. Advantages:
• •Interactive mode is suitable for writing very short programs.

• •Interactive mode is useful for testing code.

• •In this mode, the result is obtained immediately after the execution of each line of code. Hence,it
runs very fast.

Disadvantages:
• •Interactive mode does not save commands in the form of a program and also output issandwiched
between commands.

4. Write python statement for the following in interactive mode:


a. To display sum of 3,8.0,6*12
b. To print the sum of 16,5.0,44.0
Ans 4.
Ans. (i) >>>3+8.0+6*12
(ii)>>>16+5.0+44.0

5. What are operators ? give some examples of some unary and binary operators.
Ans 5. Operators are special symbols which represent computation. They are applied on operand(s),
which can be values or variables.
Unary and Binary operators: An operator can be termed as unary or binary depending upon the number
of operands it takes. A unary operator takes only one operand and a binary operator takes two operands.
For example, in the expression –6 * 2 + 8 – 3, the first minus sign is a unary minus and the second minus
sign is a binary minus.
6. What is an expression and a statement?
Ans 6. Expression: An expression is a combination of symbols, operators and operands. An expression
represents some value. The outcome of an expression is always a value. For example, 3 * 7 + 10 is an
expression.
Statement: A statement is defined as any programming instruction given in Python as per the syntax. It is
given to execute a task. It may or may not return a value as the result. For example, print("Hello") is a
statement.
7. What all components can a python program contain?
Ans 7. The basic components of Python are character sets, tokens, expressions, statements,
operators and input-output, etc.
8. What are variables? How are they important for a program?
Ans 8. Variable is the user-defined name given to a value. Variables are not fixed/reserved. These are
defined by the user but they can have letters, digits and an underscore. They must begin with either a
letter or underscore. For example, _age, name, result_1, etc. Variables are very important building blocks
of any programming language as they allow programmers to store their values in user-defined variables
which they can use later in the program.
9. write the output of the following program:
Ans 9. (i)
guru99 1
guru99 2
guru99 3
(ii)
100
200
300
(iii)
20
16
(iv)
11
21
22
31
32
33
41
42
43
44
51
52
53
54
55
(v)
15
(vi) 19
10. write the output of the following program
Ans 10. ok
11. what are the various ways of creating list?
Ans. 11. A list is a sequence data structure created by placing all the items (elements) inside a square
bracket [ ] separated by commas. The different ways to create a list are:
1. Creating an empty list. For example, L= [ ]
2. Creating a new list from an existing list using the list-slicing operation. For example,

lst=[1,2,3,4,5]
lst_new=lst[1:4]
3. Creating a list from an existing sequence using list () function. For example,

Str1=’Python’
Lst=list(Str1)
print (Lst)
4. Creating a list using the copy () function. For example,

Lst=[1,2,3,4,5]
Lst_new=Lst. Copy ()
print (Lst_new)
12. what are the similarities between strings and lists?
Ans 12. Similarities:
• • Both are sequence data types.
• • The elements of lists are enclosed with square brackets while strings can be enclosed with a
single quote, double quotes and triple quotes.

Dissimilarities:
• • Lists are mutable, unlike Strings.

13. why are lists called a mutable data type?

Ans 13. Lists are called mutable data types because values in the list can be modified in place, which
means that Python does not create a new list when you make changes to an element of a list.

14. what is the difference between insert() and append() methods.


Ans 14. The insert () function can be used to insert an element/object at a specified index in the list. It
takes two arguments: the index where an item/object is to be inserted and the item/element itself.
The append () method adds a single item to the end of the existing list. It doesn't create a new list;
rather, it modifies the original list.

15. write a program to calculate the mean of a given list of numbers.


Ans 15.
L=[20,45,50,54,60,64,68,70,72,74]
n=len(L)
s=sum(L)/n
print(s)
Or
import statistics
L=[20,45,50,54,60,64,68,70,72,74]
m=statistics. mean(L)
print("Mean of List is : ",m)

16. Write a program to calculate the minimum element of a given list of


numbers.
Ans 16.
lst = [5,3,4,7,6,8,7,5,2,3,9]
lst. sort()
print ("Minimum element of a list of numbers is ", lst[0])

17. Write a code to calculate and display total marks and percentage of
a student from a given list storing the marks of a student.
Ans 17.
lst=[]
n = int (input ("Enter the total subjects:"))
for i in range(n):
marks= eval (input ("Enter the marks in each subject:"))
lst. append(marks)
sum = 0
for i in lst:
sum = sum + i
Per=sum/n
print ("Total marks of student:", sum)
print ("Percentage of student:", Per)

18. Write a program to multiply an element by 2 if it is an odd index


for a given list containing both numbers and strings.
Ans 18. n=[6,'z',3,4,'y','c',5,7,'l']
for i in range (len(n)) :
if i % 2 != 0:
n[i] = n[i] * 2
print(n)

19. Write a program to count the frequency of an element in a list.


Ans 19. lst = [5,8,89,67,54,39,50,2,2,89,8,5]
n = len(lst)
element = int(input("Enter element:"))
c = 0
for i in range (0, n):
if element == lst[i]:
c=c+1
if c==0:
print("Not found")
else:
print(c)

20. 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]
Ans 20. lst=[10,20,30,40]
print("New list=",[lst[-1]]+lst[0:-1])

21. A list Num contains the following elements:


3, 25, 13, 6, 35, 8, 14, 45
Write a program 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
Ans 21. 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)

22. 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.
Ans 22.
tup1 = eval(input("Enter a tuple:"))
for i in tup1 :
print(i)
print(tup1)
print("Maximum value in tuple is :", max(tup1))
print("Minimum value in tuple is :", min(tup1))

23. Write a program to input any values for two tuples. Print it,
interchange it and then compare them.
Ans 23.
tup1 = eval(input("Enter elements in tuple 1:"))
24. Write a Python program to input 'n' classes and names of 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.
up2 = eval(input("Enter elements in tuple 2:"))
tup1,tup2 = tup2,tup1
print("Tuple 1:",tup1)
print("Tuple 2:",tup2)
print(tup1 < tup2)
print(tup1 > tup2)
print(tup1 == tup2)

24. Write a Python program to input 'n' classes and names of 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.
Ans 24.
Dict1 = {}
while True :
clas = int(input("Enter class:"))
t_name = input("Enter class teacher name:")
dic[clas]= t_name
x = input("Do you want to add more records Y/N")
if x == "N" or x == "n":
break
search= int(input("Enter class which you want to search"))
print("class teacher name",dic1[search])

25. 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.
Ans 25.
dic = {}
while True :
st_name = input("Enter name :")
per = float(input("Enter percentage :"))
dic[st_name] = per
a = input("Do you want to add more records Y/N")
if a == "N" or a == "n":
break
name = input("Enter name which you want to delete :")
del dic[name]
print("Dictionary",dic)
26. 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.
Ans 26.
Dict1 = {}
while True :
cust_name= input("Enter Customer name:")
phone = int(input("Enter phone number:"))
item_name = input("Enter item :-")
cost = float(input("Enter cost :-"))
Dict1[cust_name] = [phone,item_name,cost]
p = input("Do you want to add more records press (Y/N) : ")
if p == "N" or p == "n":
break
for i in Dict1 :
print()
print(" Customer Name : ",i)
print("Phone Number:",Dict1[i][0],"\t","Item name:",Dict1[i][1],"\
t","Cost:",Dict1[i][2])

27. Write a Python program to capitalize first and last letters of each word of a given string.
Ans 27.
str1='Python is easy to learn'
str1= str1.title()
output = ""
for word in str1.split():
output =output+ word[:-1] + word[-1].upper() + " "
print(output[:-1])

28. Write a Python program to remove duplicate characters of a given


string.
Ans 28.
str1 = input("Enter a string:")
new_str = ""
for i in str1:
if i not in new_str :
new_str += i
print(new_str)
29. Write a Python program to compute sum of digits of a given number.
Ans 29.
str1 = input("Enter your string: ")
sum = 0
for i in str1:
if i.isdigit():
sum += int(i)
print("Total: ", sum)

30. Write a Python program to find the second most repeated word in a
given string.
Ans 30.
string = input("Enter a string :")
lst = string.split()
max = 0
for i in lst:
if lst.count(i) > max :
max = lst.count(i)
maxvalue = i
print(maxvalue)

31. Write a Python program to change a given string to a new string


where the first and last characters have been exchanged.
Ans 31.
str1 = input("Enter a string :")
new_str = str1[-1] + str1[1:-1] + str1[0]
print(new_str)

32. Write a Python program to multiply all the items in a list.


Ans 32.
lst = [10,2,3,5,100]
prod = 1
for i in lst :
prod =prod* i
print(prod)

33. Write a Python program to get the smallest number from a list.
Ans 33.
lst = [70,6,4,60,90,34,56,27,10]
lst.sort()
print("Minimum element is ",lst[0])

34. Write a Python program to append a list to the second list.


Ans 34.
lst1 = eval(input("Enter elements in list 1:"))
lst2 = eval(input("Enter elements in list 2 :"))
l1=list(lst1)
l2=list(lst2)
l1.extend(l2)
print(l1)

35. 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).
Ans 35.
Lst1 = [ ]
for i in range(1,6):
lst1 =lst+ [ i**2 ]
for i in range(6,26):
lst1=lst+ [i]
for i in range(26,31):
lst1=lst1+ [i**2]
print(lst1)
36. Write a Python program to get unique values from a list.
Ans 36.
lst = eval (input("Enter a list :"))
for i in lst:
if lst.count(i) == 1 :
print(i)

37. Write a Python program to convert a string to a list.


Ans 37.
string = input("Enter a string:")
print(list(string))

38. Write a Python script to concatenate the following dictionaries to


create a new one:
dl = {'A':1, 'B':2, 'C':3}
d2 = {'D':4}
Output should be:
{'A':1, 'B':2, 'C':3, 'D':4}
Ans 38.
d1 = {'A':1, 'B':2, 'C':3}
d2 = {'D':4}
d1.update(d2)
print(d1)

39. Write a Python script to check if a given key already exists in a


dictionary.
belis atzil 976 VW EL
Ans 39. This program is not possible because the Python dictionary accepts only unique keys.

40. Write a Python script to print a dictionary where the keys are numbers between 1 and 15 (both
included) and the values are square 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}
Ans 40.
dic={}
for i in range(1,16):
dic[i] = i**2
print(dic)

41. Write a Python script to merge two Python dictionaries.


Ans 41.
d1 = eval(input("Enter first dictionary :- "))
d2 = eval(input("Enter second dictionary :- "))
d1.update(d2)
print(d1)

42. Write a Python program to sort a dictionary by key.


Ans 42.
n=int(input("Enter number of key-value pairs"))
dict1={}
i=1
while i<=n:
key1=int(input ("key"))
value1=input("enter value")
dict1[key1]=value1
i=i+1
for k in sorted(dict1.keys()):
print(k)

43. Write a Python program to combine two dictionaries 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})
Ans 43.
d1 = {'a': 100, 'b': 200, 'c': 300}
d2 = {'a': 300, 'b': 200, 'd': 400}
for i in d2 :
if i in d1 :
d1[ i ] = d1[ i ] +d2[ i ]
else :
d1[ i ] = d2[ i ]
print(d1)

44. Write a Python program to find the three highest values in a


dictionary.
Ans 44.
dict1={1:10,2:200,3:300,4:400,5:600}
val = list( dict1.values() )
val.sort()
print("Highest 3 values ",val[ - 1 : - 4 : - 1])

45. Write a Python program to sort a list alphabetically in a dictionary.


Ans 45.
dic = {}
lst = ['a','c','b','d','c','d','e']
lst.sort()
for i in range(len(lst)):
dic[ i + 1 ] = lst [ i ]
print(dic)

46. Write a Python program to count number of items in a dictionary


value that is a list.
Ans 46.
dict1 = eval (input("Enter a Dictionary :-"))
lst = list( dict1.values() )
print("Number of items :-",len(lst))

47. 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.
Ans 47.
[99, 105, 10, 43, 62, 8] Pass -1
[99, 10, 105, 43, 62, 8] Pass-2
[99, 10, 43, 105, 62, 8] Pass - 3

48. 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?
928, 44, 97, 34, 50, 87
Note: Show the status of all the elements after each pass very clearly
underlining the changes.
Ans 48.
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

49. Evaluate the following expressions:


(a) 6*3+4**2//5-8
Ans 49.
(i) 13
(ii) False

[CBSE Sample Paper 2020-21]


(b) 10>5 and 7>12 or not 18>3

50. What is type casting?


Ans 50.
Type casting refers to changing a variable of one data type into another. There are two types of type
casting: Implicit and Explicit.

51. What are comments in Python? How is a comment different from indentation?
Ans 51.
Comments provide explanatory notes to the readers of the program. Compiler or interpreter ignores the
comments but they are useful for specifying additional descriptive information regarding the code and
logic of the program. Indentation makes the program more readable and presentable. Its main role is to
highlight nesting of groups of control statements.

You might also like