Loading...
Please wait while we prepare your content
Please wait while we prepare your content
Solutions for Computer Science, Class 12, CBSE
(a)
Both Assertion and Reason are true and Reason is the correct explanation of Assertion.
Explanation
In python, literal values have fixed memory locations and variable names reference them as values. This means that, although we can change the value of an integer variable, the process involves creating a new integer object with the updated value. Literal values, such as 10, have fixed memory locations, and variables act as references to these values. When we assign a new value to an integer variable, we are essentially creating a new object, and the variable now points to this new object. Hence, both Assertion and Reason are true and Reason is the correct explanation of Assertion.
(c)
Assertion is true but Reason is false.
Explanation
A string literal is a sequence of characters surrounded by single or double or triple single quotes or triple double quotes.
(d)
Assertion is false but Reason is true.
Explanation
if is conditional statement and for is loop statement. Python is case sensitive and its selection and looping statements are in lower case.
(a)
Both Assertion and Reason are true and Reason is the correct explanation of Assertion.
Explanation
if is conditional statement and for is loop statement. Python is case sensitive and its selection and looping statements are in lower case.
(e)
Both Assertion and Reason are false.
Explanation
In python, the break statement can be used with iteration statements only. Using break with conditional statements will result in syntax error — SyntaxError: 'break' outside loop
(e)
Both Assertion and Reason are false.
Explanation
In python, the break statement can be used with iteration statements only. Using break with conditional statements will result in syntax error — SyntaxError: 'break' outside loop
0
Reason — According to operator precedence, floor division (//) and remainder (%) both have equal precedence hence the expression will be evaluated from left to right.
A % B // A
= 16 % 15 // 16
= 1 // 16
= 0
print("hello\\example\\test.txt")
Reason — Escape sequence (\\) is used for Backslash (\).
print('Eina\nMina\nDika')
Reason —
The smallest individual unit in a program is known as a Token. Python has following tokens:
Keywords are reserved words carrying special meaning and purpose to the language compiler/interpreter. For example, if, elif, etc. are keywords. Identifiers are user defined names for different parts of the program like variables, objects, classes, functions, etc. Identifiers are not reserved. They can have letters, digits and underscore. They must begin with either a letter or underscore. For example, _chk, chess, trail, etc.
Literals are data items that have a fixed value. The different types of literals allowed in Python are:
True.
Reason — In Python, variable declaration is implicit. This means that we don't need to explicitly declare the data type of a variable before using it. The type of a variable is determined dynamically at runtime based on the assigned value. For example:
x = 5 # x is implicitly declared as an integer
name = "Ravi" # name is implicitly declared as a string
**
Reason — Let's go through each option and see if its valid arithmetic operator or not:
Floating constants are represented in Python in two forms — Fractional Form and Exponent form. Examples:
A string-literal is represented as a sequence of characters surrounded by quotes (single, double or triple quotes). String-literals in Python are implemented using Unicode.
Operators are tokens that trigger some computation/action when applied to variables and other objects in an expression. Unary plus (+), Unary minus (-), Bitwise complement (~), Logical negation (not) are a few examples of unary operators. Examples of binary operators are Addition (+), Subtraction (-), Multiplication (*), Division (/).
An expression is any legal combination of symbols that represents a value. For example, 2.9, a + 5, (3 + 5) / 4.
A statement is a programming instruction that does something i.e. some action takes place. For example:
print("Hello")
a = 15
b = a - 10
Variables are named labels whose values can be used and processed during program run. Variables are important for a program because they enable a program to process different sets of data.
True
Reason — The 'not' operator has the highest precedence, followed by 'and', which has precedence over 'or', and the evaluation proceeds from left to right.
not True and False or True
= False and False or True
= False or True
= True
A block in Python, represents a group of statements executed as a single unit. Python uses indentation to create blocks of code. Statements at same indentation level are part of same block/suite and constitute the body of the block.
Data types are used to identify the type of data a memory location can hold and the associated operations of handling it. The data that we deal with in our programs can be of many types like character, integer, real number, string, boolean, etc. hence programming languages including Python provide ways and facilities to handle all these different types of data through data types. The data types define the capabilities to handle a specific type of data such as memory space it allocates to hold a certain type of data and the range of values supported for a given data type, etc.
Mutable types are those whose values can be changed in place whereas Immutable types are those that can never change their value in place.
Mutable types in Python are:
Immutable types in Python are:
Implicit Type Conversion | Explicit Type Conversion |
---|---|
An implicit type conversion is automatically performed by the compiler when differing data types are intermixed in an expression. | An explicit type conversion is user-defined conversion that forces an expression to be of specific type. |
An implicit type conversion is performed without programmer's intervention. | An explicit type conversion is specified explicitly by the programmer. |
Example: a, b = 5, 25.5 c = a + b | Example: a, b = 5, 25.5 c = int(a + b) |
Three reasons to use immutable data types are:
An entry-controlled loop checks the condition at the time of entry. Only if the condition is true, the program control enters the body of the loop. In Python, for and while loops are entry-controlled loops.
The pass statement of Python is a do nothing statement i.e. empty statement or null operation statement. It is useful in scenarios where syntax of the language requires the presence of a statement but the logic of the program does not. For example,
for i in range(10):
if i == 2:
pass
else:
print("i =", i)
The corrected code is shown below:
To = 30 # Correction 1
for K in range(0,To): # Correction 2
if K % 4 == 0: # Correction 3
print(K * 4)
else: # Correction 4
print(K+3) # Correction 5
Explanation
Correction 1 — Variable should be on left side and literals should be on right side.
Correction 2 — Semi-colon was missing in the for loop syntax.
Correction 3 — if statement should be in lower case.
Correction 4 — else statement should be in lower case.
Correction 5 — Full stop should not be there at the end of print function.
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")
(ii)
L = ['Hiya', 'Zoya', 'Preet']
print(L[1])
(iii)
M = []
for i in range (3) :
M.append(i)
print(M)
(iv)
L = ['Hiya', 'Zoya', 'Preet']
n = len(L)
if 'Donald' in L[1 : n] :
print(L)
(v)
if n % 2 == 0 :
print("Freezing")
(vi)
L = inputline.split()
while L != ( ) :
print(L)
L = L[1 :]
(vii)
L = ['Hiya', 'Zoya', 'Preet']
print(L[0] + L[1])
(i) bool
(ii) str
(iii) list of int
(iv) int
(v) bool
(vi) list of str
(vii) str
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>
#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 < limit and next_price > max_price:
max_price = next_price
#Read the next price
next_price = float(input("Enter a price or 0 to stop:"))
if max_price > 0:
print("Largest Price =", max_price)
else :
print("Prices exceed limit of", limit);
This is an endless (infinite) loop that will keep printing 45 continuously.
As the loop control variable x is not updated inside the loop neither there is any break statement inside the loop so it becomes an infinite loop.
%
*
* *
* * *
%%
*
* *
* * *
%%%
*
* *
* * *
In this code, the for loop is nested inside the while loop. Outer while loop runs 3 times and prints % as per the elements in x in each iteration. For each iteration of while loop, the inner for loop executes 3 times printing * as per the elements in x.
apple
PEAR
PEACH
grapefruit
x.split(', ') breaks up string x into a list of strings so y becomes ['apple', 'pear', 'peach', 'grapefruit']. The for loop iterates over this list. apple and grapefruit are less than m (since a and g comes before m) so they are converted to lowercase and printed whereas pear and peach are converted to uppercase and printed.
The loops execute 0 times and the code produces no output. range(-1, 7, -2) returns an empty sequence as there are no numbers that start at -1 and go till 6 decrementing by -2. Due to empty sequence, the loops don't execute.
Loop executes for 5 times.
*
*
*
*
*
range(1,3,1) returns [1, 2]. For first iteration of outer loop j is in range [0, 1] so inner loop executes twice. For second iteration of outer loop j is in range [0, 1, 2] so inner loop executes 3 times. This makes the total number of loop executions as 2 + 3 = 5.
Jay
Finished!
Riya
Finished!
Tanu
Got it!
The for loop iterates over each name in the list and prints it. If the name does not begin with the letter T, Finished! is printed after the name. If the name begins with T, break statement is executed that terminates the loop. Outside the loop, Got it! gets printed.
The loop is not infinite. To know this without running it we can analyze how n is changed inside the loop in the following way:
n = 2 * n - m
Substituting value of m from m = n - 1,
n = 2 * n - (n - 1)
⇒ n = 2 * n - n + 1
⇒ n = 2n - n + 1
⇒ n = n + 1
Therefore, inside the loop n is incremented by 1 in each iteration. Loop condition is n < 10 and initial value of n is 5. So after 5 iterations, n will become 10 and the loop will terminate.
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.
x = int(input("Enter x: "))
if x < 0:
print("negative")
elif x > 0:
print("positive")
else:
print("zero")
Enter x: -5
negative
Enter x: 0
zero
Enter x: 5
positive
Write a Python program that calculates and prints the number of seconds in a year.
days = 365
hours = 24
mins = 60
secs = 60
secsInYear = days * hours * mins * secs
print("Number of seconds in a year =", secsInYear)
Number of seconds in a year = 31536000
Write a Python program that accepts two integers from the user and prints a message saying if first number is divisible by second number or if it is not.
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
if a % b == 0:
print(a, "is divisible by", b)
else:
print(a, "is not divisible by", b)
Enter first number: 15
Enter second number: 5
15 is divisible by 5
Enter first number: 13
Enter second number: 7
13 is not divisible by 7
Write a program that asks the user 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.
dayNames = ["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY"]
dayNum = int(input("Enter day number: "))
firstDay = input("First day of year: ")
if dayNum < 2 or dayNum > 365:
print("Invalid Input")
else:
startDayIdx = dayNames.index(str.upper(firstDay))
currDayIdx = dayNum % 7 + startDayIdx - 1
if currDayIdx >= 7:
currDayIdx = currDayIdx - 7
print("Day on day number", dayNum, ":", dayNames[currDayIdx])
Enter day number: 243
First day of year: FRIDAY
Day on day number 243 : TUESDAY
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.
def feetToInches(lenFeet):
lenInch = lenFeet * 12
return lenInch
def getInput():
len = int(input("Enter length in feet: "))
return len
def displayLength(l):
print("Length in inches =", l)
ipLen = getInput()
inchLen = feetToInches(ipLen)
displayLength(inchLen)
Enter length in feet: 15
Length in inches = 180
Write a program that reads an integer N from the keyboard computes and displays the sum of the numbers from N to (2 * N) if N is nonnegative. If N is a negative number, then it's the sum of the numbers from (2 * N) to N. The starting and ending points are included in the sum.
n = int(input("Enter N: "))
sum = 0
if n < 0:
for i in range(2 * n, n + 1):
sum += i
else:
for i in range(n, 2 * n + 1):
sum += i
print("Sum =", sum)
Enter N: 5
Sum = 45
Enter N: -5
Sum = -45
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
months = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"]
dateStr = input("Enter date in MMDDYYYY format: ")
monthIndex = int(dateStr[:2]) - 1
month = months[monthIndex]
day = dateStr[2:4]
year = dateStr[4:]
newDateStr = month + ' ' + day + ', ' + year
print(newDateStr)
Enter date in MMDDYYYY format: 12252019
December 25, 2019
Write a program that prints a table on two columns — table that helps converting miles into kilometers.
print('Miles | Kilometres')
print(1, "\t", 1.60934)
for i in range(10, 101, 10):
print(i, "\t", i * 1.60934)
Miles | Kilometres
1 1.60934
10 16.0934
20 32.1868
30 48.2802
40 64.3736
50 80.467
60 96.5604
70 112.6538
80 128.7472
90 144.8406
100 160.934
Write another program printing a table with two columns that helps convert pounds in kilograms.
print('Pounds | Kilograms')
print(1, "\t", 0.4535)
for i in range(10, 101, 10):
print(i, "\t", i * 0.4535)
Pounds | Kilograms
1 0.4535
10 4.535
20 9.07
30 13.605
40 18.14
50 22.675
60 27.21
70 31.745
80 36.28
90 40.815
100 45.35
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 below :
Please enter the first time : 0900
Please enter the second time : 1730
8 hours 30 minutes
ft = input("Please enter the first time : ")
st = input("Please enter the second time : ")
# Converts both times to minutes
fMins = int(ft[:2]) * 60 + int(ft[2:])
sMins = int(st[:2]) * 60 + int(st[2:])
# Subtract the minutes, this will give
# the time duration between the two times
diff = sMins - fMins;
# Convert the difference to hours & mins
hrs = diff // 60
mins = diff % 60
print(hrs, "hours", mins, "minutes")
Please enter the first time : 0900
Please enter the second time : 1730
8 hours 30 minutes
Please enter the first time : 0915
Please enter the second time : 1005
0 hours 50 minutes