Anjeev Singh Academy

Anjeev Singh Academy

Chapter 1 – Python Revision Tour I


Class 12 Computer Science 083 Sumita Arora Book Solutions


Type A: Short Answer Questions / Conceptual Questions

1.    What are tokens in Python? How many types of tokens are allowed in Python? Exemplify your Answer.

Answer: Tokens are the smallest individual unit of a program. It is also known as lexical unit.

There are five types of tokens in python –

  • a) Keyword         b) Identifier             c) Literals      d) Operator              e) Punctuators

Example:

Name = “Anjeev Singh Academy”
Like = True
if Like == True:
    print(“Thank You, Share and Subscribe”)
else:
    print(“Please do Like, Share & Subscribe”)

Keyword  -> if , else , True
Identifier -> Name, Like
Literals     ->  “Anjeev Singh Academy”, True
Operators -> =, ==
Punctuator -> :

2.    How are keywords different from identifiers?

Answer: Keywords are reserved words, having special meanings reserved by the programming language.
The identifier is a user-defined word, used for naming variables, functions, classes, etc.
A keyword cannot be used as an identifier.

3.    What are literals in Python? How many types of literal are allowed in Python?

Answer: Literals are the constant values, which cannot be changed.

There are four types of literal –

  • String Literals – Set of characters written inside the quotes (single or double or tipple quotes). String literals can either be single line or multi-line strings.
  • Numeric Literals – Numbers are called numeric literals. Three types of numeric literals.
    • int    – int is called Singed Integers. Number without decimal point.
      • Decimal form – integer beginning with digit 1-9.  Eg. 1258, 5986
      • Octal form – an integer beginning with 0o (zero followed by o). 0o536
      • Hexadecimal form – an integer beginning with 0x (zero followed by letter X). eg. 0x59A, 0xAC5
    • float – Number with decimal point called floating point literals or real literals floats.
      • Fractional Form – 0.126, 569.3698
      • Scientific Form – 0.12E5, 3.E2, .6E-05
  • Complex – are the form a + bj, where a & b are floats, and j is √-1, which is imaginary number. a is the real part and b is the imaginary part.
  • Boolean Literals – True or False is known as Boolean literals.
  • None – None is a special literal. It is use to indicate absence of value.

4. State True or False: “Variable declaration is implicit type in Python” [CBSE SP 2023]

Answer: True

5. Out of the following, find those identifiers, which cannot be used for naming Variables or Functions in a Python program.  [CBSE D 2016]

       Price*Qty, class, For, do, 4thC01, totally, Row31, _Amount

Answer: Invalid Identifiers are –

  1. Price*Qty – Special symbol not allowed,
  2. class – Keyword is not allowed as an identifier,
  3. 4thC01 – Identifier cannot start with a digit.

6.    Find the invalid identifier from the following: [CBSE Sample Paper 2020-21]
(a) MyName    (b) True   (c) 2ndName   (d) My_Name

Answer: (b) True  – Keyword is not allowed.         (c) 2ndName – cannot start with a digit.

7. Which of the following is an invalid datatype in Python? [CBSE SP 2023]
(a) Set (b) None (c) Integer (d) Real

Answer: (d) Real

8.   Identify the valid arithmetic operator in Python from the following:  [CBSE Sample Paper 2020-21
(a)  ?               (b)  <       (c)  **              (d) and   

Answer: (c) ** [exponentiation operator]

9.    How are floating constants represented in Python? Give examples to support your Answer.

Answer:  float constants – Number with decimal point called floating point literals or real literals floats. It can be represented in two ways:-

  • Fractional Form – 0.126, 569.3698
  • Scientific Form – 0.12E5, 3.E2, .6E-05

10.    How are string literals represented and implemented in Python?

Answer: String Literals – Set of characters written inside the quotes (single or double or tipple quotes).

String literals can be represented and implemented

  • Single line  –
    “Hello How are You”
  • Multi-line strings  – can be written in two ways- (i) by using backslash and (ii) by using triple quotes
    By using backslash –

         “Hello \
         How are \
         You”

By using triple quotes (either single or double quote)

         ‘‘‘Hello
         How are you’’’

“““Hello
     How are you”””

11.    What are operators? What is their function? Give examples of some unary and binary operators.

Answer:  Operators are tokens that perform some action or operation on a variable or constant i.e. operands. The main function of the operator is to perform operations on the operand as per their category.

Unary Operators: Unary +, Unary -, not

Binary Operators: Arithmetic Operator, Relational Operator, Logical Operator, Assignment Operator, Membership Operator, Arithmetic Assignment Operator.     

12. Which of the following are valid operators in Python: [CBSE OD 2019]

        (i)  **  (ii) */   (iii) like   (iv) ||  (v) is   (vii) between  (viii) in

Answer: (i), (v) & (viii)

13.  What is an expression and a statement?

Answer: An expression is the valid combination of the operators, literals and variables. The expressions in Python can be of any type – Arithmetic expression, String expression, Relational expression, Logical expressions, Compound Expression.

14.  What all components can a Python program contain?

Answer: A python program consists of the following components-

  • (a) Expression   
  • (b) Statements        
  • (c) Comments
  • (d) Functions  
  • (e) Block(s)

15.  What are variables? How are they important for a program?

Answer: A variable is a named memory/storage location whose values can be changed during the program execution.

Variables are mainly used to store the values like students’ names, and student’s age. It helps in processing and storing data.

16. Consider the given expression: not True and False or True [CBSE SP 2023]
Which of the following will be the correct output if the given expression is evaluated?
(a) True (b) False (c) NONE (d) NULL

Answer: (a) True

Explanation: Note down the precedence of Logical Operator : not, and & or
not True and False or True => False and False or True => False or True => True

17.  Describe the concepts of block and body. What is indentation and how is it related to block and body?

Answer: A Block is a group of statements that are part of another statement or a function. The set of the statement(s) belonging to a particular statement (like if, else, loop, function) are called body.

In python, Indentation plays a vital role to create a block or body of a statement. Indentation means leaving space (4 to 8 spaces depending on the setting of IDE).

18. (a) What are data types? How are they important?

Answer:  Data types specify the type of data and associated operation. In Python, the interpreter implicitly identifies the data type based on value or literal.
It is important because through data type only a Python interpreter comes to know –

  • (a) how much memory is required.
  • (b) which operations are possible on it.
  • (c) what types of value can be stored.

18. (b) Write the names of any four data types available in Python.   [CBSE D 2019]

Answer: Four data types available in Python are – int, boolean, float, complex, string, tuple, list, dictionary,

19.  How many integer types are supported by Python? Name them.

Answer: Three types of integers are supported by Python. Decimal Integer, Octal Integer, and Hexadecimal Integer.

20.  What are immutable and mutable types? List immutable and mutable types of Python.

Answer: The types which do not allow to change of the value of the variable in place, are called Immutable types. The mutable types are those whose values can be changed in place.

Immutable types are integer, float, complex, boolean, string, and tuple.

Mutable types are List, Dictionary, and Sets.

21.  What is the difference between implicit type conversion and explicit type conversion?

Answer: An implicit type conversion is a conversion performed by the interpreter internally without the programmer’s intervention. Python converts all operands up to the type of the largest operand, called type promotion.

Explicit type conversion is a user-defined conversion that forces an expression to be of a specific type. The explicit type conversion is also known as type casting.

22.  An immutable data type is one that cannot change after being created. Give three reasons for immutable data.

Answer: The reasons behind immutable data are –

  • (a) It helps to create a constant.
  • (b) No one can change the value, so you can pass it freely to the function.
  • (c) It’s safe from the thread.

23.  What is an entry-controlled loop? Which loop is entry controlled loop in Python?

Answer: A loop that checks the conditions before entering inside the loop body i.e. before the execution of the loop body, is called an entry-controlled loop. In Python, while and for both are entry-controlled loops.

24.  Explain the use of the pass statement. Illustrate it with an example.

Answer: In Python, the pass is a null statement. The interpreter does not ignore a pass statement, but nothing happens and the statement results into no operation.

Sometimes we have to write the statement to complete the syntax, but we don’t want to write anything, for this purpose, we can use the pass statement.

x = 10
if x % 2  != 0:
   print("Odd Number")
else:
   pass

25.  Rewrite the following code in Python after removing all syntax error(s). Underline each correction done in the code.   [CBSE sample Paper]

30 = To
for K in range(0, To)
        IF k%4 == 0:  
print (K * 4)
       Else :
print (K + 3)                     

Answer:

26.   Below are seven segments of code, each with a part coloured. Indicate the data type of each coloured part by choosing the correct type of data from the following type.
(a) int      (b) float    (c) bool     (d) str    (e) function    (f) list of int     (g) list of str

(i)    if temp < 32:
print (“Freezing”)

Answer: (c) bool
Reason: < is a relational operator which returns either True or False.

(ii)   L = [ ‘Hiya’, ‘Zoya’, ‘Preet’]
      print(L[1])

Answer: (d) str
Reason: L is a list of Strings. When you write L[1], it returns the value at 1th index position. It is a string ‘Zoya’.

(iii) M = [ ]
        for i in range(3) :
                M.append(i)
                print(M)

Answer: (f) list of int
Reason: M is a list-type variable. Through append, you can add an item at the end of list. Here i is an integer value, which is appended in the list.

(iv) L = [ ‘Hiya’, ‘Zoya’, ‘Preet’ ]
n = len(L)
if ‘Donald’ in L[ 1 : n] :
print(L)

Answer: (a) int
Reason: n = len(L), this statement will calculate the length of list L, and assign an integer value to L. That’s why, n is an integer type variable.

(v)   if n % 2 = = 0:
print(“Freezing”)

Answer: (c) bool

(vi)  L = inputline.split( ) #split() converts the read line (i.e., inputline) into the words.
while L  != () :
                print(L)
                L = L [1 : ]

Answer: (g) list of str
Reason: split() split the string into the list of strings. By default, it splits the string on the space character.

(vii)        L = [ ‘Hiya’, ‘Zoya’, ‘Preet’ ]
        print( L[0] + L[1] )

Answer: str
Reason: L[0] gives ‘Hiya’ and L[1] gives ‘Zoya’. + is a string concatenation operator, which concatenates two string. So the final output of L[0] + L[1] = ‘Hiya’ + ‘Zoya’ = ‘HiyaZoya’, is a string.

24. Write the output of the following Python code: [CBSE 2020 C]
                for i in range(2, 7, 2 ) :
                        print ( i * ‘$’)

Answer:
$$
$$$$
$$$$$$

Ch. 2- Python Revision Tour – II Solution of Sumita Arora


Type B: Application-based Questions – Python Revision Tour I Sumita Arora Book Exercise Solution


Question 1.
Fill in the missing lines of code in the following code. The code reads in a limit amount and a list of prices and prints the largest price that is less than the limit. You can assume that all prices and the limit are positive numbers. When a price 0 is entered the program terminates and prints the largest price that is less than the limit.

#Read the limit
limit = float(input(“Enter the limit”))
max_price = 0
# Read the next price
next_price = float(input(“Enter a price or 0 to stop:”))
while next_price > 0 :
<write your code here>
#Read the next price
<write your code here>
if max_price > 0:
<write your code here>
else :
<write your code here>

Answer:

#Read the limit 
limit = float(input(“Enter the limit”)) 
max_price = 0
# Read the next price 
next_price = float(input(“Enter a price or 0 to stop:”)) 
while next_price > 0 :
    if next_price > max_price and next_price < limit:
	max_price = next_price
    #Read the next price
    next_price = float(input(“Enter a price or 0 to stop:”))
if max_price > 0:
    print(“The largest price is”, max_price)
else :
    print(“The largest price can not be 0 or less than 0”)

Question 2.
Predict the outputs of the following programs :

(a) 

count = 0 
while count < 10:
    print (‘Hello’) 
    count += 1

Answer:
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello

(b)      

x = 10
y = 0	
while x > y: 
   print(x, y) 
   x = x - 1
   y = y + 1

Answer:
10 0
9 1
8 2
7 3
6 4

(c) 

keepgoing = True 
x = 100
while keepgoing : 
    print(x) 
  
    x = x - 10 
    if x < 50:
        keepgoing = False

Answer:
100
90
80
70
60
50

(d)       

x = 45 
while x < 50:
    print(x)

Answer: It prints 45 infinite times.

(e)  

for x in [1,2,3,4,5]: 	
    print(x)

Answer:
1
2
3
4
5

(f)         

for p in range(l, 10) : 
    print(p)

Answer:
1
2
3
4
5
6
7
8
9

(g)               

for z in range(-500, 500, l00) :  
    print(z)   

Answer:
-500
-400
-300
-200
-100
0
100
200
300
400

(h)         

x = 10
y = 5
for i in range(x - y * 2): 
    print(“%”, i)

Answer: No output

(i)     

c = 0
for x in range(10) :
    for y in range(5):
	c += 1
print(c)

Answer: 50

(j)           

x = [1,2, 3]
counter = 0
while counter < len(x) : 
    print(x[counter] * ‘%’) 
    for y in x:  
       print (y * ‘*’)
    counter += 1 

Answer:
%
*
**
***
%%
*
**
***
%%%
*
**
***

(k)     

for x in 'lamp' : 
    print(str.upper(x))

Answer:
L
A
M
P

(l)           

x = 'one' 
y = 'two' 
counter = 0 
while counter < len(x) : 
    print (x[counter], y[counter] ) 
    counter += 1

Answer:
o t
n w
e o

(m)       

x = "apple, pear, peach" 
y = x. split(", ") 
for z in y : 
   print(z) 

Answer:
apple
pear
peach

(n)         

x = 'apple, pear, peach, grapefruit'
y = x. split(", ") 
for z in y:
   if z < 'm’:
      print(str.lower(z)) 
   else:
      print(str.upper(z))

Answer:

apple
PEAR
PEACH
Grapefruit

4. How many times will the following for loop execute and what’s the output?

(i)

for i in range(-1,7, -2):	
    for j in range (3) :	
       print(l, j)

Answer: Zero Times, No Output

(ii)

for i in range(1,3,1):
    for j in range(i+l) :
	    print('*')

Answer: Five Times

Output:
*
*
*
*
*

Question 3.
Which of the following is the correct output for the execution of the following Python statement? [CBSE Paper 2021 Term 1]
print(5 + 3 ** 2 /2)
(a) 32 (b) 8.0 (c) 9.5 (d) 32.0

Answer: (c) 9.5
Reason: Precedence of Operator (High to low): ** (exponentiation), / (division) and + (addition)
5 + 3**2 / 2
= 5 + 9 / 2
= 5 + 4.5
= 9.5

Question 4.
Find the output of the following Python code:  

for Name in  ['Jayes’, ‘Ramya’ , ‘Taruna’, ‘Suraj'] : 
    print (Name)
    if Name[0] == ‘T’:
	    break 
    else :
       print ('Finished!’)  
print ('Got it!’)

Answer:
Jayes
Finished!
Ramya
Finished!
Taruna
Got it!

5. Is the loop in the code below infinite? How do you know (for sure) before you run it?

m = 3
n = 5
while n < 10 :
   m = n - 1
   n = 2 * n – m
   print (n, m)

Answer: No
6 4
7 5
8 6
9 7
10 8


Ch. 2- Python Revision Tour – II Solution of Sumita Arora


Type C: Programming Practice/Knowledge-based Questions – Python Revision Tour I Sumita Arora Book Exercise Solution


1.     Write a program to print one of the words negative, zero, or positive, according to whether variable x is less than zero, zero, or greater than zero, respectively.

#Que - 1

x = int(input("Enter a Number : "))

if x < 0:
    print("Negative")
elif x == 0:
    print("Zero")
else:
    print("Postitive")

Output:

Enter a Number: -5
Negative

Enter a Number: 0
Zero

Enter a Number: 8
Positive

2.     Write a program that returns True if an input number is an even number, and False otherwise.

#Que - 2

x = int(input("Enter a Number : "))

if x % 2 == 0:
   print("Even Number => ", True)
else:
   print("Even Number => ", False)

Output:

Enter a Number: 9
Even Number => False

Enter a Number: 8
Even Number => True

3.     Write a Python program that calculates and prints the number of seconds in a year.

#Que - 3

year = int(input("Enter Year : "))

if (year % 4 == 0 and year %100 != 0) or (year % 100 == 0 and year % 400 == 0):
    no_sec = 366 * 24 * 60 * 60
    print(year, "Leap year")
else:
    no_sec = 365 * 24 * 60 * 60
    print(year, "Not a Leap year")
    
print("Number of seconds in year", year,"is",no_sec)

Output:

Enter Year: 1900
1900 Not a Leap year
Number of seconds in year 1900 is 31536000

Enter Year : 2000
2000 Leap year
Number of seconds in year 2000 is 31622400

Enter Year : 2022
2022 Not a Leap year
Number of seconds in year 2022 is 31536000

4.     Write a Python program that accepts two integers from user and prints a message saying if first number is divisible by second number or if it is not.

#Que - 4
x = int(input("Enter Number 1 : "))
y = int(input("Enter Number 2 : "))

if x % y == 0:
    print("First number", x,"is divisible by second number", y)
else:
    print("Not divisible")

Output:

Enter Number 1 : 9
Enter Number 2 : 3
First number 9 is divisible by second number 3

Enter Number 1 : 15
Enter Number 2 : 4
Not divisible

5.     Write a program that asks the day number in a year in the range 2 to 365 and asks the first day of the year –  Sunday or Monday or Tuesday etc. Then the program should display the day on the day number that has been input.

#Que - 5

day_number = int(input("Input Day number ranges 2 - 365 : "))

first_day_name = int(input("First Day of the year (0 to 6) i.e 0 - Sunday, 1 - Monday ... 6 - Saturday: "))

day_name = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]

new_day = (day_number % 7 + first_day_name - 1)%7 

print("The day on the ", day_number,"is ", day_name[new_day])

Output:

Input Day number ranges 2 – 365 : 6
First Day of the year (0 to 6) i.e 0 – Sunday, 1 – Monday … 6 – Saturday: 1
The day on the 6 is Saturday

Input Day number ranges 2 – 365 : 35
First Day of the year (0 to 6) i.e 0 – Sunday, 1 – Monday … 6 – Saturday: 3
The day on the 35 is Tuesday

6.  One foot equals 12 inches. Write a function that accepts a length written in feet as an argument and returns this length written in inches. Write a second function that asks the user for a number of feet and returns this value. Write a third function that accepts a number of inches and displays this to the screen. Use these three functions to write a program that asks the user for a number of feet and tells them the corresponding number of inches.

#Que - 6

def feet_to_inch(foot):
    return foot * 12

def input_feet():
    foot = int(input("Enter value in foot : "))
    return foot

def print_inch(inch):
    print("Value in inch : ",inch)

feet = input_feet()

inch = feet_to_inch(feet)

print_inch(inch)

Output:

Enter value in foot : 12
Value in inch : 144

Enter value in foot : 19
Value in inch : 228

7. Write a program that reads an integer N from keyboard computes and displays sum of numbers from N to (2 * N) if N is nonnegative. If N is a negative number, then it’s the sum of numbers from (2 * N) to N. The starting and ending points are included in the sum.

#Que - 7

N = int(input("Enter a number : "))

Sum = 0

print("Sum of =>")

if N > 0:
    for num in range(N, 2*N + 1):
        print(num, end=" ")
        Sum = Sum + num
elif N < 0:
    for num in range(2*N, N + 1):
        print(num, end=" ")
        Sum = Sum + num
        
print(" = ",Sum)

Output:

Enter a number : 5
Sum of =>
5 6 7 8 9 10 = 45

Enter a number : -5
Sum of =>
-10 -9 -8 -7 -6 -5 = -45

8.  Write a program that reads a date as an integer in the format MMDDYYYY. The program will call a function that prints print out the date in the format <Month Name> <day>, <year>.

Sample run:   Enter date: 12252019

                                 December 25, 2019

#Que - 8 : Method - 1

month = ['January', 'February', 'March', 'April',
         'May', 'June', 'July', 'August', 'September',
         'October', 'November', 'December']

dt = input("Enter Date in Integer MMDDYYY : ")

mm = dt[:2]
dd = dt[2:4]
yy = dt[4:]

print(month[int(mm)-1], dd,",",yy)

Enter Date in Integer MMDDYYY : 12022022
December 02 , 2022

#Que - 8 - Method 2

import datetime

DateInInt = input("Enter Date in Integer MMDDYYYY : ")

d = datetime.datetime.strptime(DateInInt,'%m%d%Y')

print(d.strftime('%B'), d.strftime('%d'),",",d.strftime('%Y'))

Output:

Enter Date in Integer MMDDYYY: 12022022
December 02 , 2022

9.  Write a program that prints a table on two columns —table that helps converting miles

#Que - 9
print("Miles - Kilometer")
print("-----------------")
for m in range(1,10):
    print(m, '-', m * 1.60934)
print("-----------------")

Output:

Miles – Kilometer
1 – 1.60934
2 – 3.21868
3 – 4.82802
4 – 6.43736
5 – 8.0467
6 – 9.65604
7 – 11.26538
8 – 12.87472
9 – 14.48406

10. Write another program printing a table with two columns that helps convert pounds in kilograms

#Que - 10
print("Pounds - Kilogram")
print("-----------------")
for m in range(1,10):
    print(m, '-', m * 0.453592)
print("-----------------")

Output:

Pounds – Kilogram
1 – 0.453592
2 – 0.907184
3 – 1.360776
4 – 1.814368
5 – 2.26796
6 – 2.721552
7 – 3.175144
8 – 3.628736
9 – 4.082328

11. Write a program that reads two times in military format (0900, 1730) and prints the number of hours and minutes between the two times. A sample run is being given:

Please enter the first time: 0900
Please enter the second time: 1730
8 hours 30 minutes

Method – 1

#Que - 11
#Two times in military format

start = input("enter start time in millitary format : ")
end = input("enter end time in millitary format :")

start_hh = int(start[0:2])  # extract hour part from start time
start_mm = int(start[2:]) # extract minute part from start time


end_hh = int(end[0:2]) # extract hour part from end time
end_mm = int(end[2:]) # extract hour part from end time


if end_mm < start_mm:   # check if end minute is less than the start minute
    end_hh = end_hh - 1        # subtract 1 from end hour
    end_mm = end_mm + 60  #add  60 to end minute

hh = end_hh - start_hh    # differece of hour
mm = end_mm - start_mm # difference of minute

print(hh, "hours", mm,"minutes")

Output:

enter start time in millitary format : 0900
enter end time in millitary format :1730
8 hours 30 minutes

enter start time in millitary format : 0950
enter end time in millitary format :1115
1 hours 25 minutes

Method – 2

#Que - 11
#Two times in military format

import datetime

firsttime = input("Please enter the first time : ")

ft = datetime.datetime.strptime(firsttime,'%H%M')

secondtime = input("Please enter the second time : ")
st = datetime.datetime.strptime(secondtime,'%H%M')

tdiff = st - ft  #tdiff is a timedelta object

seconds = tdiff.total_seconds()  #returns the time in seconds
hours = int(seconds // 3600)
minutes = int((seconds % 3600) // 60)

print(hours,"hours", minutes,"minutes")

Output:

Please enter the first time : 0900
Please enter the second time : 1730
8 hours 30 minutes

Please enter the first time : 1530
Please enter the second time : 2140
6 hours 10 minutes

Sorry! You cannot copy content of this page. Please contact, in case you want this content.

Scroll to Top