Week-2, Practice
This document has 13 questions.
Question-1
Statement
Which of the following are valid names for variables in Python? (MSQ)
Options
- (a)
a_ - (b)
_a - (c)
1a - (d)
a variable - (e)
a_variable
Answer
Hint
Rules for variable names in Python:
- A variable name can contain only alpha-numeric characters and underscores (A-Z, a-z, 0-9, and _).
- A variable name must start with a letter or the underscore character.
Question-2
Statement
Execute the following code-block. Assume that word1 and word2 are strings that have already been defined.
# word1, word2 are two strings
print(word1 + word2)
word = word1
word1 = word2
word2 = word
print(word2 + word1)
Select the statement that accurately describes the two lines in the output.
Options
- (a) The two lines are always the same.
- (b) The two lines are always different.
- (c) The two lines are the same if and only if
word1andword2are equal. - (d) None of the above
Answer
Hint
Lines 3-5 swap the values of variables word1 and word2 using a temporary variable word.
Question-3
Statement
Assume that a, b, and c are three distinct integers. The following code runs without any error.
x, y, z = a, b, c
x = y = z
Select all statements that evaluate to True at the end of execution of the code given above. (MSQ)
Options
- (a)
x == y == z - (b)
x == y == z == a - (c)
x == y == z == b - (d)
x == y == z == c
Answer
Hint
After the first line, x = a, y = b, and z = c. Then, after the second line, all variables are assigned the value of c.
Question-4
Statement
x is a variable of type float and is of the form a.bcd, where a, b, c, d are all positive integers less than 10. What is the output of the following snippet of code?
print(int(x))
print(int(-x))
Options
- (a)
aa - (b)
a + 1a + 1 - (c)
a - 1a - 1 - (d)
a - 1-a - (e)
a-a + 1 - (f)
a-a
Answer
Hint
int(x) retains the integer part and removes the fractional part.
Question-5
Statement
Consider the following code blocks:
# Block-1
flag = True
if flag == True:
print('works')
# Block-2
flag = True
if flag:
print('works')
Are the two blocks equivalent?
Options
- (a) Yes
- (b) No
Answer
Hint
Both blocks are equivalent. However, it's recommended to use the second form: if flag rather than if flag == True.
Question-6
Statement
Consider the following code-blocks. E is a Boolean expression. Two blocks of code are said to be equivalent if they produce the same output for a given input.
# Block-1
if E:
print('good')
else:
print('bad')
# Block-2
if E:
print('good')
print('bad')
# Block-3
print('good')
print('bad')
Select all true statements. (MSQ)
Options
- (a) All three blocks are equivalent to each other.
- (b) Exactly two of these three blocks are equivalent to each other.
- (c) Block-1 and Block-2 are equivalent.
- (d) Block-1 and Block-3 are equivalent.
Answer
Hint
Block-2 always prints both messages, while Block-1 only prints one message depending on the value of E.