Chapter 1: Review of Python Class 12 Computer Science NCERT Solutions
The first chapter of Class 12 Computer Science (Python), titled \”Review of Python,\” revisits the foundational concepts of Python programming that students have learned in earlier classes. This chapter serves as a refresher, helping students strengthen their Python programming skills and preparing them for the more advanced topics ahead. By revisiting basic programming concepts such as variables, data types, control structures, and functions, this chapter ensures that students have a solid foundation for tackling the rest of the curriculum.
What You Will Learn in Chapter 1 – Review of Python
This chapter is designed to ensure that students are comfortable with the essential building blocks of Python programming. It emphasizes the importance of understanding basic concepts, which will be critical in solving problems throughout the course. Students will explore topics such as variables, operators, conditionals, loops, and functions, which are used in almost every Python program.
Key Topics Covered:
Introduction to Python
Python is a high-level, interpreted, and general-purpose programming language. It is known for its simplicity and readability, making it an ideal language for beginners.
Python’s syntax is simple and easy to understand, which helps programmers to write clean and efficient code.
Data Types and Variables
Python supports several data types, including integers, floating-point numbers, strings, and booleans.
Students will learn how to declare variables and assign values to them, and how to use Python’s built-in functions to manipulate different data types.
Operators in Python
This section covers various operators used in Python: arithmetic, relational, logical, and assignment operators.
Students will learn how to perform mathematical operations, compare values, and combine conditions using logical operators.
Control Structures
Conditional Statements: Understanding the
if
,elif
, andelse
statements to execute code based on specific conditions.Loops: Use of
for
andwhile
loops to repeat a block of code multiple times, making the program more efficient.
Functions
Functions in Python allow code to be reusable and modular. This section covers the basics of defining functions, passing arguments, and returning values.
Students will learn about built-in functions and how to create their own custom functions to simplify complex tasks.
Input and Output
This section covers how to take user input using the
input()
function and how to display output using theprint()
function.
Basic Error Handling
Introduction to basic error handling using
try
,except
, andfinally
blocks to handle exceptions that may occur during the execution of the program.
Class 12 Computer Science (Python) – Chapter 1 – Review of Python
NCERT Textbook Questions Solved – Class 12 Computer Science (Python)
TOPIC-1: Python Basics
Very Short Answer Type Questions (1 mark)
Question 1. Name the Python Library modules which need to be imported to invoke the following functions: load(), pow()
Answer: pickle, math
Question 2. Name the modules to which the following functions belong: Uniform(), fabs()
Answer: random, math
Question 3. Differentiate between the round() and floor() functions with the help of suitable example. [CBSE Comptt. 2016]
Answer: The function round() is used to convert a fractional number into the nearest whole number, whereas the function floor() is used to convert to the nearest lower whole number. For example: round(5.8) = 6, round(4.1) = 5, floor(6.9) = 6, floor(5.01) = 5.
Short Answer Type Questions (2 marks)
Question 1. Out of the following, find those identifiers, which cannot be used for naming Variables or functions in a Python program:
Total * Tax, While, Class, Switch, 3rd Row, finally, Column 31, Total
Answer: Total * Tax, Class, 3rd Row, finally
Question 2. Name the Python Library modules which need to be imported to invoke the following functions: sqrt(), dump()
Answer: math, pickle
Question 3. Out of the following, find the identifiers, which cannot be used for naming Variable or Functions in a Python program: [CBSE Delhi 2016]
_Cost, Price*Qty, float, switch, Address one, Delete, Number12, do
Answer: Price*Qty, float, Address one, do
Question 4. Out of the following find those identifiers, which cannot be used for naming Variable or Functions in a Python Program:
Days * Rent, For, A_price, Grand Total, do, 2Clients, Participant1, My city
Answer: Illegal variable or function names are Days * Rent, For, do, 2Clients, and Grand Total because they either use keywords, have spaces/operators, or start with an integer.
Question 5. Name the function/method required for [CBSE SQP 2015]:
Finding second occurrence of ‘m’ in “madam”.
Get the position of an item in the list.
Answer: find, index
Question 6. Which string method is used to implement the following:
To count the number of characters in the string: len(str)
To change the first character of the string into capital letter: str.capitalize()
To check whether a given character is a letter or a number: ch.isalnum()
To change lowercase to uppercase letter: str.upper()
Change one character into another character: str.replace(old, new)
Question 7. What is the difference between input() and raw_input()?
Answer: raw_input() takes the input as a string, whereas input() automatically determines the correct type based on user input. Use input() when expecting an integer and raw_input() when expecting a string.
Question 8. What are the two ways of output using print()?
Answer: Ordinarily, each print statement produces one line of output. You can end the print statement with a trailing comma to combine the results of multiple print statements into a single line.
Question 9. Why does the expression 2 + 3*4 result in the value 14 and not the value 24?
Answer: Operator precedence rules make the expression to be interpreted as 2 + (3*4), hence the result is 14.
Question 10. How many times will Python execute the code inside the following while loop? Justify your answers.
Code:
i = 0
while i < 0 and i > 2:
print(“Hello …”)
i = i + 1
Answer: 0 times. The condition i < 0 and i > 2 is never true, so the loop body is never executed.
Question 11. How many times will Python execute the code inside the following while loop?
Code:
i = 1
while i < 10000 and i > 0 and 1:
print(“Hello …”)
i = 2 * i
Answer: 14
Question 12. Convert the following for loop into a while loop:
Code:
for i in range(1, 100):
if i % 4 == 2:
print(i, “mod”, 4, “= 2”)
Answer:
i = 1
while i < 100:
if i % 4 == 2:
print(i, “mod”, 4, “= 2”)
i = i + 1
Question 13. Convert the following for loop into while loop:
Code:
for i in range(10):
for j in range(i):
print(‘$’)
print(“”)
Answer:
i = 0
while i < 10:
j = 0
while j < i:
print(‘$’)
j = j + 1
print(“”)
i = i + 1
Question 14. Rewrite the following for loop into while loop: [CBSE Text Book]
Code:
for a in range(25, 500, 25):
print(a)
Answer:
a = 25
while a < 500:
print(a)
a = a + 25
Question 15. Rewrite the following for loop into while loop: [CBSE Text Book]
Code:
for a in range(90, 9, -9):
print(a)
Answer:
a = 90
while a > 9:
print(a)
a = a – 9
Question 16. Convert the following while loop into for loop:
Code:
i = 0
while i < 100:
if i % 2 == 0:
print(i, “is even”)
else:
print(i, “is odd”)
i = i + 1
Answer:
for i in range(100):
if i % 2 == 0:
print(i, “is even”)
else:
print(i, “is odd”)
Very Short Answer Type Questions (1 mark)
Question 1: Name the Python Library modules which need to be imported to invoke the following functions: load() and pow()
Answer: load() – pickle, pow() – math
Question 2: Name the modules to which the following functions belong: uniform() and fabs()
Answer: uniform() – random, fabs() – math
Question 3: Differentiate between the round() and floor() functions with suitable examples.
Answer: round() rounds a number to the nearest integer, while floor() returns the greatest integer less than or equal to the number.
Example: round(5.8) = 6, round(4.1) = 4; floor(6.9) = 6, floor(5.01) = 5
Short Answer Type Questions (2 marks)
Question 1: Out of the following, find identifiers which cannot be used in a Python program: Total * Tax, While, Class, Switch, 3rd Row, finally, Column 31, Total
Answer: Total * Tax, Class, 3rd Row, finally
Question 2: Name the Python Library modules for the following functions: sqrt() and dump()
Answer: sqrt() – math, dump() – pickle
Question 3: Find the invalid identifiers from the list: _Cost, Price*Qty, float, switch, Address one, Delete, Number12, do
Answer: Price*Qty, float, Address one, do
Question 4: Find identifiers which cannot be used: Days * Rent, For, A_price, Grand Total, do, 2Clients, Participant1, My city
Answer: Days * Rent, For, Grand Total, do, 2Clients
Question 5: Name the functions used for: Finding second occurrence of ‘m’ in “madam”, Get the position of an item in a list
Answer: find(), index()
Question 6: String methods used for:
1. Count characters – len(str)
2. Capitalize first letter – str.capitalize()
3. Check if alphanumeric – str.isalnum()
4. Convert to uppercase – str.upper()
5. Replace character – str.replace(old, new)
Question 7: Difference between input() and raw_input()
Answer: raw_input() returns string input. input() evaluates the input and returns data in correct type (used in Python 2.x). In Python 3.x, input() behaves like raw_input().
Question 8: Two ways of output using print()
Answer: 1. Normal print with newline
2. Print using end=”” to continue on same line
Question 9: Why does 2 + 3*4 evaluate to 14?
Answer: Due to operator precedence: 3*4 is evaluated first, then added to 2 → result is 14
Question 10: Number of executions for:
Code:
i = 0
while i < 0 and i > 2:
print(“Hello …”)
i += 1
Answer: 0 times (condition is false initially)
Question 11: Number of executions for:
Code:
i = 1
while i < 10000 and i > 0 and 1:
print(“Hello …”)
i = 2 * i
Answer: 14 times
Question 12: Convert for loop into while loop:
Code:
i = 1
while i < 100:
if i % 4 == 2:
print(i, “mod”, 4, “= 2”)
i += 1
Question 13: Convert nested for loop into while loop:
Code:
i = 0
while i < 10:
j = 0
while j < i:
print(‘$’, end=”)
j += 1
print()
i += 1
Question 14: Rewrite for a in range(25, 500, 25):
Answer:
a = 25
while a < 500:
print(a)
a += 25
Question 15: Rewrite for a in range(90, 9, -9):
Answer:
a = 90
while a > 9:
print(a)
a -= 9
Question 16: Convert the while loop into for loop:
Code:
for i in range(100):
if i % 2 == 0:
print(i, “is even”)
else:
print(i, “is odd”)
Question 17: Convert the while loop into for loop:
Code:
char = “”
print(“Press Tab Enter to stop …”)
for iteration in range(99):
if char != ‘t’:
print(“Continue?”)
char = input()
Question 18: Rewrite while loop:
Answer:
for i in range(10, 250, 50):
print(i)
Question 19: Rewrite while loop:
Answer:
for i in range(88, 7, -8):
print(i)
Question 20: Print series 10 to 300:
Answer:
for i in range(10, 301, 10):
print(i)
Question 21: Print series 105 to 7:
for i in range(105, 6, -7):
print(i)
Question 22: While loop for 5 to 100 (step 5):
i = 5
while i <= 100:
print(i)
i += 5
Question 23: Loop execution count:
for a in range(100, 10, -10):
Answer: 9 times
Question 24: Loop execution count:
i = 100
while i <= 200:
print(i)
i += 20
Answer: 6 times
Question 25: Is the statement true?
if (ch1 == ch2): print(“Equal”)
Answer: True
Question 26: Logical operators in Python
Answer: and, or, not
Question 27: Difference between ‘/’ and ‘//’
Answer:
/ – Normal division
// – Floor division
Question 28: Ways to import module
Answer:
1. import math
2. from math import sqrt
Question 29: Parameters vs Arguments
Answer:
Parameters – in function header
Arguments – in function call
Question 30: What are default arguments?
Answer: Parameters with default values in function definition
Question 31: What are keyword arguments?
Answer: Arguments passed by name instead of position
Question 32: Advantages of keyword arguments
Answer:
1. No need to remember order
2. Only needed parameters can be passed
Question 33: What does ‘in’ do?
Answer: Checks membership in a sequence.
Example: ‘Hell’ in ‘Hello World’ → True
Question 34: What does ‘not in’ do?
Answer: Checks if an item is not present in a sequence
Question 35: What does slice do?
Answer: Extracts part of a string using indices.
Example: s[0:4] → ‘Hell’ if s = “Hello World”
Question 36: What is the use of negative indices in slicing?
Answer: Python counts from the end (right) if negative indices are given.
Example:
S = “Hello”
print(S[:-3]) → He
print(S[-3:]) → llo
Question 37: Explain find() function?
Answer: find(sub[, start[, end]])
This function is used to search the first occurrence of the substring in the given string. It returns the index at which the substring starts. It returns -1 if the substring doesn’t occur.
Example:
str = “computer”
str.find(“om”) → 1
Question 38: What are the differences between arrays and lists?
Answer:
– An array holds a fixed number of values, while a list can be dynamically resized.
– An array holds values of a single data type. A list can hold values of mixed data types.
Question 39: What is the difference between a tuple and a list?
Answer:
– A tuple is immutable; a list is mutable.
– A tuple cannot be changed after creation; a list can be modified.
– Tuple uses parentheses (); list uses square brackets [].
Example:
Tuple: a = (2, 4, 5)
List: a = [2, 4, 5]
Question 40: Explain the output of the following code with respect to the scope of the variables.
Code:
x = 5
def func2():
x = 3
global x
x = x + 1
print(x)
print(x)
Output:
6
3
Explanation:
– The global x statement inside func2() accesses the global variable x and increments it.
– Hence, x = 5 + 1 → 6.
– When x = 3 is used, it creates a local variable, which does not affect the global x.
– So, 6 and then 3 is printed.
Question 41: Explain the two strategies employed by Python for memory allocation. [CBSE SQP 2016]
Answer: Python uses two strategies:
1. Reference Counting: Tracks the number of references to an object. When it reaches zero, the object is deleted.
2. Automatic Garbage Collection: Python reclaims unused memory when the number of allocations minus deallocations crosses a threshold.
Question 42: Rewrite the following code in Python after removing all syntax errors:
Code:
for Name in [“Amar”, “Shveta”, “Parag”]:
if Name[0] == ‘S’:
print(Name)
Question 43: Rewrite the following code in Python after removing all syntax errors:
Code:
for Name in [“Ramesh”, “Suraj”, “Priya”]:
if Name[0] == ‘S’:
print(Name)
Question 44: What will be the output of the following python code and explain try-except usage:
Code:
Start = 0
while True:
try:
Number = int(raw_input(“Enter Number”))
break
except ValueError:
start += 2
print(“Re-enter an integer”)
print(start)
Answer:
If user enters:
AMAR → Re-enter an integer
THREE → Re-enter an integer
A123 → Re-enter an integer
12006 → Correct entry
Output: 6
Explanation: The try block checks for valid integer input. If invalid (causes ValueError), control moves to except, increments start by 2, and prompts again.
Question 45: Give the output of the following with justification:
Code:
x = 3
x += x – x
print(x)
Answer: 3
Explanation: x = 3 + 3 – 3 = 3
Question 11. Write the output from the following code:
s = 0
for I in range(10, 2, -2):
s += I
print(“sum=”, s)
Answer: sum= 28
Question 12. Write the output from the following code:
n = 50
i = 5
s = 0
while i < n:
s += i
i += 10
print(“i=”, i)
print(“sum=”, s)
Answer: i= 55, sum= 125
Question 13. Same as Question 12 – Duplicate
Answer: i= 55, sum= 125
Question 14. Predict output for random code execution:
Code:
import random
x = 3
N = random.randint(1, x)
for i in range(N):
print(i, ‘#’, i + 1)
Answer:
Minimum number of executions: 1
Maximum number of executions: 3
Not expected output: 3#4
Question 15. Write the output of the following function:
Code:
def Findoutput():
L = “earn”
x = “”
count = 1
for i in L:
if i in [‘a’, ‘e’, ‘i’, ‘o’, ‘u’]:
x = x + i.swapcase()
else:
if (count % 2 != 0):
x = x + str(len(L[:count]))
else:
x = x + i
count += 1
print(x)
Findoutput()
Answer: EA3n
Question 16. Output of the following:
Numbers = [9, 18, 27, 36]
for N in Numbers:
print(N, “#”, end=” “)
print()
Answer: 9 # 18 # 27 # 36 #
Question 17. Predict outputs of random execution:
import random
PICK = random.randint(0, 3)
CITY = [“DELHI”, “MUMBAI”, “CHENNAI”, “KOLKATA”]
for I in CITY:
for J in range(1, PICK):
print(I, end=” “)
print()
Answer:
Max value of PICK: 3
Min value of PICK: 0
Possible Outputs: Option (i) and (iii) valid
Question 18. Output of nested loop:
Values = [10, 20, 30, 40]
for val in Values:
for I in range(1, val % 9):
print(I, “*”, end=” “)
print()
Answer:
1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 *
1 * 2 *
1 * 2 * 3 *
1 * 2 * 3 * 4 *
Question 19. Leap year check:
y = 2000
if y % 4 == 0:
print(“Leap Year”)
else:
print(“Not leap year”)
Answer: Leap Year
Question 20. Output of multiplication table:
for i in range(1, 10):
for j in range(1, 10):
print(i * j, end=” “)
print()
Answer:
1 2 3 4 5 6 7 8 9
2 4 6 8 10 12 14 16 18
3 6 9 12 15 18 21 24 27
…
9 18 27 36 45 54 63 72 81
Question 21. Print with syntax correction:
Incorrect:
print(‘Radhsa’s dress is pretty’)
Correct:
print(“Radhsa’s dress is pretty”)
Question 22. Replace character in string:
str = ‘Honesty is the best policy’
print(str.replace(‘o’, ‘*’))
Answer: H*nesty is the best p*licy
Question 23. Check title case:
str = ‘Hello Python’
print(str.istitle())
Answer: True
Question 24. Left strip characters:
str = ‘Hello Python’
print(str.lstrip(“Hel”))
Answer: lo Python
Question 25. Dictionary methods:
A = {10:1000, 20:2000, 30:3000, 40:4000, 50:5000}
print(A.items())
print(A.keys())
print(A.values())
Answer:
Items: [(10, 1000), (20, 2000), (30, 3000), (40, 4000), (50, 5000)]
Keys: [10, 20, 30, 40, 50]
Values: [1000, 2000, 3000, 4000, 5000]
Question 26. Length of a tuple:
t = (10, 20, 30, 40, 50)
print(len(t))
Answer: 5
Question 27. Max and min in a tuple:
t = (‘a’, ‘b’, ‘c’, ‘A’, ‘B’)
print(max(t))
print(min(t))
Answer:
max: ‘c’
min: ‘A’
Question 28. Max and min in numbers:
T = (10, 30, 2, 50, 5, 6, 100, 65)
print(max(T))
print(min(T))
Answer:
max: 100
min: 2
Question 29. Comparing tuples (Python 2.x):
T1 = (10, 20, 30, 40, 50)
T2 = (10, 20, 30, 40, 50)
T3 = (100, 200, 300)
cmp(T1, T2)
cmp(T2, T3)
cmp(T3, T1)
Answer:
0
-1
1
(Note: cmp() is not available in Python 3)
Question 30. Tuple concatenation:
T1 = (10, 20, 30, 40, 50)
T2 = (100, 200, 300)
T3 = T1 + T2
print(T3)
Answer: (10, 20, 30, 40, 50, 100, 200, 300)
Question 31.
t = tuple()
t = t + (‘Python’,)
print(t)
print(len(t))
t1 = (10, 20, 30)
print(len(t1))
Answer:
(‘Python’,)
1
3
Question 32.
Corrected Code:
for student in [“Jaya”, “Priya”, “Gagan”]:
if student[0] == ‘S’:
print(student)
Question 33.
Values = [11, 22, 33, 44]
for V in Values:
for NV in range(1, V % 10):
print(NV, V)
Answer:
1 11
1 22
2 22
1 33
2 33
3 33
1 44
2 44
3 44
4 44
Question 34.
import random
SEL = random.randint(0, 3)
ANIMAL = [“DEER”, “Monkey”, “COW”, “Kangaroo”]
for A in ANIMAL:
for AA in range(1, SEL):
print(A, end=””)
print()
Answer:
Possible outputs vary.
If SEL = 3:
DEERDEER
MonkeyMonkey
COWCOW
KangarooKangaroo
Maximum SEL: 3
Minimum SEL: 0
Correct option: (iv)
TOPIC-3: Random Functions
Question 1:
What are the possible outcome(s) executed from the following code? Also specify the maximum and minimum values that can be assigned to the variable PICKER.
import random
PICKER = random.randint(0, 3)
COLOR = [“BLUE”, “PINK”, “GREEN”, “RED”]
for I in COLOR:
for J in range(1, PICKER):
print(I, end=” “)
print()
Options:
(i)
BLUE
PINK
GREEN
RED
(ii)
BLUE PINK GREEN RED
(iii)
PINK PINK
GREEN GREEN
RED RED
(iv)
BLUEBLUE
BLUEPINK
PINKGREEN
REDRED
Answer:
Option (i) and (iv) are possible.
Maximum value of PICKER: 3
Minimum value of PICKER: 0
Question 2:
What are the possible outcome(s) expected from the following Python code? Also specify the maximum and minimum value, which we can have.
import random
def main():
p = “MY PROGRAM”
i = 0
while p[i] != “R”:
l = random.randint(0, 3) + 5
print(p[l], “-“, end=” “)
i += 1
Options:
(i) R – P – O – R –
(ii) P – O – R – Y –
(iii) O – R – A – G –
(iv) A – G – R – M –
Answer:
Minimum value = 5
Maximum value = 8
Only Option (iii) is valid.
TOPIC-4: Correcting the Errors
Question 1:
Rewrite the following Python code after removing all syntax errors.
Incorrect:
def main():
r = raw-input(‘enter any radius : ’)
a = pi * math.pow(r,2)
print “ Area = ” + a
Corrected Code:
import math
pi = 3.14
def main():
r = input(“Enter any radius: “)
a = pi * math.pow(float(r), 2)
print(“Area =”, a)
Question 2:
str = “Hello Python”
str[6] = ‘S’
Answer: Strings are immutable in Python. Use slicing:
str = str[:6] + “S” + str[7:]
Question 3:
T = [a, b, c]
print(T)
Answer: Variables not defined. Use strings:
T = [‘a’, ‘b’, ‘c’]
print(T)
Question 4:
Incorrect:
for i in 1 to 100:
print(i)
Corrected:
for i in range(1, 101):
print(i)
Question 5:
Incorrect:
i = 10
while [i <= n]:
print(i)
i += 10
Corrected:
i = 10
n = 100
while i <= n:
print(i)
i += 10
Question 6:
Incorrect:
if (a > b)
print a:
else if (a < b)
print b:
else
print “both are equal”
Corrected:
if a > b:
print(a)
elif a < b:
print(b)
else:
print(“both are equal”)
Question 7:
Incorrect:
c = dict()
n = input(“Enter total number”)
i = 1
while i <= n:
a = raw_input(“enter place”)
b = raw_input(“enter number”)
c[a] = b
i = i + 1
print “place”, “t”, “number”
for i in c:
print i, “t”, c[a[i]]
Corrected:
c = dict()
n = int(input(“Enter total number: “))
i = 1
while i <= n:
a = input(“Enter place: “)
b = input(“Enter number: “)
c[a] = b
i += 1
print(“PlacetNumber”)
for i in c:
print(i, “t”, c[i])
Question 8:
class info:
ips = 0
def __str__(self):
return “Welcome to the Info Systems”
def __init__(self):
self._Systemdate = “”
self.SystemTime = “”
def getinput(self):
self.Systemdate = input(“Enter date: “)
self.SystemTime = input(“Enter time: “)
def incrips(self):
info.ips += 1
i. Invoke Function 1:
print(I)
ii. Error Explanation:
_Systemdate is private, should be accessed using self._Systemdate or through a method.
TOPIC – 5: Short Programs
Q1: Area of Rectangle
length = float(input(“Enter length: “))
breadth = float(input(“Enter breadth: “))
print(“Area of rectangle =”, length * breadth)
Q2: Roots of a Quadratic Equation
import math
a = float(input(“Enter coefficient of x^2: “))
b = float(input(“Enter coefficient of x: “))
c = float(input(“Enter constant term: “))
d = b**2 – 4*a*c
if d == 0:
print(“Roots are real and equal”)
root1 = root2 = -b / (2*a)
elif d > 0:
print(“Roots are real and distinct”)
root1 = (-b + math.sqrt(d)) / (2*a)
root2 = (-b – math.sqrt(d)) / (2*a)
else:
print(“Roots are imaginary”)
print(“Roots of the equation are:”, root1, “and”, root2)
Q3: Print All Factors of a Number
n = int(input(“Enter the number: “))
for i in range(1, n + 1):
if n % i == 0:
print(i, “is a factor of”, n)
Q4: Armstrong Number Check
n = int(input(“Enter a number: “))
savedn = n
sum = 0
while n > 0:
a = n % 10
sum += a**3
n = n // 10
if savedn == sum:
print(savedn, “is an Armstrong Number”)
else:
print(savedn, “is not an Armstrong Number”)
Q5: Check Prime Number
n = int(input(“Enter the number: “))
flag = 0
for i in range(2, n):
if n % i == 0:
flag = 1
break
if flag == 0:
print(n, “is prime”)
else:
print(n, “is composite”)
Q6: Decimal to Binary
dec = int(input(“Enter the decimal to convert: “))
binary = “”
while dec > 0:
binary = str(dec % 2) + binary
dec = dec // 2
print(“Binary of the number is:”, binary)
Q7: Binary to Decimal
binary = input(“Enter binary number: “)
decimal = 0
for i in range(len(binary)):
power = len(binary) – i – 1
decimal += int(binary[i]) * (2 ** power)
print(“Decimal value is:”, decimal)
Q8: Sum of Two Complex Numbers
a_real = int(input(“Enter real part of first complex number: “))
a_img = int(input(“Enter imaginary part: “))
b_real = int(input(“Enter real part of second complex number: “))
b_img = int(input(“Enter imaginary part: “))
total_real = a_real + b_real
total_img = a_img + b_img
print(“Sum =”, total_real, “+ i”, total_img)
Q9: Product of Two Complex Numbers
a = int(input(“Enter real part of first complex number: “))
b = int(input(“Enter imaginary part: “))
c = int(input(“Enter real part of second complex number: “))
d = int(input(“Enter imaginary part: “))
real = a*c – b*d
img = a*d + b*c
print(“Product =”, real, “+ i”, img)
Q10: Sum of Digits
n = int(input(“Enter the number: “))
sum = 0
while n > 0:
digit = n % 10
sum += digit
n = n // 10
print(“Sum of digits =”, sum)
Question 11. Write a program to find the reverse of a number.
n = int(input(“Enter the number: “))
rev = 0
while n > 0:
a = n % 10
rev = (rev * 10) + a
n = n // 10
print(“Reversed number =”, rev)
Question 12. Write a program to print the pyramid.
for i in range(1, 6):
for j in range(1, i + 1):
print(i, end=” “)
print()
Question 13. Check username and password.
username = input(“Enter username: “)
password = input(“Enter password: “)
if username.strip() == “XXX”:
if password == “123”:
print(“Login successful”)
else:
print(“Password Incorrect”)
else:
print(“Username Incorrect”)
Question 14. Write a generator function generatesq()
import math
def generatesq(n):
for i in range(100, n):
yield math.sqrt(i)
for val in generatesq(105):
print(val)
Question 15. Write a method in Python to find and display the prime numbers between 2 to n.
def prime(N):
for a in range(2, N):
for i in range(2, a):
if a % i == 0:
break
else:
print(a)
Question 16. (Repeated same as Question 13)
Already answered above.
Question 17. String methods for specific tasks
To count characters: len(str)
To capitalize first character: str.capitalize() or str.title()
To check if character is letter/number: str.isalpha() or str.isdigit()
To convert to uppercase: str.upper()
To replace a character: str.replace(old, new)
Question 18. Write a program to input a string and find number of words.
s = input(“Enter a string: “)
words = s.split()
print(“Number of words:”, len(words))
Question 19. Write a program to input n numbers and insert a number at a particular position.
n = int(input(“Enter number of values: “))
num = []
for i in range(n):
number = int(input(“Enter the number: “))
num.append(number)
newno = int(input(“Enter the number to be inserted: “))
pos = int(input(“Enter position: “))
num.insert(pos, newno)
print(num)
Question 20. Write a program to input n numbers and search a number.
n = int(input(“Enter number of values: “))
num = []
for i in range(n):
number = int(input(“Enter the number: “))
num.append(number)
search = int(input(“Enter number to be searched: “))
flag = False
for i in range(n):
if num[i] == search:
print(search, “found at position”, i)
flag = True
break
if not flag:
print(search, “not found in list”)
Question 21. Write a program to search a customer number in phonebook.
def printlist(s):
for i in range(len(s)):
print(i, s[i])
phonenumbers = [‘9840012345’, ‘9840011111’, ‘9845622222’, ‘9850012345’, ‘9884412345’]
number = input(“Enter the phone number to be searched: “).strip()
try:
i = phonenumbers.index(number)
print(“Phone number found at index”, i)
except ValueError:
print(“Phone number not found in phonebook”)
print(“PHONEBOOK”)
printlist(phonenumbers)
Question 22. Reverse a list without built-in function.
n = int(input(“Enter number of values: “))
num = []
for i in range(n):
number = int(input(“Enter the number: “))
num.append(number)
for i in range(n // 2):
num[i], num[n-i-1] = num[n-i-1], num[i]
print(“Reversed list:”, num)
Question 23. Output of the Client class program:
class Client:
def __init__(self, ID=1, NM=”Noname”):
self.CID = ID
self.Name = NM
def Allocate(self, changelD, Title):
self.CID = self.CID + changelD
self.Name = Title + self.Name
def Display(self):
print(self.CID, “#”, self.Name)
C1 = Client()
C2 = Client(102)
C3 = Client(205, “Fedrick”)
C1.Display()
C2.Display()
C3.Display()
C2.Allocate(4, “Ms.”)
C3.Allocate(2, “Mr.”)
C1.Allocate(1, “Mrs.”)
C1.Display()
C2.Display()
C3.Display()
Output:
1 # Noname
102 # Noname
205 # Fedrick
2 # Mrs.Noname
106 # Ms.Noname
207 # Mr.Fedrick
Question 24. Output and explanation of try-except usage.
count = 0
while True:
try:
number = int(input(“Input a Number: “))
break
except ValueError:
count += 2
print(count, “Re-enter Number”)
Explanation: If the user inputs a non-integer, the except block increases count by 2 and prompts again.
Question 25. Write a method in Python to display prime numbers between 2 to N.
def prime(N):
for a in range(2, N):
is_prime = True
for i in range(2, int(a**0.5) + 1):
if a % i == 0:
is_prime = False
break
if is_prime:
print(a)
Question 1. (Stack Program for String Reversal)
class mystack:
def __init__(self):
self.mystr = input(“Enter the string: “)
self.mylist = list(self.mystr)
def display(self):
if len(self.mylist) > 0:
print(“Reversed string using stack:”)
while self.mylist:
print(self.mylist.pop(), end=””)
print()
else:
print(“Stack is empty”)
Sample Output:
Enter the string: Python
Reversed string using stack:
nohtyP
Explanation:
A stack works on the principle of LIFO (Last In, First Out). Using pop() in a loop reverses the string efficiently.