This page contains the CBSE Computer Science with Python class 12 Unit-1 chapter 1 Review Of Python. You can find the solutions for chapter 1 of CBSE class 12 Computer Science with Python Exercise. So is the case if you are looking for CBSE class 12 Computer Science with Python related topic Review Of Python questions and answers for the Exercise.
Question 1
1. Write the output from the following code:
(a)
x = 10y = 20if(x > y):print x + yelse:print x - y(b)
print "Inspirational stories\nfor\tChildren"(c)
s = 0for I in range(10, 2, -2):s += Iprint "sum=", s(d)
n = 50i = 5s = 0while i < n:s += ii += 10print "i=", iprint "sum=", s(e)
y = 2000if(y % 4 == 0):print "Leap Year"else:print "Not leap year"Answer 1
(a) Output:
-10
(b) Output:
Inspirational stories
for Children
(c) Output:
sum= 28
(d) Output:
i= 55
sum= 125
(e) Output:
Traceback (most recent call last):
File "review_of_python_q_01_e.py", line 2, in <module>
if i % 4 == 0:
^
NameError: name 'i' is not defined. Did you mean: 'id'?
Question 2
2. Write for statement to print the following series:
(a)
10, 20, 30, … 300
(b)
105, 98, 91, … 7
Answer 2
(a) 10, 20, 30, … 300
Python Program
# Print multiples of 10 from 10 to 300
# range(start, stop, step): stop is excluded
for i in range(10, 301, 10):
print i
Output
10
20
30
40
50
60
70
80
90
100
110
120
130
140
150
160
170
180
190
200
210
220
230
240
250
260
270
280
290
300
(b) 105, 98, 91, … 7
Python Program
# Print series from 105 down to 7 with step -7
# Negative step prints numbers in decreasing order
for i in range(105, 6, -7):
print i
Output
105
98
91
84
77
70
63
56
49
42
35
28
21
14
7
Question 3
3. Write the while loop to print the following series:
(a)
5, 10, 15, … 100
(b)
100, 98, 96, … 2.
Answer 3
(a) Write the loop to print the series 5, 10, 15, … 100
Python Code Snippet:
# Print series 5, 10, 15, ... 100
# Start at 5 and add 5 each time
i = 5
while i <= 100:
print i
i += 5
Output:
5
10
15
20
25
30
35
40
45
50
55
60
65
70
75
80
85
90
95
100
(b) Write the loop to print the series 100, 98, 96, … 2
Python Code Snippet:
# Print series 100, 98, 96, ... 2
# Start at 100 and subtract 2 each time
i = 100
while i >= 2:
print i
i -= 2
Output:
100
98
96
94
92
90
88
86
84
82
80
78
76
74
72
70
68
66
64
62
60
58
56
54
52
50
48
46
44
42
40
38
36
34
32
30
28
26
24
22
20
18
16
14
12
10
8
6
4
2
Question 4
4. How many times are the following loops executed?
(a)
for a in range(100, 10, -10):print a(b)
i = 100while (i <= 200):print ii += 20(c)
for b in (1, 10):print b(d)
i = 4while i >= 4:print ii += 10(e)
i = 2while i <= 25:print iAnswer 4
(a)
9 times
(b)
6 times
(c)
2 times
(d)
Infinite times (infinite loop)
(e)
File "/Users/allabakash/Documents/eduxir/website/site/study material/cbse/class 12/computer-science-with-python/delete.py", line 2
while (i<=25)
^
SyntaxError: expected ':'
After placing the colon, it executes
if we place the colon, it executes infinite times (infinite loop) because the value of i is not updated inside the loop.
Question 5
5. Rewrite the following for loop into while loop.
(a)
for a in range(25, 500, 25):print a(b)
for a in range(90, 9, -9):print aAnswer 5
(a) Conversion of the given for loop into while loop
# Equivalent while loop for range(25, 500, 25)
# Start at 25 and increase by 25 until value is less than 500
a = 25
while a < 500:
print a
a += 25
(b) Conversion of the given for loop into while loop
# Equivalent while loop for range(90, 9, -9)
# Start at 90 and decrease by 9 while value stays above 9
a = 90
while a > 9:
print a
a -= 9
Question 6
6. Rewrite the following while loop into for loop.
(a)
i = 10while i < 250:print ii = i + 50(b)
i = 88while (i >= 8):print ii -= 8Answer 6
(a) Conversion of while loop into for loop
# Equivalent for loop for i = 10; while i < 250; i += 50
# Generates: 10, 60, 110, 160, 210
for i in range(10, 250, 50):
print i
(b) Conversion of while loop into for loop
# Equivalent for loop for i = 88; while i >= 8; i -= 8
# Stop value is 7 so that 8 is still included
for i in range(88, 7, -8):
print i
Question 7
7. Which command is used to convert text into integer value?
Answer 7
The command(more precisely the function)
int() is used to convert text/string to integer.Python Code Snippet:
# Convert user input (string) to integer
# raw_input() always returns text in Python 2
x = int(raw_input("Enter a number: "))
Question 8
8. Find the errors from the following code.
(a)
T = [a, b, c]print T(b)
for i in 1 to 100:print I(c)
i = 10while [i <= n]:print ii += 10(d)
if (a > b)print a:else if (a < b)print b:elseprint "both are equal"Answer 8
(a) Errors:
•
Name Error:
a, b, and c are used without being defined.•
If characters were intended, they should be written as strings:
["a", "b", "c"].(b) Errors:
•
Syntax Error:
for i in 1 to 100: is invalid; Python uses range().•
Name Error:
print I uses uppercase I, but loop variable is lowercase i.(c) Errors:
•
Name Error:
n is not defined before using it in the condition.•
Condition Style Issue:
while [i <= n]: uses a list around the condition; it should be while i <= n:.(d) Errors:
•
Syntax Error: Missing colon
: after if, elif/else if, and else.•
Syntax Error: Python uses
elif, not else if.•
Syntax Error: Colons after
print statements are invalid.Question 9
9. Find the output from the following code:
L = [100, 200, 300, 400, 500]L1 = L[2:4]print L1L2 = L[1:5]print L2L2.extend(L1)print L2Answer 9
Output:
[300, 400]
[200, 300, 400, 500]
[200, 300, 400, 500, 300, 400]
Question 10
10. Write a program to input any number and print all factors of that number.
Answer 10
Python Program:
# Print all factors of a given number
# Read input number from user
n = int(raw_input("Enter a number: "))
print "Factors of", n, "are:"
# Check every number from 1 to n
i = 1
while i <= n:
# If remainder is 0, i is a factor
if n % i == 0:
print i,
i += 1
print
Sample Output:
Enter a number: 12
Factors of 12 are:
1 2 3 4 6 12
Question 11
11. Write a program to input any number and check whether the given number is Armstrong or not.
(Example: 153 = 13 + 53 + 33.)
Answer 11
Python Program:
# Check whether the number is an Armstrong number
# Take input and keep a copy for comparison
n = int(raw_input("Enter a number: "))
temp = n
s = 0
# Extract digits and add cubes of digits
while temp > 0:
d = temp % 10
s = s + (d*d*d)
temp = temp / 10
# Compare computed sum with original number
if s == n:
print "Result: Armstrong Number"
else:
print "Result: Not an Armstrong Number"
Sample Output:
Enter a number: 153
Result: Armstrong Number
Question 12
12. Write a program to input employee number, name, and basic pay, then find HRA, DA, and net pay.
Basic Pay
HRA
DA
> 100000
15%
8%
<= 100000 and > 50000
10%
5%
<= 50000
5%
3%
Answer 12
Python Program:
# Calculate HRA, DA and net pay based on basic salary slabs
# Input employee details
empno = raw_input("Enter employee number: ")
name = raw_input("Enter employee name: ")
basic = float(raw_input("Enter basic pay: "))
# Select HRA and DA percentage according to salary slab
if basic > 100000:
hra_rate = 15
da_rate = 8
elif basic <= 100000 and basic > 50000:
hra_rate = 10
da_rate = 5
else:
hra_rate = 5
da_rate = 3
# Calculate allowances and final net pay
hra = basic * hra_rate / 100
da = basic * da_rate / 100
netpay = basic + hra + da
print "Net Pay:", netpay
Sample Output:
Enter employee number: 101
Enter employee name: Amit
Enter basic pay: 60000
Net Pay: 69000.0
Question 13
13. Write a program to find all prime numbers up to a given number.
Answer 13
Python Program:
# Prime numbers up to n (console input/output)
# Read upper limit
n = int(raw_input("Enter a number: "))
print "Number:", n
print "Prime numbers:",
# Check each number from 2 to n
num = 2
while num <= n:
is_prime = True
d = 2
# Test divisibility up to square root of num
while d*d <= num:
if num % d == 0:
is_prime = False
break
d += 1
if is_prime:
print num,
num += 1
print
Sample Output:
Enter a number: 20
Number: 20
Prime numbers: 2 3 5 7 11 13 17 19
Question 14
14. Write a program to convert decimal number to binary.
Answer 14
Python Program:
# Decimal to Binary conversion
# Read decimal number
n = int(raw_input("Enter a decimal number: "))
temp = n
binary = ""
# Special case for 0
if temp == 0:
binary = "0"
else:
# Build binary from right to left
while temp > 0:
r = temp % 2
binary = str(r) + binary
temp = temp / 2
print "Decimal:", n
print "Binary:", binary
Sample Output:
Enter a decimal number: 25
Decimal: 25
Binary: 11001
Question 15
15. Write a program to convert binary to decimal.
Answer 15
Python Program:
# Binary to Decimal conversion
# Read binary string
b = raw_input("Enter a binary number: ")
# Convert using positional weights (powers of 2)
dec = 0
i = 0
pos = len(b) - 1
while pos >= 0:
digit = int(b[pos])
dec = dec + digit * (2 ** i)
i += 1
pos -= 1
print "Binary:", b
print "Decimal:", dec
Sample Output:
Enter a binary number: 11001
Binary: 11001
Decimal: 25
Question 16
16. Write a program to input two complex numbers and find their sum.
Answer 16
Python Program:
# Sum of two complex numbers: (a+bi) + (c+di)
# Input real and imaginary parts
a = int(raw_input("Enter first complex number real part: "))
b = int(raw_input("Enter first complex number imaginary part: "))
c = int(raw_input("Enter second complex number real part: "))
d = int(raw_input("Enter second complex number imaginary part: "))
# Add real parts and imaginary parts separately
real_sum = a + c
imag_sum = b + d
print "First complex:", a, "+", b, "i"
print "Second complex:", c, "+", d, "i"
print "Sum:", real_sum, "+", imag_sum, "i"
Sample Output:
Enter first complex number real part: 2
Enter first complex number imaginary part: 3
Enter second complex number real part: 4
Enter second complex number imaginary part: 5
First complex: 2 + 3 i
Second complex: 4 + 5 i
Sum: 6 + 8 i
Question 17
17. Write a program to input two complex numbers and implement multiplication of the given complex numbers.
Answer 17
Python Program:
# (a+bi)(c+di) = (ac - bd) + (ad + bc)i
# Input real and imaginary parts
a = int(raw_input("Enter first complex number real part: "))
b = int(raw_input("Enter first complex number imaginary part: "))
c = int(raw_input("Enter second complex number real part: "))
d = int(raw_input("Enter second complex number imaginary part: "))
# Apply complex multiplication formula
real_part = (a * c) - (b * d)
imag_part = (a * d) + (b * c)
print "First complex:", a, "+", b, "i"
print "Second complex:", c, "+", d, "i"
print "Product:", real_part, "+", imag_part, "i"
Sample Output:
Enter first complex number real part: 2
Enter first complex number imaginary part: 3
Enter second complex number real part: 4
Enter second complex number imaginary part: 5
First complex: 2 + 3 i
Second complex: 4 + 5 i
Product: -7 + 22 i
Question 18
18. Write a program to find the sum of two distances with feet and inches.
Answer 18
Python Program:
# Sum of two distances (feet, inches)
# Input both distances
f1 = int(raw_input("Enter first distance feet: "))
i1 = int(raw_input("Enter first distance inches: "))
f2 = int(raw_input("Enter second distance feet: "))
i2 = int(raw_input("Enter second distance inches: "))
# Add feet and inches separately
feet = f1 + f2
inch = i1 + i2
# Convert extra inches to feet
extra_feet = inch / 12
inch = inch % 12
feet = feet + extra_feet
print "Sum distance:", feet, "feet", inch, "inches"
Sample Output:
Enter first distance feet: 4
Enter first distance inches: 9
Enter second distance feet: 4
Enter second distance inches: 9
Sum distance: 9 feet 6 inches
Question 19
19. Write a program to find the difference between two times with hours, minutes, and seconds.
Answer 19
Python Program:
# Difference between two times (h, m, s)
# Input first and second time values
h1 = int(raw_input("Enter first time hours: "))
m1 = int(raw_input("Enter first time minutes: "))
s1 = int(raw_input("Enter first time seconds: "))
h2 = int(raw_input("Enter second time hours: "))
m2 = int(raw_input("Enter second time minutes: "))
s2 = int(raw_input("Enter second time seconds: "))
# Convert both times into total seconds
t1 = h1*3600 + m1*60 + s1
t2 = h2*3600 + m2*60 + s2
diff = t2 - t1
# Convert difference back to h:m:s
dh = diff / 3600
diff = diff % 3600
dm = diff / 60
ds = diff % 60
print "Difference:", dh, "hours", dm, "minutes", ds, "seconds"
Sample Output:
Enter first time hours: 10
Enter first time minutes: 15
Enter first time seconds: 30
Enter second time hours: 12
Enter second time minutes: 45
Enter second time seconds: 20
Difference: 2 hours 29 minutes 50 seconds
Question 20
20. Write a program to find the sum of all digits of a given number.
Answer 20
Python Program:
# Sum of digits
# Read number from user
n = int(raw_input("Enter a number: "))
temp = n
s = 0
# Extract digits one by one and add them
while temp > 0:
d = temp % 10
s = s + d
temp = temp / 10
print "Number:", n
print "Sum of digits:", s
Sample Output:
Enter a number: 458
Number: 458
Sum of digits: 17
Question 21
21. Write a program to find the reverse of a given number.
Answer 21
Python Program:
# Reverse of a number
# Read number from user
n = int(raw_input("Enter a number: "))
temp = n
rev = 0
# Build reversed number digit by digit
while temp > 0:
d = temp % 10
rev = rev*10 + d
temp = temp / 10
print "Number:", n
print "Reverse:", rev
Sample Output:
Enter a number: 345
Number: 345
Reverse: 543
Question 22
22. Write a program to input username and password, and check whether they are correct or not.
Answer 22
Python Program:
# Username & password check
# Stored correct credentials
correct_user = "admin"
correct_pass = "admin123"
# Input entered credentials
user = raw_input("Enter username: ")
pwd = raw_input("Enter password: ")
print "Username entered:", user
# Validate both username and password
if user == correct_user and pwd == correct_pass:
print "Result: Login Successful"
else:
print "Result: Invalid Username or Password"
Sample Output:
Enter username: admin
Enter password: admin123
Username entered: admin
Result: Login Successful
Question 23
23. Which string method is used for the following?
(a)
To count the number of characters in the string.
(b)
To change the first character of the string into a capital letter.
(c)
To check whether a given character is a letter or a number.
(d)
To change lower case letters to upper case letters.
(e)
To change one character into another character.
Answer 23
(a)
len(string) – count number of characters.(b)
capitalize() – first character capital.(c)
isalpha(), isdigit(), isalnum().(d)
upper().(e)
replace(old, new).Question 24
24. Write a program to input any string and find the number of words in the string.
Answer 24
Python Program:
# Count words in a string
# Read sentence from user
s = raw_input("Enter a string: ")
# split() separates words using spaces
words = s.split()
count = len(words)
print "String:", s
print "Number of words:", count
Sample Output:
Enter a string: Python is easy to learn
String: Python is easy to learn
Number of words: 5
Question 25
25. Write a program to input any two strings and check whether the given strings are equal or not.
Answer 25
Python Program:
# Compare two strings
# Read both strings
s1 = raw_input("Enter first string: ")
s2 = raw_input("Enter second string: ")
print "String1:", s1
print "String2:", s2
# Compare exact text (case-sensitive)
if s1 == s2:
print "Result: Strings are Equal"
else:
print "Result: Strings are Not Equal"
Sample Output:
Enter first string: hello
Enter second string: Hello
String1: hello
String2: Hello
Result: Strings are Not Equal
Question 26
26. Differentiate between tuple and list.
Answer 26
Feature
List
Tuple
Brackets
[ ]( )Nature
Mutable
Immutable
Methods
append(), insert(), remove()Mostly read-only operations
Example
L=[10,20,30]T=(10,20,30)Question 27
27. Write a program to input n numbers and insert any number at a particular position.
Answer 27
Python Program:
# Insert number at a position
# Read list size and list elements
n = int(raw_input("Enter how many numbers: "))
L = []
i = 0
while i < n:
L.append(int(raw_input("Enter number: ")))
i += 1
x = int(raw_input("Enter number to insert: "))
pos = int(raw_input("Enter position: "))
# Keep position within valid range
if pos < 0:
pos = 0
if pos > len(L):
pos = len(L)
# Insert new value at required position
L.insert(pos, x)
print "Updated List:", L
Sample Output:
Enter how many numbers: 5
Enter number: 10
Enter number: 20
Enter number: 30
Enter number: 40
Enter number: 50
Enter number to insert: 99
Enter position: 2
Updated List: [10, 20, 99, 30, 40, 50]
Question 28
28. Write a program to input n numbers and search any number from the list.
Answer 28
Python Program:
# Linear search in list
# Read list size and list elements
n = int(raw_input("Enter how many numbers: "))
L = []
i = 0
while i < n:
L.append(int(raw_input("Enter number: ")))
i += 1
key = int(raw_input("Enter search key: "))
# Search key in list using linear scan
found = False
index = -1
i = 0
while i < n:
if L[i] == key:
found = True
index = i
break
i += 1
print "List:", L
print "Search key:", key
if found:
print "Result: Found at position", index
else:
print "Result: Not Found"
Sample Output:
Enter how many numbers: 5
Enter number: 11
Enter number: 22
Enter number: 33
Enter number: 44
Enter number: 55
Enter search key: 44
List: [11, 22, 33, 44, 55]
Search key: 44
Result: Found at position 3
Question 29
29. Write a program to input n customer names and phone numbers.
Answer 29
Python Program:
# Store customer data in customers.txt
# Read number of records to store
n = int(raw_input("Enter number of customers: "))
# Open file in write mode (old data will be replaced)
fcust = open("customers.txt", "w")
i = 0
while i < n:
name = raw_input("Enter customer name: ")
phone = raw_input("Enter phone number: ")
# Save one customer per line as name,phone
fcust.write(name + "," + phone + "\\n")
i += 1
fcust.close()
print "Customer data saved to customers.txt"
Sample Output:
Enter number of customers: 3
Enter customer name: Ravi
Enter phone number: 9876543210
Enter customer name: Meena
Enter phone number: 9123456780
Enter customer name: Asha
Enter phone number: 9000000001
Customer data saved to customers.txt
Question 30
30. Write a program to search a customer name and display the customer phone number if the customer name exists in the list.
Answer 30
Python Program:
# Search customer from customers.txt
# Read name to search
search_name = raw_input("Enter customer name to search: ")
# Open customer file and scan line by line
fcust = open("customers.txt", "r")
found = False
phone_found = ""
for line in fcust:
line = line.strip()
if line != "":
parts = line.split(",")
name = parts[0]
phone = parts[1]
# If name matches, keep phone and stop search
if name == search_name:
found = True
phone_found = phone
break
fcust.close()
print "Search Name:", search_name
if found:
print "Phone Number:", phone_found
else:
print "Result: Customer name not found"
Sample Output:
Enter customer name to search: Meena
Search Name: Meena
Phone Number: 9123456780
Question 31
31. Explain in detail about cmp() function.
Answer 31
cmp(a, b) compares two values/objects.•
Returns
0 if both are equal.•
Returns
1 if a > b.•
Returns
-1 if a < b.•
cmp(T, T1) = 0 (same)•
cmp(T2, T1) = 1•
cmp(T1, T2) = -1Question 32
32. Write a program to input n numbers and reverse the set of numbers without using functions.
Answer 32
Python Program:
# Reverse list without using reverse()/slicing
# Read list size and list elements
n = int(raw_input("Enter how many numbers: "))
L = []
i = 0
while i < n:
L.append(int(raw_input("Enter number: ")))
i += 1
# Swap values from both ends towards center
i = 0
j = n - 1
while i < j:
temp = L[i]
L[i] = L[j]
L[j] = temp
i += 1
j -= 1
print "Reversed List:", L
Sample Output:
Enter how many numbers: 6
Enter number: 10
Enter number: 20
Enter number: 30
Enter number: 40
Enter number: 50
Enter number: 60
Reversed List: [60, 50, 40, 30, 20, 10]