Professional Documents
Culture Documents
Kayal Mam Document
Kayal Mam Document
Question 1
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.
Question 2
How many integer types are supported by Python? Name them.
Answer
Two integer types are supported by Python. They are:
1. Integers (signed)
2. Booleans
Question 3
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.
Question 4
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.
Question 5
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.
Question 6
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.
Question 7
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:
1. Lists
2. Dictionaries
3. Sets
Immutable types in Python are:
1. Integers
2. Floating-Point numbers
3. Booleans
4. Strings
5. Tuples
Question 8
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:
1. Type
2. Value
3. 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)
Question 9
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.
Question 10
Are these values equal? Why/why not?
1. 20 and 20.0
2. 20 and int(20)
3. str(20) and str(20.0)
4. 'a' and "a"
Answer
1. 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.
2. 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.
3. 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.
4. For 'a' and "a", both equality (==) and is operator returns True as their values are same
and they point to the same object.
Question 11
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.
Question 12
What is the difference between implicit type conversion and explicit type conversion?
Answer
Implicit Type Conversion Explicit Type Conversion
An implicit type conversion is
An explicit type conversion is user-defined
automatically performed by the
conversion that forces an expression to be of
compiler when differing data types are
specific type.
intermixed in an expression.
An implicit type conversion is
An explicit type conversion is specified
performed without programmer's
explicitly by the programmer.
intervention.
Example: Example:
a, b = 5, 25.5 a, b = 5, 25.5
c=a+b c = int(a + b)
Question 13
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.
Question 14
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
Explanation
\begin{matrix} \underset{-5}{\overset{0}\bold{H}} & \underset{-4}{\overset{1}\bold{e}} &
\underset{-3}{\overset{2}\bold{l}} & \underset{-2}{\overset{3}\bold{l}} & \underset{-
1}{\overset{4}\bold{o}} \end{matrix}−5H0−4e1−3l2−2l3−1o4
Question 15
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.
Question 16
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.
Question 17
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.
Question 18
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.
Question 19
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
Question 20
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
Question 21
Write following expressions in Python:
(a) \dfrac{1}{3} b^2 h31b2h
Answer
1/3*b*b*h
(b) \pi r^2 hπr2h
Answer
math.pi * r * r * h
(c) \dfrac{1}{3} \pi r^2 h31πr2h
Answer
1 / 3 * math.pi * r * r * h
(d) \sqrt{(x2 - x1)^2 + (y2 - y1)^2}(x2−x1)2+(y2−y1)2
Answer
math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
(e) (x - h)^2 + (y - k)^2 = r^2(x−h)2+(y−k)2=r2
Answer
(x - h) ** 2 + (y - k) ** 2 == r ** 2
(f) x = \dfrac{-b + \sqrt{b^2 - 4ac}}{2a}x=2a−b+b2−4ac
Answer
x = (-b + math.sqrt(b * b - 4 * a * c)) / (2 * a)
(g) a^n \times a^m = a^{n+m}an×am=an+m
Answer
a ** n * a ** m == a ** (n + m)
(h) (a^n)^m = a^{nm}(an)m=anm
Answer
(a ** n) ** m == a ** (n * m)
(i) \dfrac{a^n}{a^m} = a^{n - m}aman=an−m
Answer
a ** n / a ** m == a ** (n - m)
(j) a^{-n} = \dfrac{1}{a^n}a−n=an1
Answer
a ** -n == 1 / a ** n
Question 22
int('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.
Question 23
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.
Question 24
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'))
Question 25
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]
Question 26
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
Question 27
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.
Question 28
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
⇒ not 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
Question 29
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.
Question 30
Write an expression that uses exactly 3 arithmetic operators with integer literals and produces
result as 99.
Answer
9 * 10 + 21 % 12
Question 31
Add 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)
Question 32
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.
Question 33
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] = 10
The above Python code will work correctly without any errors as Lists are mutable in Python.
Question 34
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 // 60
Question 35
MidAir 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
Question 36
What are main error types? Which types are most dangerous and why?
Answer
The types of errors are:
Question 37
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.
Question 38
Differentiate between a syntax error and a semantics error.
Answer
Question 39
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
Logical Errors occur due to our mistakes in
rules of writing the statements of the
programming logic.
programming language.
Program compiles and executes but doesn't give
Program fails to compile and execute.
the desired output.
Syntax Errors are caught by the Logical errors need to be found and corrected by
compiler. people working on the program.
Syntax errors are found at compile type whereas Logical errors are found when the program
starts executing.
Question 40
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.
Type B: Application Based Questions
Question 1
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
Question 2
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.
Question 3
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.
Question 4a
What will following code print?
a = va = 3
b = va = 3
print (a, b)
Answer
This Python code prints:
33
Question 4b
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.
Question 5a
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
Output
True
True
True
False
Explanation
Value of d becomes 2 and as values of c and d are equal so print(c == d) prints True.
Question 5b
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
Output
-2
6561
Explanation
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
Question 5c
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
Output
2.7
False
Explanation
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
Question 6a
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)
Output
4.6 7.4
13.799999999999999
21.2
Explanation
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
Question 6b
What will be the output of following Python code?
x, y = 4, 8
z = x/y*y
print(z)
Output
4.0
Explanation
z = x/y*y
⇒ z = 4/8*8
⇒ z = 0.5*8
⇒ z = 4.0
Question 7
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)
Question 8
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
Question 9
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())
Question 10
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
Output
Enter the value of a:11
Enter the value of b:9
119
Explanation
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.
Question 11
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)
Question 12
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.
Question 13
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)
Question 14
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.
Question 15a
Following expression does not report an error even if it has a sub-expression with 'divide by zero'
problem:
3 or 10/0
What 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 3
Question 15b
What 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.
Question 16
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]))
Question 17
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
Output
True
True
True
True
Enter :True
True
False
Explanation
1. As 0 < 5 is True so b value of b becomes True and its type is bool.
2. print (a == b) gives True as a and b both are True.
3. print (a is b) gives True as a and b both being True point to the same object in memory.
4. Similarly print (c == d) and print (c is d) give True as c and d both are string and point to
the same object in memory.
5. The user input for e is True so e is of type string having value "True".
6. As value of strings c and e is "True" so print (c == e) gives True.
7. 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.
Question 18a
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.
Question 18b
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.
Question 18c
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.
Question 18d
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.
Question 18e
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.
Question 18f
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 (/).
Question 19a
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)
Output
True False
Explanation
1. x or (y and z)
⇒ True or (False and False)
⇒ True
2. (x or y) and z
⇒ (True or False) and False
⇒ True and False
⇒ False
Question 19b
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.
Question 19c
What will be the output produced?
s = 'Sipo'
s1 = s + '2'
s2 = s * 2
print(s1)
print(s2)
Answer
Output
Sipo2
SipoSipo
Explanation
Question 19d
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
Output
False
Explanation
-(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
Question 20
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.")
Question 21
Consider the code given below:
import random
r = random.randrange(100, 999, 5)
print(r, end = ' ')
r = random.randrange(100, 999, 5)
print(r, end = ' ')
r = random.randrange(100, 999, 5)
print(r)
Which of the following are the possible outcomes of the above code ? Also, what can be the
maximum and minimum number generated by line 2 ?
(a) 655, 705, 220
(b) 380, 382, 505
(c) 100, 500, 999
(d) 345, 650, 110
Answer
The possible outcomes of the above code can be:
Option (a) — 655, 705, 220
Option (d) — 345, 650, 110
Maximum number can be 995 and minimum number can be 100.
Question 22
Consider the code given below:
import random
r = random.randint(10, 100) - 10
print(r, end = ' ')
r = random.randint(10, 100) - 10
print(r, end = ' ')
r = random.randint(10, 100) - 10
print(r)
Which of the following are the possible outcomes of the above code? Also, what can be the
maximum and minimum number generated by line 2?
(a) 12 45 22
(b) 100 80 84
(c) 101 12 43
(d) 100 12 10
Answer
The possible outcomes of the above code can be:
Option (a) — 12 45 22
Maximum number can be 90 and minimum number can be 0.
Question 23
Consider the code given below:
import random
r = random.random() * 10
print(r, end = ' ')
r = random. random() * 10
print(r, end = ' ')
r = random.random() * 10
print(r)
Which of the following are the possible outcomes of the above code? Also, what can be the
maximum and minimum number generated by line 2 ?
(a) 0.5 1.6 9.8
(b) 10.0 1.0 0.0
(c) 0.0 5.6 8.7
(d) 0.0 7.9 10.0
Answer
The possible outcomes of the above code can be:
Option (a) — 0.5 1.6 9.8
Option (c) — 0.0 5.6 8.7
Maximum number can be 9.999999..... and minimum number can be 0.
Question 24
Consider the code given below:
import statistics as st
v = [7, 8, 8, 11, 7, 7]
m1 = st.mean(v)
m2 = st.mode(v)
m3 = st.median(v)
print(m1, m2, m3)
Which of the following is the correct output of the above code?
(a) 7 8 7.5
(b) 8 7 7
(c) 8 7 7.5
(c) 8.5 7 7.5
Answer
The correct output of the above code is:
Option (c) — 8 7 7.5
Type C: Programming Practice/Knowledge based Questions
Question 1
Write a program to obtain principal amount, rate of interest and time from user and compute
simple interest.
Solution
p = float(input("Enter principal: "))
r = float(input("Enter rate: "))
t = float(input("Enter time: "))
si = p * r * t / 100
Output
Enter principal: 55000.75
Enter rate: 14.5
Enter time: 3
Simple Interest = 23925.32625
Question 2
Write a program to obtain temperatures of 7 days (Monday, Tuesday ... Sunday) and then display
average temperature of the week.
Solution
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: "))
Output
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
Question 3
Write a program to obtain x, y, z from user and calculate expression : 4x4 + 3y3 + 9z + 6π
Solution
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
Output
Enter x: 2
Enter y: 3
Enter z: 5
Result = 208.84955592153875
Question 4
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]
Solution
totalSecs = int(input("Enter seconds: "))
mins = totalSecs // 60
secs = totalSecs % 60
Output
Enter seconds: 200
3 minutes and 20 seconds
Question 5
Write a program to take year as input and check if it is a leap year or not.
Solution
y = int(input("Enter year to check: "))
print(y % 4 and "Not a Leap Year" or "Leap Year")
Output
Enter year to check: 2020
Leap Year
Question 6
Write a program to take two numbers and print if the first number is fully divisible by second
number or not.
Solution
x = int(input("Enter first number: "))
y = int(input("Enter second number: "))
print(x % y and "Not Fully Divisible" or "Fully Divisible")
Output
Enter first number: 4
Enter second number: 2
Fully Divisible
Question 7
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.
Solution
x = int(input("Enter a two digit number: "))
y = x % 10 * 10 + x // 10
print("Reversed Number:", y)
Output
Enter a two digit number: 25
Reversed Number: 52
Question 8
Try writing program (similar to previous one) for three digit number i.e., if you input 123, the
program should print 321.
Solution
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)
Output
Enter a three digit number: 123
Reversed Number: 321
Question 9
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".
Solution
d = int(input("Enter day: "))
m = int(input("Enter month: "))
n = (m - 1) * 30 + d
Output
Enter day: 3
Enter month: 2
Day of the year: 33
Question 10
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
Solution
y = float(input("How many years? "))
d = y * 365
h = d * 24
m = h * 60
s = m * 60
Output
How many years? 10
10.0 years is:
3650.0 days
87600.0 hours
5256000.0 minutes
315360000.0 seconds
Question 11
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!
Solution
a = int(input("What is your age? "))
print("In ten years, you will be", a + 10, "years old!")
Output
What is your age? 17
In ten years, you will be 27 years old!
Question 12
Write a program whose three sample runs are shown below:
Sample Run 1:
Random number between 0 and 5 (A) : 2
Random number between 0 and 5 (B) :5.
A to the power B = 32
Sample Run 2:
Random number between 0 and 5 (A) : 4
Random number between 0 and 5 (B) :3.
A to the power B = 64
Sample Run 3:
Random number between 0 and 5 (A) : 1
Random number between 0 and 5 (B) :1.
A to the power B = 1
Solution
import random
a = random.randint(0, 5)
b = random.randint(0, 5)
c = a ** b
Output
Random number between 0 and 5 (A) : 5
Random number between 0 and 5 (B) : 3
A to the power B = 125
Question 13
Write a program that generates six random numbers in a sequence created with (start, stop, step).
Then print the mean, median and mode of the generated numbers.
Solution
import random
import statistics
print("Generated Numbers:")
print(a, b, c, d, e, f)
seq = (a, b, c, d, e, f)
mean = statistics.mean(seq)
median = statistics.median(seq)
mode = statistics.mode(seq)
Output
Enter start: 100
Enter stop: 500
Enter step: 5
Generated Numbers:
235 255 320 475 170 325
Mean = 296.6666666666667
Median = 287.5
Mode = 235
Question 14
Write a program to generate 3 random integers between 100 and 999 which is divisible by 5.
Solution
import random
a = random.randrange(100, 999, 5)
b = random.randrange(100, 999, 5)
c = random.randrange(100, 999, 5)
print("Generated Numbers:", a, b, c)
Output
Generated Numbers: 885 825 355
Question 15
Write a program to generate 6 digit random secure OTP between 100000 to 999999.
Solution
import random
print("OTP:", otp);
Output
OTP: 553072
Question 16
Write a program to generate 6 random numbers and then print their mean, median and mode.
Solution
import random
import statistics
a = random.random()
b = random.random()
c = random.random()
d = random.random()
e = random.random()
f = random.random()
print("Generated Numbers:")
print(a, b, c, d, e, f)
seq = (a, b, c, d, e, f)
mean = statistics.mean(seq)
median = statistics.median(seq)
mode = statistics.mode(seq)
Output
Generated Numbers:
0.47950245404109626 0.6908539320958872 0.12445888663826654 0.13613724999684718
0.37709141355821396 0.6369609321575742
Mean = 0.40750081141464756
Median = 0.4282969337996551
Mode = 0.47950245404109626
Question 17
Write a program to find a side of a right angled triangle whose two sides and an angle is given.
Solution
import math
c = math.sqrt(a ** 2 + b ** 2)
print("Hypotenuse =", c)
Output
Enter base: 10.5
Enter height: 5.5
Enter angle: 60
Hypotenuse = 11.853269591129697
Question 18
Write a program to calculate the radius of a sphere whose area (4πr 2) is given.
Solution
import math
r = math.sqrt(area / (4 * math.pi))
Output
Enter area of sphere: 380.14
Radius of sphere = 5.50005273006328
Question 19
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
Solution
str = input("Enter string: ")
len = len(str)
opStr = str * len
print("Result", opStr)
Output
Enter string: eka
Result ekaekaeka
Question 20
Find the volume of the cylinder (πr2h) as shown:
Radius = 8 cm
Height = 15 cm
Solution
import math
r=8
h = 15
v = math.pi * r * r * h
print("Volume of Cylinder =", v)
Output
Volume of Cylinder = 3015.928947446201
Question 21
Write a program to calculate the area of an equilateral triangle. (area = (√3 / 4) * side * side).
Solution
import math
Output
Enter side: 5
Area of triangle = 10.825317547305481
Question 22
Write a program to input the radius of a sphere and calculate its volume (V = 4/3πr 3)
Solution
import math
Output
Enter radius of sphere: 3.5
Volume of sphere = 179.59438003021648
Question 23
Write a program to calculate amount payable after simple interest.
Solution
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)
Output
Enter principal: 55000.75
Enter rate: 14.5
Enter time: 3
Amount Payable = 78926.07625
Question 24
Write a program to calculate amount payable after compound interest.
Solution
p = float(input("Enter principal: "))
r = float(input("Enter rate: "))
t = float(input("Enter time: "))
amt = p * (1 + r / 100) ** t
Output
Enter principal: 15217.75
Enter rate: 9.2
Enter time: 3
Amount Payable = 19816.107987312007
Question 25
Write a program to compute (a + b)3 using the formula a3 + b3 + 3a2b + 3ab2
Solution
a = int(input("Enter a: "))
b = int(input("Enter b: "))
res = a ** 3 + b ** 3 + 3 * a ** 2 * b + 3 * a * b ** 2
Output
Enter a: 3
Enter b: 5
Result = 512
********
CHAPTER 7 : PYTHON FUNDAMENTALS
Type A : Short Answer Questions/Conceptual Questions
Question 1
What are tokens in Python ? How many types of tokens are allowed in Python ? Examplify your
answer.
Answer
The smallest individual unit in a program is known as a Token. Python has following tokens:
Question 2
Answer
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.
Question 3
What are literals in Python ? How many types of literals are allowed in Python ?
Answer
Literals are data items that have a fixed value. The different types of literals allowed in Python
are:
1. String literals
2. Numeric literals
3. Boolean literals
4. Special literal None
5. Literal collections
Question 4
Can nongraphic characters be used in Python ? How ? Give examples to support your answer.
Answer
Yes, nongraphic characters can be used in Python with the help of escape sequences. For
example, backspace is represented as \b, tab is represented as \t, carriage return is represented as
\r.
Question 5
How are floating constants represented in Python ? Give examples to support your answer.
Answer
Floating constants are represented in Python in two forms — Fractional Form and Exponent
form. Examples:
Question 6
Answer
Question 7
Which of these is not a legal numeric type in Python ? (a) int (b) float (c) decimal.
Answer
Question 8
Answer
(i) sep (ii) end
Question 9
What are operators ? What is their function ? Give examples of some unary and binary operators.
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 (/).
Question 10
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
Question 11
Question 12
Answer
A block/code block/suite is a group of statements that are part of another statement. For example:
if b > 5:
print("Value of 'b' is less than 5.")
print("Thank you.")
Question 13
Question 14
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.
Question 15
In Python, a variable is not created until some value is assigned to it. A variable is created
when a value is assigned to it for the first time. If we try to use a variable before assigning a
value to it then it will result in an undefined variable. For example:
Question 16
x = 10
print(x)
x = "Hello World"
print(x)
Question 17
Question 18
What is the error in following code : X, Y = 7 ?
The error in the above code is that we have mentioned two variables X, Y as Lvalues but
only give a single numeric literal 7 as the Rvalue. We need to specify one more value like this to
correct the error:
X, Y = 7, 8
Question 19
Python doesn't allow decimal numbers to have leading zeros. That is the reason why this
line is creating problem.
Question 20
"Comments are useful and easy way to enhance readability and understandability of a program."
Elaborate with examples.
Comments can be used to explain the purpose of the program, document the logic of a
piece of code, describe the behaviour of a program, etc. This enhances the readability and
understandability of a program. For example:
Question 1
From the following, find out which assignment statement will produce an error. State reason(s)
too.
(a) x = 55
(b) y = 037
(c) z = 0o98
(d) 56thnumber = 3300
(e) length = 450.17
(f) !Taylor = 'Instant'
(g) this variable = 87.E02
(h) float = .17E - 03
(i) FLOAT = 0.17E - 03
Answer
1. y = 037 (option b) will give an error as decimal integer literal cannot start with a 0.
2. z = 0o98 (option c) will give an error as 0o98 is an octal integer literal due to the 0o
prefix and 8 & 9 are invalid digits in an octal number.
3. 56thnumber = 3300 (option d) will give an error as 56thnumber is an invalid identifier
because it starts with a digit.
4. !Taylor = 'Instant' (option f) will give an error as !Taylor is an invalid identifier because
it contains the special character !.
5. this variable = 87.E02 (option g) will give an error due to the space present between this
and variable. Identifiers cannot contain any space.
6. float = .17E - 03 (option h) will give an error due to the spaces present in exponent part
(E - 03). A very important point to note here is that float is NOT a KEYWORD in
Python. The statement float = .17E-03 will execute successfully without any errors in
Python.
7. FLOAT = 0.17E - 03 (option i) will give an error due to the spaces present in exponent
part (E - 03).
Question 2
(i) 20 + 30 * 40
Answer
20 + 30 * 40
⇒ 20 + 1200
⇒ 1220
(ii) 20 - 30 + 40
Answer
20 - 30 + 40
⇒ -10 + 40
⇒ 30
Answer
(20 + 30) * 40
⇒ 50 * 40
⇒ 2000
Answer
15.0 / 4 + (8 + 3.0)
⇒ 15.0 / 4 + 11.0
⇒ 3.75 + 11.0
⇒ 14.75
Question 3
(i)
temperature = 90
print temperature
Answer
The call to print function is missing parenthesis. The correct way to call print function is this:
print(temperature)
(ii)
a = 30
b=a+b
print (a And b)
Answer
(iii)
a, b, c = 2, 8, 9
print (a, b, c)
c, b, a = a, b, c
print (a ; b ; c)
Answer
In the statement print (a ; b ; c) use of semicolon will give error. In place of semicolon, we must
use comma like this print (a, b, c)
(iv)
X = 24
4=X
Answer
print("X ="X)
Answer
1. Variable X is undefined
2. "X =" and X should be separated by a comma like this print("X =", X)
(vi)
else = 21 - 5
Answer
Question 4
(i)
X = 10
X = X + 10
X=X-5
print (X)
X, Y = X - 2, 22
print (X, Y)
Output
15
13 22
Explanation
(ii)
first = 2
second = 3
third = first * second
print (first, second, third)
first = first + second + third
third = second * first
print (first, second, third)
Output
236
11 3 33
Explanation
(iii)
side7
7 49
Explanation
1. side = int(input('side') ) ⇒ This statements asks the user to enter the side. We enter 7 as
the value of side.
2. area = side * side ⇒ area = 7 * 7 = 49.
3. print (side, area) ⇒ prints the value of side and area as 7 and 49 respectively.
Question 5
(i)
a=3
print(a)
b=4
print(b)
s=a+b
print(s)
Answer
name = "Prejith"
age = 26
print ("Your name & age are ", name + age)
Answer
In the print statement we are trying to add name which is a string to age which is an integer. This
is an invalid operation in Python.
(iii)
a=3
s = a + 10
a = "New"
q = a / 10
Answer
The statement a = "New" converts a to string type from numeric type due to dynamic typing. The
statement q = a / 10 is trying to divide a string with a number which is an invalid operation in
Python.
Question 6
Predict the output:
(a)
x = 40
y=x+1
x = 20, y + x
print (x, y)
Output
(20, 81) 41
Explanation
(b)
x, y = 20, 60
y, x, y = x, y - 10, x + 10
print (x, y)
Output
50 30
Explanation
(c)
a, b = 12, 13
c, b = a*2, a/2
print (a, b, c)
Output
12 6.0 24
Explanation
(d)
a, b = 12, 13
print (print(a + b))
Output
25
None
Explanation
Question 7
a, b, c = 10, 20, 30
p, q, r = c - 5, a + 3, b - 4
print ('a, b, c :', a, b, c, end = '')
print ('p, q, r :', p, q, r)
Output
a, b, c : 10 20 30p, q, r : 25 13 16
Explanation
(a)
y=x+5
print (x, Y)
Answer
(b)
print (x = y = 5)
Answer
Python doesn't allow assignment of variables while they are getting printed.
(c)
a = input("value")
b = a/2
print (a, b)
Answer
The input( ) function always returns a value of String type so variable a is a string. This
statement b = a/2 is trying to divide a string with an integer which is invalid operation in Python.
Question 9
Find the errors in following code fragment : (The input entered is XI)
Question 10
Consider the following code :
Hi <name>,
How are you doing?
What could be the problem ? Can you suggest the solution for the same ?
Answer
The print() function appends a newline character at the end of the line unless we give our own
end argument. Due to this behaviour of print() function, the statement print ('Hi', name, ',1) is
printing a newline at the end. Hence "How are you doing?" is getting printed on the next line.
To fix this we can add the end argument to the first print() function like this:
print ('Hi', name, ',1, end = '')
Question 11
Question 12
Answer
<class 'int'>
Answer
<class 'int'>
(c) >>>.type(int('0')
Answer
Answer
<class 'str'>
Answer
<class 'float'>
Answer
<class 'int'>
(g) >>>type(float(0))
Answer
<class 'float'>
Answer
<class 'float'>
<class 'float'>
Question 13
Output
'NoneOne'
Explanation
print() function doesn't return any value so its return value is None.
Hence, str(print()) becomes str(None). str(None) converts None into string 'None' and addition
operator joins 'None' and 'One' to give the final output as 'NoneOne'.
(b) >>> str(print("hello"))+"One"
Output
hello 'NoneOne'
Explanation
First, print("hello") function is executed which prints the first line of the output as hello. The
return value of print() function is None i.e. nothing. str() function converts it into string and
addition operator joins 'None' and 'One' to give the second line of the output as 'NoneOne'.
Output
Hola None
Explanation
First, print("Hola") function is executed which prints the first line of the output as Hola. The
return value of print() function is None i.e. nothing. This is passed as argument to the outer print
function which converts it into string and prints the second line of output as None.
Output
HolaNone
Explanation
First, print ("Hola", end = "") function is executed which prints Hola. As end argument is
specified as "" so newline is not printed after Hola. The next output starts from the same line.
The return value of print() function is None i.e. nothing. This is passed as argument to the outer
print function which converts it into string and prints None in the same line after Hola.
Question 14
Carefully look at the following code and its execution on Python shell. Why is the last
assignment giving error ?
>>> a = 0o12
>>> print(a)
10
>>> b = 0o13
>>> c = 0o78
File "<python-input-41-27fbe2fd265f>", line 1
c = 0o78
^
SyntaxError : invalid syntax
Answer
Due to the prefix 0o, the number is treated as an octal number by Python but digit 8 is invalid in
Octal number system hence we are getting this error.
Question 15
a, b, c = 2, 3, 4
a, b, c = a*a, a*b, a*c
print(a, b, c)
Output
468
Explanation
Question 16
The id( ) can be used to get the memory address of a variable. Consider the adjacent code and tell
if the id( ) functions will return the same value or not(as the value to be printed via print() ) ?
Why ?
[There are four print() function statements that are printing id of variable num in the code shown
on the right.
num = 13
print( id(num) )
num = num + 3
print( id(num) )
num = num - 3
print( id(num) )
num = "Hello"
print( id(num) )
Answer
num = 13
print( id(num) ) # print 1
num = num + 3
print( id(num) ) # print 2
num = num - 3
print( id(num) ) # print 3
num = "Hello"
print( id(num) ) # print 4
For the print statements commented as print 1 and print 3 above, the id() function will return the
same value. For print 2 and print 4, the value returned by id() function will be different.
The reason is that for both print 1 and print 3 statements the value of num is the same which is
13. So id(num) gives the address of the memory location which contains 13 in the front-loaded
dataspace.
Question 17
Consider below given two sets of codes, which are nearly identical, along with their execution in
Python shell. Notice that first code-fragment after taking input gives error, while second code-
fragment does not produce error. Can you tell why ?
(a)
>>> print(float(input("valuel:")) )
value1:67
67.0
Answer
In part a, the value entered by the user is converted to a float type and passed to the print
function by assigning it to a variable named num. It means that we are passing an argument
named num to the print function. But print function doesn't accept any argument named num.
Hence, we get this error telling us that num is an invalid argument for print function.
In part b, we are converting the value entered by the user to a float type and directly passing it to
the print function. Hence, it works correctly and the value gets printed.
Question 18
Output
Input days : 1
Input hours: 2
Input minutes: 3
Input seconds: 4
Total number of seconds 93784
Question 19
n1, n2 = 5, 7
n3 = n1 + n2
n4 = n4 + 2
print(n1, n2, n3, n4)
Answer
The code will result into an error as in the statement n4 = n4 + 2, variable n4 is undefined.
Question 20
Correct the following program so that it displays 33 when 30 is input.
val = int(input("Enter a value")) #used int() to convert input value into integer
nval = val + 3 #changed 30 to 3
print(nval)
Type C : Programming Practice/Knowledge based Questions
Question 1
Write a program that displays a joke. But display the punchline only when the user presses enter
key.
(Hint. You may use input( ))
Solution
Output
Why is 6 afraid of 7?
Press Enter
Because 7 8(ate) 9 :-)
Question 2
Write a program to read today's date (only del part) from user. Then display how many days are
left in the current month.
Solution
Question 3
Solution
a=5
print(a)
a=a*2
print(a)
a=a-1
print(a)
Output
5
10
9
Question 4
Solution
a=5
print(a, end='@')
a=a*2
print(a, end='@')
a=a-1
print(a)
Output
5@10@9
Question 5
Write the program with maximum three lines of code and that assigns first 5 multiples of a
number to 5 variables and then print them.
Solution
Output
Enter a number: 2
2 4 6 8 10
Question 6
Write a Python program that accepts radius of a circle and prints its area.
Solution
r = float(input("Enter radius of circle: "))
a = 3.14159 * r * r
print("Area of circle =", a)
Output
Question 7
Write Python program that accepts marks in 5 subjects and outputs average marks.
Solution
Question 8
Write a short program that asks for your height in centimetres and then converts your height to
feet and inches. (1 foot = 12 inches, 1 inch = 2.54 cm).
Solution
Question 9
Solution
n = int(input("Enter n: "))
n2, n3, n4 = n ** 2, n ** 3, n ** 4
print("n =", n)
print("n^2 =", n2)
print("n^3 =", n3)
print("n^4 =", n4)
Output
Enter n: 2
n=2
n^2 = 4
n^3 = 8
n^4 = 16
Question 10
Question 11
Solution
p = float(input("Enter principal: "))
r = float(input("Enter rate: "))
t = int(input("Enter time: "))
si = (p * r * t) / 100
ci = p * ((1 + (r / 100 ))** t) - p
print("Simple interest = ", si)
print("Compound interest = ", ci)
Output
Question 12
Write a program to input a number and print its first five multiples.
Solution
Output
Enter number: 5
First five multiples of 5 are
5 10 15 20 25
Question 13
Write a program to read details like name, class, age of a student and then print the details firstly
in same line and then in separate lines. Make sure to have two blank lines in these two different
types of prints.
Solution
Name: Kavya
Class: 11
Age: 17
Question 14
Write a program to input a single digit(n) and print a 3 digit number created as <n(n + 1)(n + 2)>
e.g., if you input 7, then it should print 789. Assume that the input digit is in range 1-7.
Solution
Output
Question 15
Write a program to read three numbers in three variables and swap first two variables with the
sums of first and second, second and third numbers respectively.
Solution
Output