What are the built-in core data types of Python ?
Answer
The built-in core data types in Python include:
- Numbers
- String
- List
- Tuple
- Dictionary
What do you mean by Numeric types ? How many numeric data types does Python provide ?
Answer
Numeric data types are used to store numeric values in Python.
The Python provides three numeric data types:
- Integers
- Floating-point Numbers
- Complex Numbers
What will be the data types of following two variables ?
A = 2147483647; B = A + 1
(Hint: Carefully look the values they are storing. You can refer to range of Python number table.)
Answer
The data types of both variables A and B are integer.
What are Boolean numbers ? Why are they considered as a type of integers in Python ?
Answer
Boolean numbers represent the truth values False and True.
The Boolean type is a subtype of plain integers, and Boolean values False and True behave like the values 0 and 1, respectively. Hence, they are considered a type of integers in Python.
What are floating point numbers ? When are they preferred over integers ?
Answer
A number having fractional part is a floating-point number.
FLoating-point numbers have two advantages over integers:
They can represent values between the integers.
They can represent a much greater range of values.
What are complex numbers ? How would Python represent a complex number with real part as 3 and imaginary part as -2.5 ?
Answer
A complex number is made up of both real and imaginary components.
For a complex number with a real part of 3 and an imaginary part of -2.5, it can be represented in Python as: z = 3 - 2.5j.
What will be the output of following code ?
p = 3j
q = p + (1 + 1.5j)
print(p)
print(q)Answer
3j
(1+4.5j)
The code initializes p as the complex number 3j, where j represents the imaginary unit. Then, it adds p to another complex number (1 + 1.5j), storing the result in q. When adding complex numbers, their real and imaginary parts are added separately, so q becomes (1 + 4.5j). The print(p) statement outputs 3j, and print(q) outputs (1+4.5j).
What will be the output of following code ?
r = 2.5 + 3.9j
print(r.real)
print(r.imag)Answer
2.5
3.9
The code initializes r as the complex number 2.5 + 3.9j, where 2.5 is the real part and 3.9j is the imaginary part.
print(r.real)— This accesses the real part of the complex numberr, which is 2.5, and prints it.print(r.imag)— This accesses the imaginary part of the complex numberr, which is 3.9, and prints it.
Why does Python uses symbol j to represent imaginary part of a complex number instead of the conventional i ?
Answer
Python uses the symbol j to represent the imaginary part of a complex number instead of the conventional i because the programming language was influenced by electrical engineering conventions. In electrical engineering, i is typically used to represent current, so to avoid confusion, j is used for imaginary numbers.
What is String data type in Python ?
Answer
In Python, a string is a sequence of characters surrounded by quotes (single, double).
What are two internal subtypes of String data in Python ?
Answer
The two internal subtypes of string data in Python are str and bytes.
How are str type strings different from Unicode strings ?
Answer
In Python 3, there is no distinction between str and Unicode strings, as all strings store Unicode characters.
What are List and Tuple data types of Python ?
Answer
A List in Python represents a list of comma-separated values of any datatype between square brackets. Lists are mutable, meaning their contents can be changed after creation.
Tuples are represented as group of comma-separated values of any data type within parentheses. Tuples are immutable, meaning their contents cannot be altered after creation.
How is a list type different from tuple data type of Python ?
Answer
Values of type list are mutable, meaning they can be changed; we can add, modify, or delete elements within a list. Lists are defined using square brackets. In contrast, values of type tuple are immutable, meaning they cannot be changed; once a tuple is created, we cannot modify its contents. Tuples are defined using parentheses.
What are Dictionaries in Python ?
Answer
Dictionary is an unordered set of comma-separated key:value pairs, within {}, with the requirement that within a dictionary, no two keys can be the same.
Identify the types of data from the following set of data:
'Roshan', u'Roshan', False, 'False', ['R', 'o', 's', 'h', 'a', 'n',], ('R', 'o', 's', 'h', 'a', 'n'), {'R' : 1, 'o' : 2, 's' : 3, 'h' : 4, 'a' : 5, 'n' : 6}, (2.0 - j), 12, 12.0, 0.0, 0, 3j, 6 + 2.3j, True, "True"
Answer
- 'Roshan' — str (string)
- u'Roshan' — str (string)
- False — bool (boolean)
- 'False' — str (string)
- ['R', 'o', 's', 'h', 'a', 'n'] — list (list)
- ('R', 'o', 's', 'h', 'a', 'n') — tuple (tuple)
- {'R': 1, 'o': 2, 's': 3, 'h': 4, 'a': 5, 'n': 6} — dict (dictionary)
- (2.0 - j) — complex (complex number)
- 12 — int (integer)
- 12.0 — float (floating-point number)
- 0.0 — float (floating-point number)
- 0 — int (integer)
- 3j — complex (complex number)
- 6 + 2.3j — complex (complex number)
- True — bool (boolean)
- "True" — str (string)
What do you understand by mutable and immutable objects ?
Answer
The immutable types are those that can never change their value in place.
The mutable types are those whose values can be changed in place.
What is the function of operators ? What are arithmetic operators ? Give their examples.
Answer
The function of operators is to trigger the operation/action on operands.
Arithmetic Operators are used to perform mathematical (arithmetic) operations.
For example, addition, subtraction, multiplication, division, floor division, remainder, exponentiation.
How is 'unary +' operator different from '+' operator ? How is 'unary -' operator different from '-' operator ?
Answer
The unary '+' operator precedes an operand and is used to indicate the positive value of that operand. The operand must have an arithmetic type, and the result is simply the value of the operand, as it does not change it. In contrast, the binary '+' operator, when used between two operands, performs addition by combining their values.
The unary '-' operator precedes an operand and is used to indicate the negation of that operand's value. The operand must have an arithmetic type, and the result is the negative value of the operand. In contrast, the binary '-' operator, when used between two operands, performs subtraction.
What are binary operators ? Give examples of arithmetic binary operators.
Answer
Operators that act upon two operands are referred to as Binary Operators.
For example, addition, subtraction, multiplication, division, floor division, modulus, exponentiation.
What does the modulus operator % do ? What will be the result of 7.2 % 2.1 and 8 % 3 ?
Answer
The % operator finds the modulus of its first operand relative to the second. That is, it produces the remainder of dividing the first operand by the second operand.
The expression 7.2 % 2.1 evaluates to 0.89999999.
The expression 8 % 3 evaluates to 2.
What will be the result of 5.0/3 and 5.0//3 ?
Answer
The expression 5.0/3 evaluates to 1.6666666666666667.
The expression 5.0//3 evaluates to 1.0.
How will you calculate 4.55 in Python ?
Answer
To calculate 4.55 in Python, we can use the exponentiation operator **.
print(4.5 ** 5)1845.28125
Write an expression that uses a relational operator to return True if the variable total is greater than or equal to variable final.
Answer
We can use the >= relational operator to compare the variables total and final.
print(total >= final)Given that i = 4, j = 5, k = 4, what will be the result of following expressions ?
(i) i < k
(ii) i < j
(iii) i <= k
(iv) i == j
(v) i == k
(vi) j > k
(vii) j >= i
(viii) j != i
(ix) j <= k
Answer
(i) i < k: 4 < 4 evaluates to False.
(ii) i < j: 4 < 5 evaluates to True.
(iii) i <= k: 4 <= 4 evaluates to True.
(iv) i == j: 4 == 5 evaluates to False.
(v) i == k: 4 == 4 evaluates to True.
(vi) j > k: 5 > 4 evaluates to True.
(vii) j >= i: 5 >= 4 evaluates to True.
(viii) j != i: 5 != 4 evaluates to True.
(ix) j <= k: 5 <= 4 evaluates to False.
What will be the order of evaluation for following expressions ?
(i) i + 5 >= j - 6
(ii) s * 10 < p ** 2
(iii) i < j + k > 1 - n
Answer
(i) i + 5 >= j - 6:
- First, evaluate the addition:
i + 5 - Then, evaluate the subtraction:
j - 6 - Finally, compare the results using the relational operator
>=.
(ii) s * 10 < p ** 2:
- First, evaluate the exponentiation:
p ** 2 - Then, evaluate the multiplication:
s * 10 - Finally, compare the results using the relational operator <.
(iii) i < j + k > 1 - n:
- First, evaluate the addition:
j + k - Then, evaluate the subtraction:
1 - n - Finally, evaluate the comparisons from left to right: first i < (result of j + k) and then (result of j + k) > (result of 1 - n).
How are following two expressions different ? (i) ans = 8 (ii) ans == 8
Answer
(i) ans = 8:
This expression is an assignment statement. It assigns the value 8 to the variable ans. After this statement executes, ans will hold the value 8.
(ii) ans == 8:
This expression is a comparison or equality check. It evaluates whether the current value of ans is equal to 8. This expression will return True if ans is 8, and False otherwise.
What is the function of logical operators ? Write an expression involving a logical operator to test if marks are 55 and grade is 'B'.
Answer
Logical operators are used to combine conditional statements and return a boolean value (True or False).
To test if marks are 55 and grade is 'B', we can use the and operator as follows:
print((marks == 55) and (grade == 'B'))What is the order of evaluation in the following expressions:
(i) a > b or b <= d ?
(ii) x == y and y >= m ?
(iii) a > b < c > d
Answer
(i) a > b or b <= d:
- First, evaluate the relational operators:
a > bb <= d - Finally, evaluate the logical operator
orto combine the results of the two comparisons.
(ii) x == y and y >= m:
- First, evaluate the relational operators:
x == yy >= m - Finally, evaluate the logical operator
andto combine the results of the two comparisons.
(iii) a > b < c > d:
- Python evaluates them from left to right:
- First, evaluate a > b.
- Then, evaluate b < c.
- Finally, evaluate c > d.
What is the result of following expression : a >= b and (a + b) > a if
(i) a = 3, b = 0 (ii) a = 7, b = 7 ?
Answer
(i) 3 >= 0 and (3 + 0) > 3
- 3 >= 0 is True.
- (3 + 0) > 3 → 3 > 3 is False.
- True and False is False.
Hence, 3 >= 0 and (3 + 0) > 3 evaluates to False.
(ii) 7 >= 7 and (7 + 7) > 7
- 7 >= 7 is True.
- (7 + 7) > 7 → 14 > 7 is True.
- True and True is True.
Hence, 7 >= 7 and (7 + 7) > 7 evaluates to False.
What is the result of following expressions (a to e) if
(i) check = 3, mate = 0.0
(ii) check = 0, mate = -5
(iii) check = '', mate = 'e'
(iv) check = 'meera', mate = ''
(a) check or mate
(b) mate or check
(c) check and not mate
(d) check and mate
(e) mate and check
Evaluate each of the above expressions for all four sets of values.
Answer
(a) check or mate
(i) 3 or 0.0 → 3
(ii) 0 or -5 → -5
(iii) '' or 'e' → 'e'
(iv) 'meera' or '' → 'meera'
(b) mate or check
(i) 0.0 or 3 → 3
(ii) -5 or 0 → -5
(iii) 'e' or '' → 'e'
(iv) '' or 'meera' → 'meera'
(c) check and not mate
(i) 3 and not 0.0 → 0.0
(ii) 0 and not -5 → 0
(iii) '' and not 'e' → ''
(iv) 'meera' and not '' → ''
(d) check and mate
(i) 3 and 0.0 → 0.0
(ii) 0 and -5 → 0
(iii) '' and 'e' → ''
(iv) 'meera' and '' → ''
(e) mate and check
(i) 0.0 and 3 → 0.0
(ii) -5 and 0 → 0
(iii) 'e' and '' → ''
(iv) '' and 'meera' → ''
Identify the order of evaluation in the following expression :
4 * 5 + 7 * 2 - 8 % 3 + 4 and 5.7 // 2 - 1 + 4 or not 2 == 4 and not 2 ** 4 > 6 * 2
Answer
4 * 5 + 7 * 2 - 8 % 3 + 4 and 5.7 // 2 - 1 + 4 or not 2 == 4 and not 2 ** 4 > 6 * 2
= 20 + 14 - 2 + 4 and 2.0 - 1 + 4 or not 2 == 4 and not 16 > 12
= 34 - 2 + 4 and 1.0 + 4 or not 2 == 4 and not 16 > 12
= 32 + 4 and 5.0 or not 2 == 4 and not 16 > 12
= 36 and 5.0 or not 2 == 4 and not 16 > 12
= 36 and 5.0 or not False and not True
= 36 and 5.0 or True and False
= 5.0 or False
= 5.0
a = 15.5, b = 15.5 then why is a is b is False while a == b is True ?
Answer
In Python, the expression a is b checks for identity, meaning it evaluates to True only if both a and b refer to the same object in memory. In this case, even though both a and b have the same value of 15.5, they are two distinct float objects in memory, which is why a is b returns False.
On the other hand, the expression a == b checks for equality, which evaluates to True if the values of a and b are the same, regardless of whether they are the same object. Since both a and b have the same value of 15.5, a == b returns True.
What is an expression ? How many different types of expressions can you have in Python ?
Answer
An expression in Python is any valid combination of operators and atoms. An expression is composed of one or more operations, with operators, literals amd variables as the constituents of expressions.
There are four types of expressions in Python:
- Arithmetic expressions
- Relational expressions
- Logical expressions
- String expressions
What is atom in context of expression ?
Answer
An atom is something that has a value. Identifiers, literals, strings, lists, tuples, sets, dictionaries etc are all atoms.
From the following expression, identify atoms and operators.
str(a + b > c + d > e + f or not g - h)
Answer
Atoms: str, a, b, c, d, e, f, g, h
Operators: +, >, or, not, -
What is type conversion (coercion) ? How does Python perform it ?
Answer
An implicit type conversion (coercion) is a conversion performed by the compiler without programmers intervention. An implicit conversion is applied generally whenever differing data types are intermixed in an expression, so as not to lose information.
Python automatically converts a smaller data type to a larger data type during operations without user intervention.
For example,
a = 5 # int
b = 2.0 # float
result = a + b # Python converts 'a' to float
print(result) 7.0
Are the following expressions equal ? Why/why not ?
x or y and not z
(x or y) and (not z) )
(x or (y and (not z)))
Answer
The following expressions are not equal because :
x or y and not z
According to Python’s operator precedence, and has a higher precedence than or, and not has the highest precedence. This expression will be evaluated as: x or (y and (not z))
(x or y) and (not z)
Here, the expression inside parentheses are evaluated first (x or y), followed by (not z), and then the and operation is performed between them.
x or (y and (not z))
In this case, the expression inside the parentheses (y and (not z)) is evaluated first, and then the result is used with the or operation involving x.
State when would only first argument be evaluated and when both first and second arguments are evaluated in following expressions if a = 5, b = 10, c = 5, d = 0.
(i) b > c and c > d
(ii) a <= b or c <= d
(iii) (b + c) <= a and not (c < a)
(iv) b < d and d < a
Answer
(i) b > c and c > d
- First Argument:
b > c(i.e., 10 > 5) evaluates to True. - Second Argument:
c > d(i.e., 5 > 0) evaluates to True. - Both arguments evaluated because the first argument is True.
(ii) a <= b or c <= d
- First Argument:
a <= b(i.e., 5 <= 10) evaluates to True. - Second Argument:
c <= d(i.e., 5 <= 0) evaluates to False. - Only first argument evaluated because the first argument is True, and
ordoes not evaluate the second argument if the first is True.
(iii) (b + c) <= a and not (c < a)
- First Argument:
(b + c) <= a(i.e., 10 + 5 <= 5 or 15 <= 5) evaluates to False. - Second Argument:
not (c < a)(i.e., not (5 < 5), which is not False, evaluates to True. - Only first argument evaluated because the first argument is False, and and does not evaluate the second argument if the first is False.
(iv) b < d and d < a
- First Argument:
b < d(i.e., 10 < 0) evaluates to False. - Second Argument:
d < a(i.e., 0 < 5) evaluates to True. - Only first argument evaluated because the first argument is False, and and does not evaluate the second argument if the first is False.
What is Type casting ?
Answer
The explicit conversion of an operand to a specific type is called type casting.
How is implicit type conversion different from explicit type conversion ?
Answer
An implicit type conversion is performed automatically by the compiler or interpreter without the programmer's intervention when mixed data types are involved, ensuring no information is lost. On the other hand, an explicit type conversion is manually done by the programmer, forcing an expression to be of a specific type using type casting functions like int() or float().
Write conversion function you would use for following type of conversions.
(i) Boolean to string
(ii) integer to float
(iii) float to integer
(iv) string to integer
(v) string to float
(vi) string to Boolean
(vii) integer to complex
Answer
(i) Boolean to string — str()
(ii) Integer to float — float()
(iii) Float to integer — int()
(iv) String to integer — int()
(v) String to float — float()
(vi) String to Boolean — bool()
(vii) Integer to complex — complex()
Which of the following are valid Python data types ?
- Numeric
- None
- Mappings
- list
- Sequence
- set
- tuple
- dictionary
Answer
None, list, set, tuple, dictionary
Reason — "None," "list," "set," "tuple," and "dictionary" are valid Python data types.
Which of the following are data types considered as Numbers in Python.
- Integer
- Boolean
- complex
- floating point
- list
- None
Answer
Integer, Boolean, complex, floating point
Reason — "Integer," "Boolean," "complex," and "floating point" are considered numbers in Python because "Integer" represents whole numbers, "Boolean" represents True or False, "complex" represents numbers with real and imaginary parts, and "floating point" handles decimal numbers.
Consider the following sequence of statements:
a = 35
m = a
Following the execution of these statements, Python has created how many objects and how many references ?
- Two integer objects, two references
- One integer object, two references
- One integer object, one reference
- Two integer objects, one reference
Answer
One integer object, two references
Reason — Python creates one integer object, 35, and two references to it: "a" and "m." Both "a" and "m" refer to the same object in memory, so only one object is created, but there are two references pointing to it.
Which Python built-in function returns the unique number assigned to an object?
- identity()
- id()
- refnum()
- ref()
Answer
id()
Reason — The built-in function id() returns the unique identifier assigned to an object in Python.
The ............... operator is used to check if both the operands reference the same object memory.
- in
- is
- id
- ==
Answer
is
Reason — The is operator is used to check if both operands reference the same object in memory.
For two objects x and y, the expression x is y will yield True, if and only if
- id(x) == id(y)
- len(x) == len(y)
- x == y
- all of these
Answer
id(x) == id(y)
Reason — The expression x is y will yield True if and only if id(x) == id(y), meaning both variables reference the exact same object in memory.
Which of the following is not an immutable type in Python ?
- String
- Tuples
- Set
- dictionary
Answer
Set, dictionary
Reason — Set and dictionary are not immutable types in Python because their contents can be changed after creation. In contrast, String and Tuples are immutable types.
What is the value of the expression 100 / 25 ?
- 4
- 4.0
- 2.5
- none of these
Answer
4.0
Reason — In Python, the / operator performs floating-point division, so the result of the expression 100 / 25 is 4.0, a floating-point number.
What is the value of the expression 100 // 25 ?
- 4
- 4.0
- 2.5
- none of these
Answer
4
Reason — In Python, the // operator performs integer division, so the result of the expression 100 // 25 is 4.
In Python, a variable must be declared before it is assigned a value.
- True
- False
- Only in Functions
- Only in modules
Answer
False
Reason — In Python, a variable does not need to be declared before it is assigned a value. Variables can be created dynamically at the point of assignment, making it possible to assign a value to a variable without prior declaration.
In Python, a variable is assigned a value of one type, and then later assigned a value of a different type. This will yield .......... .
- Warning
- Error
- None
- No Error
Answer
No Error
Reason — In Python, a variable can be assigned a value of one type and then later assigned a value of a different type without causing any error. Python is dynamically typed, which means that the type of a variable is determined at runtime.
In Python, a variable once assigned a value of one type, can be assigned a value of a different type later. This concept is known as .......... .
- mutability
- static typing
- dynamic typing
- immutability
Answer
dynamic typing
Reason — In Python, a variable may be assigned a value of one type, and then later assigned a value of a different type. This concept is known as dynamic typing.
Is it safe to directly use the == operator to determine whether objects of type float are equal ?
- Yes
- No
- Yes, if the values are < 100
- Yes, if the values are > 100
Answer
No
Reason — It is not safe to directly use the == operator to compare float values due to precision errors in how floats are represented in memory.
What will the following code produce ?
a, b = 8.6, 2
print ( a//b )- 4.3
- 4.0
- 4
- compilation error
Answer
4.0
Reason — The code assigns the value 8.6 to variable a and 2 to variable b using multiple assignment. It then performs floor division with the // operator, which divides a by b and rounds down to the nearest whole number. Specifically, 8.6 // 2 calculates to 4.3, but due to floor division, it returns 4.0 as a floating-point number.
In the Python statement x = a + 5 - b : a and b are .......... .
- Operands
- Expression
- operators
- Equation
Answer
Operands
Reason — In the Python statement x = a + 5 - b, the variables a and b are considered operands because they are the values that are operated on by the operators + and - to produce a result.
In the Python statement x = a + 5 - b : a + 5 - b is .......... .
- Operands
- Expression
- operators
- Equation
Answer
Expression
Reason — In the Python statement x = a + 5 - b, the part a + 5 - b is called an expression because it combines operands (like a and b) and operators (+ and -) to compute a value that is assigned to x.
What will be the value of y after following code fragment is executed ?
x = 10.0
y = (x < 100.0) and x >= 10- 110
- True
- False
- Error.
Answer
True
Reason — In the code fragment, x is assigned the floating-point value 10.0. The variable y is then assigned the result of the expression (x < 100.0) and (x >= 10). This expression checks two conditions: whether x is less than 100.0 (which is True) and whether x is greater than or equal to 10 (which is also True). Since both conditions are satisfied, the logical and operator evaluates the entire expression to True, so y is set to True.
Which of these are equivalent to True ?
- 0.000001
- 'None'
- 0
- [ ]
- False
- True
- 1
- 33
- None
- 0.0
Answer
0.000001, 'None', True, 1, 33
Reason — The literals 0.000001, 'None', True, 1, and 33 have a True truth value because non-zero numbers (like 0.000001, 1, and 33) are considered True in Python, as well as the string 'None', which is a non-empty string. The values 0, False, [] (empty list), None, and 0.0 evaluate to False in Python.
Which of the following operators has the lowest precedence ?
- not
- %
- and
- +
- **
Answer
and
Reason — The and operator has the lowest precedence among the listed operators. In Python, the precedence from highest to lowest is: ** (exponentiation), % (modulus), + (addition), and not (logical negation), with and having the lowest precedence, meaning it is evaluated last in expressions involving multiple operators.
What is the value of the expression 10 + 3 ** 3 * 2 ?
- 28
- 739
- 829
- 64
Answer
64
Reason — The value of the expression is as follows:
= 10 + 3 ** 3 * 2
= 10 + 27 * 2
= 10 + 54
= 64
To increase the value of x five times using an augmented assignment operator, the correct expression will be
- x += 5
- x *= 5
- x = x ** 5
- none of these
Answer
x *= 5
Reason — To increase the value of x five times using an augmented assignment operator, the correct expression is x *= 5. This expression multiplies the current value of x by 5 and assigns the result back to x.
What will be the result of the expression 10 or 0 ?
- 0
- 1
- 10
- 1.0
Answer
10
Reason — The result of 10 or 0 is 10 because in Python, the or operator returns the first value that is considered true. Since 10 is a non-zero number (true value), it is returned without checking the second value, which is 0 (false). Therefore, the Answer is 10.
The result of the expression 5 or 10 ?
- 5
- 1
- 10
- 0
Answer
5
Reason — The result of 5 or 10 is 5 because the or operator in Python returns the first true value it finds. Since 5 is a non-zero number (true value), the expression returns 5 without evaluating the second value, which is 10. Therefore, the Answer is 5.
The result of the expression 5 and 10?
- 5
- 1
- 10
- 0
Answer
10
Reason — The result of 5 and 10 is 10 because the and operator in Python returns the second value if both operands are true (non-zero). Since 5 is true and 10 is also true, the result is the second value, which is 10. Therefore, the Answer is 10.
The result of the expression 15 and 10?
- 5
- 1
- 10
- 0
Answer
10
Reason — The result of 15 and 10 is 10 because the and operator in Python returns the second value if both operands are true (non-zero). Since 15 is true and 10 is also true, the result is the second value, which is 10. Therefore, the Answer is 10.
The result of the expression 'a' or '' (" is an empty string) ?
- 'a'
- "
- 1
- 0
Answer
'a'
Reason — The result of 'a' or '' is 'a' because the or operator in Python returns the first true value it encounters. Since 'a' is a non-empty string (true), the expression returns 'a' without evaluating the second value, which is an empty string (false). Therefore, the Answer is 'a'.
The result of the expression 'a' and '' (" is an empty string) ?
- 'a'
- "
- 1
- 0
Answer
"
Reason — The result of 'a' and '' (an empty string) is '' because the and operator in Python returns the second value if both operands are true (non-empty). Since 'a' is a non-empty string (true), the expression evaluates to the second operand, which is an empty string. Therefore, the Answer is ''.
The result of the expression 'x' and 'a' ?
- 'a'
- "
- 'x'
- 1
Answer
'a'
Reason — The result of 'x' and 'a' is 'a' because the and operator in Python returns the second value if both operands are true (non-empty). Since both 'x' and 'a' are non-empty strings (true), the expression evaluates to the second operand, which is 'a'. Therefore, the Answer is 'a'.
The result of the expression 'a' and 'x' ?
- 'a'
- ''
- 'x'
- 1
Answer
'x'
Reason — The result of 'a' and 'x' is 'x' because the and operator in Python returns the second value if both operands are true (non-empty). Since both 'a' and 'x' are non-empty strings (true), the expression evaluates to the second operand, which is 'x'. Therefore, the Answer is 'x'.
The result of the expression 'a' and 'None' ?
- 'a'
- ''
- 'None'
- 1
Answer
'None'
Reason — The result of 'a' and None is None because the and operator in Python returns the second operand if the first operand is true (non-empty). Since 'a' is a non-empty string (true), the expression evaluates to the second operand, which is None. Therefore, the Answer is None.
The result of the expression 'None' and 'a' ?
- 'a'
- ''
- 'None'
- 1
Answer
'a'
Reason — The result of 'None' and 'a' is 'a' because the and operator in Python returns the second operand if the first operand is true (non-empty). Since 'None' is a non-empty string (true), the expression evaluates to the second operand, which is 'a'. Therefore, the Answer is 'a'
The result of the expression 'false' and False ?
- false
- False
- 'false'
- 'False'
Answer
False
Reason — The result of 'false' and False is False because the and operator in Python evaluates both operands. The first operand, 'false', is a non-empty string (true), but the second operand is False. In an and operation, if one operand is false, the result is that false operand. Therefore, the Answer is False.
The result of the expression 'false' or False ?
- false
- False
- 'false'
- 'False'
Answer
'false'
Reason — The result of 'false' or False is 'false' because the or operator in Python returns the first true value it encounters. In this case, 'false' is a non-empty string (true), so it is returned without evaluating the second operand, which is False. Therefore, the Answer is 'false'.
Boolean data type is internally treated as integer data type.
Two forms of floating-point numbers are: fractional form and exponent notation.
Python's floating point numbers have precision of 15 digits.
Three mutable types of Python are lists, dictionaries and sets.
The floor division of two integers yields a result of integer type.
The division of two integers yields a result of floating-point type.
The set sequence type cannot store duplicate values.
The tuple datatype is like lists but is not mutable.
The id of an object gives the memory location of the object.
To check if two objects reference the same memory address, is operator is used.
List is an immutable data type.
Answer
False
Reason — In Python, a list is a mutable data type, meaning that its elements can be changed after the list is created. We can add, remove, or modify elements within a list.
Set is a mutable data type.
Answer
True
Reason — In Python, a set is a mutable data type, meaning that its elements can be changed after the set is created. We can add, remove, or modify elements within a set.
A set can contain duplicate values in it.
Answer
False
Reason — In Python, a set is an unordered collection of unique elements, meaning it cannot contain duplicate values.
A Boolean value is internally treated as an integer value.
Answer
True
Reason — In Python, True is represented as 1 and False as 0, meaning a Boolean value is internally treated as an integer.
'' (an empty string) has truth value as False.
Answer
True
Reason — An empty string ('') in Python has a truth value of False.
' ' (a space) has truth value as False.
Answer
False
Reason — In Python, a space (' ') is considered a non-empty string, which has a truth value of True.
Value false is a legal literal value in Python.
Answer
False
Reason — The value False is a legal literal value in Python, representing a Boolean false condition. It is case-sensitive and must be written with an uppercase "F" as False.
Value False is a legal literal value in Python.
Answer
True
Reason — The value False is a legal literal value in Python, representing a Boolean false condition.
Value 'False' is a legal literal value in Python.
Answer
True
Reason — The value 'False' is a legal literal value in Python, representing a string.
Value 'false' is a legal literal value in Python.
Answer
True
Reason — The value 'false' is a legal literal value in Python, representing a string.
None and 'None' are the same.
Answer
False
Reason — None and 'None' are not the same in Python. None is a special literal that represents the absence of a value or a null value, whereas 'None' is a string.
None has the truth value as False.
Answer
True
Reason — In Python, None is considered a false value, meaning it evaluates to False in a Boolean context.
'None' has the truth value as False.
Answer
False
Reason — The string 'None' is considered a true value in Python because it is a non-empty string. In Python, all non-empty strings evaluate to True in a Boolean context.
The result of bool(0) is False.
Answer
True
Reason — The result of bool(0) is False because in Python, the bool() function converts values to their Boolean equivalent. Since 0 is considered a false value, calling bool(0) evaluates to False.
The result of bool('None') is False.
Answer
False
Reason — The result of bool('None') is True because 'None' is a non-empty string. In Python, all non-empty strings evaluate to True in a Boolean context.
Dividing two integers results in an integer.
Answer
False
Reason — Dividing two integers in Python using the / operator results in a float. For example, 5 / 2 yields 2.5, not 2. However, using the // operator will yield an integer result.
Floor division of two integers results in an integer.
Answer
True
Reason — Floor division of two integers using the // operator in Python returns the largest integer less than or equal to the division result.
Two floating point numbers should not be compared for equality using ==.
Answer
True
Reason — It is not safe to directly use the == operator to compare float values due to precision errors in how floats are represented in memory.
In implicit conversion, all operands' data types are converted to the datatype of the largest operand.
Answer
True
Reason — In implicit conversion, Python internally changes the data type of some operands so that all operands have same data type.
Explicit type conversion involves the use of a function to convert datatype of a value.
Answer
True
Reason — Explicit type conversion is performed using the <type>() function of the appropriate data type, formatted as follows: <datatype>(expression), where <datatype> is the data type to which we want to type-cast our expression.
Assertion (A): Mutability means that the values can be changed in place.
Reasoning (R): Immutable types mean that their values cannot be changed in place.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
Answer
Both A and R are true and R is the correct explanation of A.
Explanation
Mutability refers to the property of an object whose value can be changed in place. Mutable types are those whose values can be changed in place, while immutable types are those that can never have their value changed in place.
Assertion (A): For evaluating a mixed type expression, Python carries our implicit type conversion.
Reasoning (R): In implicit type conversion, all operands are converted up to the type of the largest operand.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
Answer
Both A and R are true and R is the correct explanation of A.
Explanation
In expression with mixed types, Python internally changes the data type of some operands so that all operands have same data type. This type of conversion is automatic, i.e., implicit and hence known as implicit type conversion.
Assertion (A): Type conversion can be implicit or explicit.
Reasoning (R): Only Python interpreter can force the type conversion and not the programmer.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
Answer
A is true but R is false.
Explanation
Type conversion can be implicit or explicit. Implicit type conversion occurs automatically by the Python interpreter, while explicit type conversion is a user-defined process that forces an expression to be of a specific type.
Assertion (A): Syntax errors are the violations of grammatical rules of a programming language.
Reasoning (R): The syntax errors can be easily caught by the Python interpreter.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
Answer
Both A and R are true but R is not the correct explanation of A.
Explanation
Syntax errors occur when rules of a programming language are misused i.e., when a grammatical rule of Python is violated. The Python interpreter can easily catch syntax errors during the parsing stage, typically providing error messages to help the programmer identify the issue.
Assertion (A): The logical errors are the result of mistaken analysis of a problem.
Reasoning (R): Logical errors are missed by the interpreter.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
Answer
Both A and R are true but R is not the correct explanation of A.
Explanation
Logical errors result from a mistaken analysis of a problem, which can lead to incorrect results. For instance, incorrectly implemented algorithms, using a variable before its initialization, failing to mark the end of a loop, or passing wrong parameters can all contribute to logical errors. These errors are often the hardest to prevent and locate, as they do not occur during compile-time or run-time.
Assertion (A): The runtime errors occur during the execution of a program.
Reasoning (R): The runtime errors mainly occur due to unavailability of a resource required for program execution.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
Answer
Both A and R are true and R is the correct explanation of A.
Explanation
Errors that occur during the execution of a program are known as runtime errors. These errors can arise due to the unavailability of resources needed for program execution, such as missing files, insufficient memory, or network connectivity issues.
Assertion (A): Exceptions may occur even if the program is free from all types of errors.
Reasoning (R): Irregular unexpected situations occurring during runtime are called exceptions.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
Answer
Both A and R are true and R is the correct explanation of A.
Explanation
Exceptions may occur even if the program is free from all types of errors. An exception refers to any irregular situation occurring during execution/run-time, which we have no control on.
What are data types in Python? How are they important?
Answer
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.
How many integer types are supported by Python? Name them.
Answer
Two integer types are supported by Python. They are:
- Integers (signed)
- Booleans
How are these numbers different from one another (with respect to Python)? 33, 33.0, 33j, 33 + j
Answer
The number 33 is an integer whereas 33.0 is a floating-point number. 33j represent the imaginary part of a complex number. 33 + j is a complex number.
The complex numbers have two parts : real and imaginary. In which data type are real and imaginary parts represented ?
Answer
In Python, the real and imaginary parts of a complex number are represented as floating-point numbers.
How many string types does Python support? How are they different from one another?
Answer
Python supports two types of strings — Single-line strings and Multi-line strings. Single line strings are enclosed in single or double quotes and terminate in one line. Multi-line strings store multiple lines of text and are enclosed in triple quotes.
What will following code print?
str1 = '''Hell
o'''
str2 = '''Hell\
o'''
print(len(str1) > len(str2))Answer
This code will print:
True
len(str1) is 6 due to the EOL character. len(str2) is 5 as backslash (\) character is not counted in the length of string. As len(str1) is greater than len(str2) so the output is True.
What are Immutable and Mutable types in Python? List immutable and mutable types of Python.
Answer
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:
- Lists
- Dictionaries
- Sets
Immutable types in Python are:
- Integers
- Floating-Point numbers
- Booleans
- Strings
- Tuples
What are three internal key-attributes of a value-variable in Python ? Explain with example.
Answer
The three internal key-attributes of a value-variable in Python are:
- Type
- Value
- Id
For example, consider this:
a = 4
The type of a is int which can be found with the built-in function type() like this:
type(a).
Value can be found using the built-in function print() like this:
print(a)
It will give the output as 4 which is value contained in variable a.
Id is the memory location of the object which can be determined using built-in function id() like this:
id(a)
Is it true that if two objects return True for is operator, they will also return True for == operator?
Answer
Yes, if is operator returns true, it implicitly means that the equality operator will also return True. is operator returning true implies that both the variables point to the same object and hence == operator must return True.
Are these values equal? Why/why not?
- 20 and 20.0
- 20 and int(20)
- str(20) and str(20.0)
- 'a' and "a"
Answer
- The type of 20 is int whereas the type of 20.0 is float so they are two different objects. Both have the same value of 20. So, as values are same equality (==) operator return True but as objects are different is operator returns False.
- The value and type of both 20 and int(20) are the same and both point to the same object so both equality (==) and is operator returns True.
- For str(20) and str(20.0), both equality (==) and is operator returns False as their values are different and they point to two different objects.
- For 'a' and "a", both equality (==) and is operator returns True as their values are same and they point to the same object.
What is an atom in Python? What is an expression?
Answer
In Python, an atom is something that has a value. Identifiers, literals, strings, lists, tuples, sets, dictionaries, etc. are all atoms. An expression in Python, is any valid combination of operators and atoms. It is composed of one or more operations.
What is the difference between implicit type conversion and explicit type conversion?
Answer
| 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) |
Two objects (say a and b) when compared using == ,return True. But Python gives False when compared using is operator. Why? (i.e., a == b is True but why is a is b False?)
Answer
As equality (==) operator returns True, it means that a and b have the same value but as is operator returns False, it means that variables a and b point to different objects in memory. For example, consider the below Python statements:
>>> a = 'abc'
>>> b = input("Enter a string: ")
Enter a string: abc
>>> a == b
True
>>> a is b
False
Here, both a and b have the same value 'abc' but they point to different objects.
Given str1 = "Hello", what will be the values of:
(a) str1[0]
(b) str1[1]
(c) str1[-5]
(d) str1[-4]
(e) str1[5]
Answer
(a) H
(b) e
(c) H
(d) e
(e) IndexError: string index out of range
If you give the following for str1 = "Hello", why does Python report error?
str1[2] = 'p'
Answer
Python reports error because strings are immutable and hence item assignment is not supported.
What will the result given by the following?
(a) type (6 + 3)
(b) type (6 -3)
(c) type (6 *3)
(d) type (6 / 3)
(e) type (6 // 3)
(f) type (6 % 3)
Answer
(a) type (6 + 3)
⇒ int + int
⇒ int
So the result is int.
(b) type (6 -3)
⇒ int - int
⇒ int
So the result is int.
(c) type (6 * 3)
⇒ int * int
⇒ int
So the result is int.
(d) type (6 / 3)
⇒ int / int
⇒ float
So the result is float.
(e) type (6 // 3)
⇒ int // int
⇒ int
So the result is int.
(f) type (6 % 3)
⇒ int % int
⇒ int
So the result is int.
What are augmented assignment operators? How are they useful?
Answer
Augmented assignment operators combine the impact of an arithmetic operator with an assignment operator. For example, to add the value of b to the value of a and assign the result back to a then instead of writing:
a = a + b
we can write
a += b.
Augmented assignment operators are useful as they provide a shorthand way by combining the arithmetic and assignment operators.
Differentiate between (555/222)**2 and (555.0/222)**2.
Answer
In the first expression, 555 is of int type whereas in the second expression 555.0 is of float type.
Given three Boolean variables a, b, c as : a = False, b = True, c = False. Evaluate the following Boolean expressions:
(a) b and c
(b) b or c
(c) not a and b
(d) (a and b) or not c
(e) not b and not (a or c)
(f) not ((not b or not a) and c) or a
Answer
(a) b and c
⇒ False and True
⇒ False
(b) b or c
⇒ True or False
⇒ True
(c) not a and b
⇒ not False and True
⇒ True and True
⇒ True
(d) (a and b) or not c
⇒ (False and True) or not False
⇒ False or not False
⇒ False or True
⇒ True
(e) not b and not (a or c)
⇒ not True and not (False or False)
⇒ not True and not False
⇒ False and True
⇒ False
(f) not ((not b or not a) and c) or a
⇒ not ((not True or not False) and False) or False
⇒ not ((False or True) and False) or False
⇒ not (True and False) or False
⇒ not False or False
⇒ True or False
⇒ True
What would following code fragments result in? Given x = 3.
(a) 1 < x
(b) x >= 4
(c) x == 3
(d) x == 3.0
(e) "Hello" == "Hello"
(f) "Hello" > "hello"
(g) 4/2 == 2.0
(h) 4/2 == 2
(i) x < 7 and 4 > 5.
Answer
(a) True
(b) False
(c) True
(d) True
(e) True
(f) False
(g) True
(h) True
(i) False
Write following expressions in Python:
(a)
Answer
1 / 3 * b * b * h(b)
Answer
math.pi * r * r * h(c)
Answer
1 / 3 * math.pi * r * r * h(d)
Answer
math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)(e)
Answer
(x - h) ** 2 + (y - k) ** 2 == r ** 2(f)
Answer
x = (-b + math.sqrt(b * b - 4 * a * c)) / (2 * a)(g)
Answer
a ** n * a ** m == a ** (n + m)(h)
Answer
(a ** n) ** m == a ** (n * m)(i)
Answer
a ** n / a ** m == a ** (n - m)(j)
Answer
a ** -n == 1 / a ** nint('a') produces error. Why ?
Answer
int() converts its argument into an integer. As 'a' is a letter, it cannot be converted into a valid integer hence int('a') produces an error.
int('a') produces error but following expression having int('a') in it, does not return error. Why?
len('a') + 2 or int('a')
Answer
The or operator tests the second operand only if the first operand is false otherwise it ignores it. In the expression, the first operand of or operator is len('a') + 2. It evaluates to 3 and as it is a non-zero value hence it is True for or operator. As first operand of or operator is True so it doesn't evaluate its second argument int('a') and no error is returned.
Write expression to convert the values 17, len('ab') to (i) integer (ii) str (iii) boolean values
Answer
(i) int(17), int(len('ab'))
(ii) str(17), str(len('ab'))
(iii) bool(17), bool(len('ab'))
Evaluate and Justify:
(i) 22 / 17 = 37 / 47 + 88 /83
(ii) len('375')**2
Answer
(i) It produces an error as LHS value in this case is an expression that evaluates to a literal whereas LHS value should be a variable.
(ii) len('375')**2
⇒ 3 ** 2 [∵ len('375') = 3]
⇒ 9 [∵ 3 * 3 = 9]
Evaluate and Justify:
(i) 22.0/7.0 - 22/7
(ii) 22.0/7.0 - int(22.0/7.0)
(iii) 22/7 - int (22.0)/7
Answer
(i) 22.0/7.0 - 22/7
⇒ 0
As values of 22.0/7.0 and 22/7 are equal, subtracting them will give the result as 0.0.
(ii) 22.0/7.0 - int(22.0/7.0)
⇒ 3.142857142857143 - 3
⇒ 0.142857142857143
(iii) 22/7 - int (22.0)/7
⇒ 0.0
int (22.0) gives 22 so the expression becomes 22/7 - 22/7 which results in 0.0
Evaluate and Justify:
(i) false and None
(ii) 0 and None
(iii) True and None
(iv) None and None
Answer
(i) This produces an error as false is an invalid literal in Python. It should be False. Had the expression being False and None, the return value will be False.
(ii) This logical expression evaluates to 0. As first operand of and operator is false so it will return the first operand itself.
(iii) This logical expression evaluates to None. As first operand of and operator is True so it will return the second operand.
(iv) This logical expression evaluates to None. As first operand of and operator is false so it will return the first operand itself.
Evaluate and Justify:
(a) 0 or None and "or"
(b) 1 or None and 'a' or 'b'
(c) False and 23
(d) 23 and False
(e) not (1 == 1 and 0 != 1)
(f) "abc" == "Abc" and not (2 == 3 or 3 == 4)
(g) False and 1 == 1 or not True or 1 == 1 and False or 0 == 0
Answer
(a) 0 or None and "or"
⇒ 0 or None [∵ and has higher precedence than or]
⇒ None
(b) 1 or None and 'a' or 'b'
⇒ 1 or None or 'b'
⇒ 1 or 'b'
⇒ 1
(c) False and 23
⇒ False
(d) 23 and False
⇒ False
(e) not (1 == 1 and 0 != 1)
⇒ not (True and True)
⇒ not True
⇒ False
(f) "abc" == "Abc" and not (2 == 3 or 3 == 4)
⇒ "abc" == "Abc" and not (False or False)
⇒ "abc" == "Abc" and not False
⇒ False and not False
⇒ False and True
⇒ False
(g) False and 1 == 1 or not True or 1 == 1 and False or 0 == 0
⇒ False and True or not True or True and False or True
⇒ False and True or False or True and False or True
⇒ False or False or False or True
⇒ False or False or True
⇒ False or True
⇒ True
Evaluate the following for each expression that is successfully evaluated, determine its value and type for unsuccessful expression, state the reason.
(a) len("hello") == 25/5 or 20/10
(b) 3 < 5 or 50/(5 - (3 + 2))
(c) 50/(5 - (3 + 2)) or 3 < 5
(d) 2 * (2 * (len("01")))
Answer
(a) len("hello") == 25/5 or 20/10
⇒ 5 == 25/5 or 20/10
⇒ 5 == 5 or 2
⇒ True or 2
⇒ True
The type of result is Boolean.
(b) 3 < 5 or 50/(5 - (3 + 2))
⇒ True or 50/(5 - (3 + 2)) [∵ first operand is True, second operand is not evaluated so no division by 0 error happens]
⇒ True
The type of result is Boolean.
(c) 50/(5 - (3 + 2)) or 3 < 5
⇒ 50/(5 - 5) or 3 < 5
⇒ 50/0 or 3 < 5
⇒ Division by Zero Error
As the denominator of or operator's first operand is 0, Division by Zero error occurs.
(d) 2 * (2 * (len("01")))
⇒ 2 * (2 * 2)
⇒ 2 * 4
⇒ 8
The type of result is Integer.
Write an expression that uses exactly 3 arithmetic operators with integer literals and produces result as 99.
Answer
9 * 10 + 21 % 12Add parentheses to the following expression to make the order of evaluation more clear.
y % 4 == 0 and y % 100 != 0 or y % 400 == 0
Answer
((y % 4) == 0) and ((y % 100) != 0) or ((y % 400) == 0)
A program runs to completion but gives an incorrect result. What type of error would have caused it?
Answer
Logical errors can make a program run till completion but give incorrect result.
In Python, strings are immutable while lists are mutable. What is the difference?
Answer
In Python, strings are immutable means that individual letter assignment for strings is not allowed. For example:
name='hello'
name[0] = 'p'The above Python code will cause an error as we are trying to assign some value to an individual letter of a string.
Lists are mutable in Python means that we can assign values to individual elements of a list. For example:
a = [1, 2, 3, 4, 5]
a[0] = 10The above Python code will work correctly without any errors as Lists are mutable in Python.
How does the // operator differ from the / operator? Give an example of where // would be needed.
Answer
The Division operator (/) divides its first operand by second operand and always returns the result as a float value whereas Floor Division operator (//) divides its first operand by second operand and truncates the fractional part of the result and returns it as an int value. Floor Division operator is useful in situations where we only need the integer part of the division operation result. For example, to determine how many minutes are there in some given number of seconds:
secs = 2565
mins = 2565 // 60MidAir Airlines will only allow carry-on bags that are no more than 22 inches long, 14 inches wide, and 9 inches deep. Assuming that variables named length, width, and depth have already been assigned values, write an expression combining the three that evaluates to True if bag fits within those limits, and False otherwise.
Answer
length <= 22 and width <= 14 and depth <= 9
What are main error types? Which types are most dangerous and why?
Answer
The types of errors are:
- Compile Time Errors (Syntax errors and Semantic Errors)
- Runtime Errors
- Logical Errors
Logical Errors are the most dangerous as they are hardest to prevent, find and fix.
Correct any false statements:
(a) Compile-time errors are usually easier to detect and to correct than run-time errors.
(b) Logically errors can usually be detected by the compiler.
Answer
(a) The statement is correct.
(b) The statement is incorrect. The correct statement should be:
Logical errors cannot be detected by the compiler.
Differentiate between a syntax error and a semantics error.
Answer
| Syntax Error | Semantics Error |
|---|---|
| Syntax errors occurs when the rules of the programming language are violated. | Semantic errors occur when the statement are not meaningful. |
| Example: x = false | Example: x * y = z |
Differentiate between a syntax error and a logical error in a python program. When is each type of error likely to be found?
Answer
| Syntax Error | Logical Error |
|---|---|
| Syntax Errors occur when we violate the rules of writing the statements of the programming language. | Logical Errors occur due to our mistakes in programming logic. |
| Program fails to compile and execute. | Program compiles and executes but doesn't give the desired output. |
| Syntax Errors are caught by the compiler. | Logical errors need to be found and corrected by people working on the program. |
Syntax errors are found at compile type whereas Logical errors are found when the program starts executing.
What is the difference between an error and exception?
Answer
An Error is a bug in the code that causes irregular output or stops the program from executing whereas an Exception is an irregular unexpected situation occurring during execution on which programmer has no control.
What is the result produced by (i) bool (0) (ii) bool (str(0))? Justify the outcome.
Answer
(i) bool (0)
The result is False as truth value of 0 is falsetval
(ii) bool (str(0))
The result is True as str(0) converts 0 to string "0". As it becomes a non-empty string so its truth value is truetval
What will be the output, if input for both the statements is 5 + 4/2.
6 == input ("Value 1:")
6 == int(input ("value 2:"))
Answer
Output of first statement is False as '5 + 4/2' is entered as a string so it cannot be equal to the number 6.
The second statement gives an error as int() function cannot convert the string '5 + 4/2' to a valid integer.
Following Python code has an expression with all integer values. Why is the result in floating point form?
a, b, c = 2, 3, 6
d = a + b * c/b
print(d)Answer
The output of the above Python code is 8.0. Division operator is present in the expression. The result of Division operator is of float type. Due to implicit conversion, other operand in this expression are also converted to float type and hence the final result is in floating point form.
What will following code print?
a = va = 3
b = va = 3
print (a, b)Answer
This Python code prints:
3 3
What will following code print?
a = 3
b = 3.0
print (a == b)
print (a is b)Answer
This Python code prints:
True
False
As values of a and b are equal so equality operator returns True. a is of int type and b is of float type so a and b are different objects so a is b returns False.
What will be output produced by following code? State reason for this output.
a, b, c = 1, 1, 2
d = a + b
e = 1.0
f = 1.0
g = 2.0
h = e + f
print(c == d)
print(c is d)
print(g == h)
print(g is h)Answer
True
True
True
False
Value of d becomes 2 and as values of c and d are equal so print(c == d) prints True.
What will be output produced by following code? State reason for this output.
a = 5 - 4 - 3
b = 3**2**3
print(a)
print(b) Answer
-2
6561
a = 5 - 4 - 3
⇒ a = 1 - 3
⇒ a = -2
The exponentiation operator (**) has associativity from right to left so:
b = 3**2**3
⇒ b = 3**8
⇒ b = 6561
What will be output produced by following code? State reason for this output.
a, b, c = 1, 1, 1
d = 0.3
e=a+b+c-d
f=a+b+c == d
print(e)
print(f)Answer
2.7
False
e = a+b+c-d
⇒ e = 1+1+1-0.3
⇒ e = 3-0.3
⇒ e = 2.7
As 0.3 is float so implicit conversion converts 3 also to float and result of the expression is of float type.
f = a + b + c == d
⇒ f = 1 + 1 + 1 == 0.3
⇒ f = 3 == 0.3
⇒ f = False
Make change in the expression for z of previous question so that the output produced is zero. You cannot change the operators and order of variables. (Hint. Use a function around a sub-expression)
Answer
x, y = 4, 8
z = int(x/y)*y
print(z)Consider the following expression:
x = "and" * (3 + 2) > "or" + "4"
What is the data type of value that is computed by this expression?
Answer
The data type of value that is computed by this expression is bool.
x = "and" * (3 + 2) > "or" + "4"
⇒ x = "and" * 5 > "or" + "4"
⇒ x = "andandandandand" > "or4"
⇒ x = False
What will be the output of following Python code?
a = 12
b = 7.4
c = 1
a -= b
print(a, b)
a *= 2 + c
print(a)
b += a * c
print(b)Answer
4.6 7.4
13.799999999999999
21.2
a -= b
⇒ a = a - b
⇒ a = 12 - 7.4
⇒ a = 4.6
a *= 2 + c
⇒ a = 4.6 * (2 + c)
⇒ a = 4.6 * (2 + 1)
⇒ a = 4.6 * 3
⇒ a = 13.799999999999999
b += a * c
⇒ b = b + (a * c)
⇒ b = 7.4 + (13.799999999999999 * 1)
⇒ b = 7.4 + 13.799999999999999
⇒ b = 21.2
What will be the output of following Python code?
x, y = 4, 8
z = x/y*y
print(z)Answer
4.0
z = x/y*y
⇒ z = 4/8*8
⇒ z = 0.5*8
⇒ z = 4.0
Consider the following code segment:
a = input()
b = int(input())
c = a + b
print(c)When the program is run, the user first enters 10 and then 5, it gives an error. Find the error, its reason and correct it
Answer
The error is:
TypeError: can only concatenate str (not "int") to str
It occurs because a is of type string but b is of type int. We are trying to add together a string operand and an int operand using addition operator. This is not allowed in Python hence this error occurs.
To correct it, we need to cast a to int like this:
a = int(input())
Consider the following code segment:
a = input("Enter the value of a:")
b = input("Enter the value of b:")
print(a + b)If the user runs the program and enters 11 for a and 9 for b then what will the above code display?
Answer
Enter the value of a:11
Enter the value of b:9
119
input() function accepts user input as string type. The data type of a and b is string not int so addition operator concatenates them to print 119 instead of 20.
Find out the error and the reason for the error in the following code. Also, give the corrected code.
a, b = "5.0", "10.0"
x = float(a/b)
print(x)Answer
a and b are defined as strings not float or int. Division operator doesn't support strings as its operand so we get the error — unsupported operand type(s) for /: "str" and "str".
The corrected code is:
a, b = 5.0, 10.0
x = float(a/b)
print(x)Consider the following program. It is supposed to compute the hypotenuse of a right triangle after the user enters the lengths of the other two sides.
a = float(input("Enter the length of the first side:"))
b = float(input("Enter the length of the second side:"))
h = sqrt(a * a + b * b)
print("The length of the hypotenuse is", h)When this program is run, the following output is generated (note that input entered by the user is shown in bold):
Enter the length of the first side: 3
Enter the length of the second side: 4
Traceback (most recent call last):
h = sqrt(a * a + b * b)
NameError: name 'sqrt' is not defined
Why is this error occurring? How would you resolve it ?
Answer
The error is coming because math module is not imported in the code. To resolve it, we should import the math module using the import statement import math.
Consider the following program. It is supposed to compute the hypotenuse of a right triangle after the user enters the lengths of the other two sides.
a = float(input("Enter the length of the first side:"))
b = float(input("Enter the length of the second side:"))
h = sqrt(a * a + b * b)
print("The length of the hypotenuse is", h)After adding import math to the code given above, what other change(s) are required in the code to make it fully work ?
Answer
After adding import math statement, we need to change the line h = sqrt(a * a + b * b) to h = math.sqrt(a * a + b * b). The corrected working code is below:
import math
a = float(input("Enter the length of the first side:"))
b = float(input("Enter the length of the second side:"))
h = math.sqrt(a * a + b * b)
print("The length of the hypotenuse is", h)Which of the following expressions will result in an error message being displayed when a program containing it is run?
(a) 2.0/4
(b) "3" + "Hello"
(c) 4 % 15
(d) int("5")/float("3")
(e) float("6"/"2")
Answer
(a) No Error
(b) No Error
(c) No Error
(d) No Error
(e) This will cause an error of unsupported operand types as using division operator on string types is not allowed in Python.
Following expression does not report an error even if it has a sub-expression with 'divide by zero' problem:
3 or 10/0What changes can you make to above expression so that Python reports this error?
Answer
Interchanging the operands of or operator as shown below will make Python report this error:
10/0 or 3What is the output produced by following code?
a, b = bool(0), bool(0.0)
c, d = str(0), str(0.0)
print (len(a), len(b))
print (len(c), len(d))Answer
The above code will give an error as the line print (len(a), len(b)) is calling len function with bool arguments which is not allowed in Python.
Given a string s = "12345". Can you write an expression that gives sum of all the digits shown inside the string s i.e., the program should be able to produce the result as 15 (1+2+3+4+5).
[Hint. Use indexes and convert to integer]
Answer
print(int(s[0]) + int(s[1]) + int(s[2]) + int(s[3]) + int(s[4]))Predict the output if e is given input as 'True':
a = True
b = 0 < 5
print (a == b)
print (a is b)
c = str (a)
d = str (b)
print (c == d)
print (c is d)
e = input ("Enter :")
print (c == e)
print (c is e)Answer
True
True
True
True
Enter :True
True
False
- As 0 < 5 is True so b value of b becomes True and its type is bool.
print (a == b)gives True as a and b both are True.print (a is b)gives True as a and b both being True point to the same object in memory.- Similarly
print (c == d)andprint (c is d)give True as c and d both are string and point to the same object in memory. - The user input for e is True so e is of type string having value "True".
- As value of strings c and e is "True" so
print (c == e)gives True. - Even though the values of strings c and e are same, they point to different objects in memory so
print (c is e)gives False.
Find the errors(s)
name = "HariT"
print (name)
name[2] = 'R'
print (name) Answer
The line name[2] = 'R' is trying to assign the letter 'R' to the second index of string name but strings are immutable in Python and hence such item assignment for strings is not supported in Python.
Find the errors(s)
a = bool (0)
b = bool (1)
print (a == false)
print (b == true)Answer
false and true are invalid literals in Python. The correct boolean literals are False and True.
Find the errors(s)
print (type (int("123")))
print (type (int("Hello")))
print (type (str("123.0")))Answer
In the line print (type (int("Hello"))), string "Hello" is given as an argument to int() but it cannot be converted into a valid integer so it causes an error.
Find the errors(s)
pi = 3.14
print (type (pi))
print (type ("3.14"))
print (type (float ("3.14")))
print (type (float("three point fourteen")))Answer
In the line print (type (float("three point fourteen"))), string "three point fourteen" is given as an argument to float() but it cannot be converted into a valid floating-point number so it causes an error.
Find the errors(s)
print ("Hello" + 2)
print ("Hello" + "2")
print ("Hello" * 2) Answer
The line print ("Hello" + 2) causes an error as addition operator (+) cannot concatenate a string and an int.
Find the errors(s)
print ("Hello"/2)
print ("Hello" / 2)Answer
Both the lines of this Python code will give an error as strings cannot be used with division operator (/).
What will be the output produced?
x, y, z = True, False, False
a = x or (y and z)
b = (x or y) and z
print(a, b)Answer
True False
- x or (y and z)
⇒ True or (False and False)
⇒ True - (x or y) and z
⇒ (True or False) and False
⇒ True and False
⇒ False
What will be the output produced?
x, y = '5', 2
z = x + y
print(z)Answer
This code produces an error in the line z = x + y as operands of addition operator (+) are string and int, respectively which is not supported by Python.
What will be the output produced?
s = 'Sipo'
s1 = s + '2'
s2 = s * 2
print(s1)
print(s2)Answer
Sipo2
SipoSipo
s1 = s + '2'concatenates 'Sipo' and '2' storing 'Sipo2' in s1.s2 = s * 2repeats 'Sipo' twice storing 'SipoSipo' in s2.
What will be the output produced?
w, x, y, z = True , 4, -6, 2
result = -(x + z) < y or x ** z < 10
print(result)Answer
False
-(x + z) < y or x ** z < 10
⇒ -(4 + 2) < -6 or 4 ** 2 < 10
⇒ -6 < -6 or 4 ** 2 < 10
⇒ -6 < -6 or 16 < 10
⇒ False or False
⇒ False
Program is giving a weird result of "0.50.50.50.50.50.50..........". Correct it so that it produces the correct result which is the probability value (input as 0.5) times 150.
probability = input("Type a number between 0 and 1: ")
print("Out of 150 tries, the odds are that only", (probability * 150), "will succeed.")[Hint. Consider its datatype.]
Answer
The corrected program is below:
probability = float(input("Type a number between 0 and 1: "))
print("Out of 150 tries, the odds are that only", (probability * 150), "will succeed.")Write a program to obtain principal amount, rate of interest and time from user and compute simple interest.
p = float(input("Enter principal: "))
r = float(input("Enter rate: "))
t = float(input("Enter time: "))
si = p * r * t / 100
print("Simple Interest =", si)Enter principal: 55000.75
Enter rate: 14.5
Enter time: 3
Simple Interest = 23925.32625
Write a program to obtain temperatures of 7 days (Monday, Tuesday ... Sunday) and then display average temperature of the week.
d1 = float(input("Enter Sunday Temperature: "))
d2 = float(input("Enter Monday Temperature: "))
d3 = float(input("Enter Tuesday Temperature: "))
d4 = float(input("Enter Wednesday Temperature: "))
d5 = float(input("Enter Thursday Temperature: "))
d6 = float(input("Enter Friday Temperature: "))
d7 = float(input("Enter Saturday Temperature: "))
avg = (d1 + d2 + d3 + d4 + d5 + d6 + d7) / 7
print("Average Temperature =", avg)Enter Sunday Temperature: 21.6
Enter Monday Temperature: 22.3
Enter Tuesday Temperature: 24.5
Enter Wednesday Temperature: 23.0
Enter Thursday Temperature: 23.7
Enter Friday Temperature: 24.2
Enter Saturday Temperature: 25
Average Temperature = 23.47142857142857
Write a program to obtain x, y, z from user and calculate expression : 4x4 + 3y3 + 9z + 6π
import math
x = int(input("Enter x: "))
y = int(input("Enter y: "))
z = int(input("Enter z: "))
res = 4 * x ** 4 + 3 * y ** 3 + 9 * z + 6 * math.pi
print("Result =", res)Enter x: 2
Enter y: 3
Enter z: 5
Result = 208.84955592153875
Write a program that reads a number of seconds and prints it in form : mins and seconds, e.g., 200 seconds are printed as 3 mins and 20 seconds.
[Hint. use // and % to get minutes and seconds]
totalSecs = int(input("Enter seconds: "))
mins = totalSecs // 60
secs = totalSecs % 60
print(mins, "minutes and", secs, "seconds")Enter seconds: 200
3 minutes and 20 seconds
Write a program to take year as input and check if it is a leap year or not.
y = int(input("Enter year to check: "))
print(y % 4 and "Not a Leap Year" or "Leap Year")Enter year to check: 2020
Leap Year
Write a program to take two numbers and print if the first number is fully divisible by second number or not.
x = int(input("Enter first number: "))
y = int(input("Enter second number: "))
print(x % y and "Not Fully Divisible" or "Fully Divisible")Enter first number: 4
Enter second number: 2
Fully Divisible
Write a program to take a 2-digit number and then print the reversed number. That is, if the input given is 25, the program should print 52.
x = int(input("Enter a two digit number: "))
y = x % 10 * 10 + x // 10
print("Reversed Number:", y)Enter a two digit number: 25
Reversed Number: 52
Try writing program (similar to previous one) for three digit number i.e., if you input 123, the program should print 321.
x = int(input("Enter a three digit number: "))
d1 = x % 10
x //= 10
d2 = x % 10
x //= 10
d3 = x % 10
y = d1 * 100 + d2 * 10 + d3
print("Reversed Number:", y)Enter a three digit number: 123
Reversed Number: 321
Write a program to take two inputs for day, month and then calculate which day of the year, the given date is. For simplicity, take 30 days for all months. For example, if you give input as: Day3, Month2 then it should print "Day of the year : 33".
d = int(input("Enter day: "))
m = int(input("Enter month: "))
n = (m - 1) * 30 + d
print("Day of the year:", n)Enter day: 3
Enter month: 2
Day of the year: 33
Write a program that inputs an age and print age after 10 years as shown below:
What is your age? 17
In ten years, you will be 27 years old!
a = int(input("What is your age? "))
print("In ten years, you will be", a + 10, "years old!")What is your age? 17
In ten years, you will be 27 years old!
Write a program that asks a user for a number of years, and then prints out the number of days, hours, minutes, and seconds in that number of years.
How many years? 10
10.0 years is:
3650.0 days
87600.0 hours
5256000.0 minutes
315360000.0 seconds
y = float(input("How many years? "))
d = y * 365
h = d * 24
m = h * 60
s = m * 60
print(y, "years is:")
print(d, "days")
print(h, "hours")
print(m, "minutes")
print(s, "seconds")How many years? 10
10.0 years is:
3650.0 days
87600.0 hours
5256000.0 minutes
315360000.0 seconds
Write a program to find a side of a right angled triangle whose two sides and an angle is given.
import math
a = float(input("Enter base: "))
b = float(input("Enter height: "))
x = float(input("Enter angle: "))
c = math.sqrt(a ** 2 + b ** 2)
print("Hypotenuse =", c)Enter base: 10.5
Enter height: 5.5
Enter angle: 60
Hypotenuse = 11.853269591129697
Write a program to calculate the radius of a sphere whose area (4πr2) is given.
import math
area = float(input("Enter area of sphere: "))
r = math.sqrt(area / (4 * math.pi))
print("Radius of sphere =", r)Enter area of sphere: 380.14
Radius of sphere = 5.50005273006328
Write a program that inputs a string and then prints it equal to number of times its length, e.g.,
Enter string : "eka"
Result ekaekaeka
str = input("Enter string: ")
len = len(str)
opStr = str * len
print("Result", opStr)Enter string: eka
Result ekaekaeka
Find the volume of the cylinder (πr2h) as shown:
Radius = 8 cm
Height = 15 cm
import math
r = 8
h = 15
v = math.pi * r * r * h
print("Volume of Cylinder =", v)Volume of Cylinder = 3015.928947446201
Write a program to input the radius of a sphere and calculate its volume (V = 4/3πr3)
import math
r = float(input("Enter radius of sphere: "))
v = 4 / 3 * math.pi * r ** 3
print("Volume of sphere = ", v)Enter radius of sphere: 3.5
Volume of sphere = 179.59438003021648
Write a program to calculate amount payable after simple interest.
p = float(input("Enter principal: "))
r = float(input("Enter rate: "))
t = float(input("Enter time: "))
si = p * r * t / 100
amt = p + si
print("Amount Payable =", amt)Enter principal: 55000.75
Enter rate: 14.5
Enter time: 3
Amount Payable = 78926.07625
Write a program to calculate amount payable after compound interest.
p = float(input("Enter principal: "))
r = float(input("Enter rate: "))
t = float(input("Enter time: "))
amt = p * (1 + r / 100) ** t
print("Amount Payable =", amt)Enter principal: 15217.75
Enter rate: 9.2
Enter time: 3
Amount Payable = 19816.107987312007