Chapter Python Fundamentals
Multiple Choice Questions
Q1. Special meaning words of Pythons, fixed for specific functionality are called .......... .
a. Identifiers b. functions c. Keywords ✓ d. literals
Q2. Names given to different parts of a Python program are .......... .
a. Identifiers ✓ b. functions c. Keywords d. literals
Q3. Data items having fixed value are called .......... .
a. Identifiers b. functions c. Keywords d. literals ✓
Q4. Which of the following is/are correct ways of creating strings ?
a. name = Jiya c. name = 'Jiya' ✓
b. name = "Jiya" ✓ d. name = (Jiya)
Q5. Which of the following are keyword(s) ?
a. name b. Print c. print ✓ d. input ✓
Q6. Which of the following are valid identifiers ?
a. my name b. _myname ✓ c. myname ✓ d. my-name
Q7. Which of the following are literals ?
a. myname b. "Radha" ✓ c. 24.5 ✓ d. 24A
Q8. Escape sequences are treated as .......... .
a. strings b. characters ✓ c. integers d. none of these
Q9 Which of the following is an escape sequence for a tab character ?
a. \a b. \t ✓ c. \n d. \b
Q10. Which of the following is an escape sequence for a newline character ?
a. \a b. \t c. \n ✓ d. \b
Q11. Which of the following is not a legal integer type value in Python ?
a. Decimal b. Octal c. Hexadecimal d. Roman ✓
Q12. Which of the following symbols are not legal in an octal value ?
a. 7 b. 8 ✓ c. 9 ✓ d.
0
Q13. Value 17.25 is equivalent to
a. 0.1725E-2 b. 0.1725E+2 ✓ c. 1725E2 d. 0.1725E2 ✓
Q14. Value 0.000615 is equivalent to
a. 615E3 b. 615E-3 c. 0.615E3 d. 0.615E-3 ✓
Q15. Which of the following is/are expression(s) ?
a. a+b-5 ✓ b. a c. -5 d. b-5 ✓
Q16. The lines beginning with a certain character, and which are ignored by a compiler and not executed,
are called ..........
a. operators b. operands c. functions d. comments ✓
Q17. Which of the following can be used to create comments ?
a. // b. # ✓ c. ''' d. ''' . . . ''' ✓
Q18. Which of the following functions print the output to the console ?
a. Output( ) b. Print( ) c. Echo( ) d. print( ) ✓
Q19. Select the reserved keyword in Python.
a. Else b. import c. print d. all of these ✓
Q20. The input( ) returns the value as .......... type.
a. Integer b. string ✓ c. floating point d. none of these
Q21. To convert the read value through input( ) into integer type, ..........( ) is used.
a. floating b. float c. int ✓ d. integer
Q22. To convert the read value through input( ) into a floating point number, ..........( ) is used.
a. Floating b. float ✓ c. int d. integer
Q23. To print a line a text without ending it with a newline, .......... argument is used with print( )
a. sep b. newline c. end ✓ d. next
Q24. The default separator character of print( ) is ..........
a. tab b. space ✓ c. newline d. dot
Q25. To give a different separator with print( ) .......... argument is used.
1. sep ✓ b. separator c. end d. tab
Fill in the Blanks
Q1. A keyword is a reserved word carrying special meaning and purpose.
Q2. Identifiers are the user defined names for different parts of a program.
Q3. Literals are the fixed values.
Q4. Operators are the symbols that trigger some computation or action.
Q5. An expression is a legal combination of symbols that represents a value.
Q6. Non-executable, additional lines added to a program, are known as comments.
Q7. In Python, the comments begin with # character.
Q8. Python is a case sensitive language.
Q9. The print( ) function prints the value of a variable/expression.
Q10. The input( ) function gets the input from the user.
Q11. The input( ) function returns the read value as of string type.
Q12. To convert an input( )'s value in integer type, int( ) function is used.
Q13. To convert an input( )'s value in floating-point type, float( ) function is used.
Q14. Strings can be created with single quotes, double quotes and triple quotes.
True/False Questions
Q1. Keywords can be used as identifier names. False
Q2. The identifiers in Python can begin with an underscore. True
Q3. 0128 is a legal literal value in Python. False
Q4. 0x12EFG is a legal literal value in Python. False
Q5. 0123 is a legal literal value in Python. True
Q6. Variables once assigned a value can be given any other value. True
Q7. Variables are created when they are first assigned their value. True
Q8. Python variables support dynamic typing. True
Q9. You can rename a keyword. False
Q10. String values in Python can be single line strings, and multi-line strings. True
Q11. A variable can contain values of different types at different times. True
Q12. Expressions contain values/variables along with operators. True
Type A : Short Answer Questions/Conceptual Questions
Q1. 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:
1. Keywords — Examples are import, for, in, while, etc.
2. Identifiers — Examples are MyFile, _DS, DATE_9_7_77, etc.
3. Literals — Examples are "abc", 5, 28.5, etc.
4. Operators — Examples are +, -, >, or, etc.
5. Punctuators — ' " # () etc.
Q2. How are keywords different from identifiers ?
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.
Q3. 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 [Link] literals
2. Boolean literals [Link] literal None
3. Literal collections
Q4. 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.
Q5. 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:
1. Fractional Form — 2.0, 17.5, -13.0, -0.00625
2. Exponent form — 152E05, 1.52E07, 0.152E08, -0.172E-3
Q6. How are string-literals represented and implemented in Python ?
Answer A string-literal is represented as a sequence of characters surrounded by quotes (single,
double or triple quotes). String-literals in Python are implemented using Unicode.
Q7. Which of these is not a legal numeric type in Python ? (a) int (b) float (c) decimal.
Answer decimal is not a legal numeric type in Python.
Q8 Which argument of print( ) would you set for:
(i) changing the default separator (space) ?
(ii) printing the following line in current line ?
Answer (i) sep (ii) end
Q9 What are operators ? What is their function ? Give examples of some unary and binary operators.
Answer 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 (/).
Q10 What is an expression and a statement ?
Answer 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
Q11 What all components can a Python program contain ?
Answer A Python program can contain various components like expressions, statements, comments,
functions, blocks and indentation.
Q12 What do you understand by block/code block/suite in Python ?
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.")
Q13 What is the role of indentation in Python ?
Answer Python uses indentation to create blocks of code. Statements at same indentation level are
part of same block/suite.
Q14 What are variables ? How are they important for a program ?
Answer 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.
Q15 What do you understand by undefined variable in Python ?
Answer 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:
print(x) #This statement will cause an error for undefined variable x
x = 20
print(x)
The first line of the above code snippet will cause an undefined variable error as we are
trying to use x before assigning a value to it.
Q16 What is Dynamic Typing feature of Python ?
Answer A variable pointing to a value of a certain type can be made to point to a value/object of
different [Link] is called Dynamic Typing. For example:
x = 10
print(x)
x = "Hello World"
print(x)
Q17 What would the following code do : X = Y = 7 ?
Answer It will assign a value of 7 to the variables X and Y.
Q18 What is the error in following code : X, Y = 7 ?
Answer 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
Q19 Following variable definition is creating problem X = 0281, find reasons.
Answer Python doesn't allow decimal numbers to have leading zeros. That is the reason why this line
is creating problem.
Q20 "Comments are useful and easy way to enhance readability and understandability of a program."
Elaborate with examples.
Answer 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:
# This program shows a program's components
# Definition of function SeeYou() follows
def SeeYou():
print("Time to say Good Bye!!")
# Main program-code follows now
a = 15
b = a - 10
print (a + 3)
if b > 5: # colon means it's a block
print("Value of 'a' was more than 15 initially.")
else:
print("Value of 'a' was 15 or less initially.")
SeeYou() # calling above defined function SeeYou()
Type B: Application Based Questions
Q1 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
Ans
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).
Q2 How will Python evaluate the following expression ?
(i) 20 + 30 * 40 Answer
⇒ 20 + 1200
20 + 30 * 40
⇒ 1220
(ii) 20 - 30 + 40 Answer
⇒ -10 + 40
20 - 30 + 40
⇒ 30
(iii) (20 + 30) * 40 Answer
⇒ 50 * 40
(20 + 30) * 40
⇒ 2000
(iv) 15.0 / 4 + (8 + 3.0) Answer
⇒ 15.0 / 4 + 11.0
15.0 / 4 + (8 + 3.0)
⇒ 3.75 + 11.0
⇒ 14.75
Q3 Find out the error(s) in following code fragments:
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 There are two errors in this code fragment:
1. In the statement b=a+b variable b is undefined.
2. In the statement print (a And b), And should be written as and.
(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 The statement 4 = X is incorrect as 4 cannot be a Lvalue. It is a Rvalue.
(v) print("X ="X)
Answer There are two errors in this code fragment:
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 else is a keyword in Python so it can't be used as a variable name.
Q4 What will be the output produced by following code fragment (s) ?
i. X = 10
X = X + 10
X=X-5
print (X)
X, Y = X - 2, 22
print (X, Y)
Output 15
13 22
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
(iii) side = int(input('side') ) #side given as 7
area = side * side
print (side, area)
Output side7
7 49
Q5 What is the problem with the following code fragments ?
a=3
print(a)
b=4
print(b)
s=a+b
print(s)
Answer The problem with the above code is inconsistent indentation.
The statements print(a), print(b), print(s) are indented but they are not inside a suite. In
Python, we cannot indent a statement unless it is inside a suite and we can indent only as
much is required.
(ii) 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.
Q6 Predict the output:
a) x = 40
y=x+1
x = 20, y + x
print (x, y)
Output
(20, 81) 41
(b) x, y = 20, 60
y, x, y = x, y - 10, x + 10
print (x, y)
Output
50 30
(c) a, b = 12, 13
c, b = a*2, a/2
print (a, b, c)
Output
12 6.0 24
(d) a, b = 12, 13
print (print(a + b))
Output
25
None
Q7 Predict the output
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
Q8 Find the errors in following code fragment
(a) y = x + 5
print (x, Y)
Answer There are two errors in this code fragment:
1. x is undefined in the statement y = x + 5
2. Y is undefined in the statement print (x, Y). As Python is case-sensitive hence y and Y will be
treated as two different variables.
(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.
Q9 Find the errors in following code fragment : (The input entered is XI)
c = int (input ( "Enter your class") )
print ("Your class is", c)
Answer The input value XI is not int type compatible.
Q10 Consider the following code :
name = input ("What is your name?")
print ('Hi', name, ',')
print ("How are you doing?")
was intended to print output as
Hi <name>, How are you doing ?
But it is printing the output as :
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 = '')
Q11 Find the errors in following code fragment :
c = input( "Enter your class" )
print ("Last year you were in class") c - 1
Answer There are two errors in this code fragment:
1. c - 1 is outside the parenthesis of print function. It should be specified as one of the arguments
of print function.
2. c is a string as input function returns a string. With c - 1, we are trying to subtract a integer from
a string which is an invalid operation in Python.
The corrected program is like this:
c = int(input( "Enter your class" ))
print ("Last year you were in class", c - 1)
Q12 What will be returned by Python as result of following statements?
(a) >>> type(0) Answer <class 'int'>
b) >>> type(int(0)) Answer <class 'int'>
(c) >>>.type(int('0') Answer SyntaxError: invalid syntax
(d) >>> type('0') Answer <class 'str'>
(e) >>> type(1.0) Answer <class 'float'>
(f) >>> type(int(1.0)) Answer <class 'int'>
(g) >>>type(float(0)) Answer <class 'float'>
(h) >>> type(float(1.0)) Answer <class 'float'>
(i) >>> type( 3/2) Answer <class 'float'>
Q13 What will be the output produced by following code ?
(a) >>> str(print())+"One" Output NoneOne
(b) >>> str(print("hello"))+"One" Output hello
NoneOne
(c) >>> print(print("Hola")) Output Hola
None
(d) >>> print (print ("Hola", end = " ")) Output Hola None
Q14 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.
Q15 Predict the output
a, b, c = 2, 3, 4
a, b, c = a*a, a*b, a*c
print(a, b, c)
Output 468
Q16 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
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.
Q17 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(num = float(input("value1:")) )
value1:67
TypeError: 'num' is an invalid keyword argument for this function
(b) >>> 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.
Q18 Predict the output of the following code :
days = int (input ("Input days : ")) * 3600 * 24
hours = int(input("Input hours: ")) * 3600
minutes = int(input("Input minutes: ")) * 60
seconds = int(input("Input seconds: "))
time = days + hours + minutes + seconds
print("Total number of seconds", time)
If the input given is in this order : 1, 2, 3, 4
Output Input days : 1
Input hours: 2
Input minutes: 3
Input seconds: 4
Total number of seconds 93784
Q19 What will the following code result into ?
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.
Q20 Correct the following program so that it displays 33 when 30 is input.
val = input("Enter a value")
nval = val + 30
print(nval)
Answer Below is the corrected program:
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
Q1 Write a program that displays a joke. But display the punchline only when the user presses enter
key.
(Hint. You may use input( ))
Solution print("Why is 6 afraid of 7?")
input("Press Enter")
print("Because 7 8(ate) 9 :-)")
Q2 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 day = int(input("Enter day part of today's date: "))
totalDays = int(input("Enter total number of days in this month: "))
daysLeft = totalDays - day
print(daysLeft, "days are left in current month")
Q3 Write a program that generates the following output :
5
10
9
Assign value 5 to a variable using assignment operator (=) Multiply it with 2 to generate 10 and
subtract 1 to generate 9.
Solution a=5
print(a)
a=a*2
print(a)
a=a-1
print(a)
Q4 Modify above program so as to print output as 5@10@9.
Solution a=5
print(a, end='@')
a=a*2
print(a, end='@')
a=a-1
print(a)
Q5 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 a = int(input("Enter a number: "))
b, c, d, e = a * 2, a * 3, a * 4, a * 5
print(a, b, c, d, e)
Q6 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)
Q7 Write Python program that accepts marks in 5 subjects and outputs average marks.
Solution m1 = int(input("Enter first subject marks: "))
m2 = int(input("Enter second subject marks: "))
m3 = int(input("Enter third subject marks: "))
m4 = int(input("Enter fourth subject marks: "))
m5 = int(input("Enter fifth subject marks: "))
avg = (m1 + m2+ m3+ m4 + m5) / 5;
print("Average Marks =", avg)
Q8 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 ht = int(input("Enter your height in centimeters: "))
htInInch = ht / 2.54;
feet = htInInch // 12;
inch = htInInch % 12;
print("Your height is", feet, "feet and", inch, "inches")
Q9 Write a program to read a number n and print n2, n3 and n4.
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)
Q10 Write a program to find area of a triangle.
Solution h = float(input("Enter height of the triangle: "))
b = float(input("Enter base of the triangle: "))
area = 0.5 * b * h
print("Area of triangle = ", area)
Q11 Write a program to compute simple interest and compound interest.
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)
Q12 Write a program to input a number and print its first five multiples.
Solution n = int(input("Enter number: "))
print("First five multiples of", n, "are")
print(n, n * 2, n * 3, n * 4, n * 5)
Q13 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 n = input("Enter name of student: ")
c = int(input("Enter class of student: "))
a = int(input("Enter age of student: "))
print("Name:", n, "Class:", c, "Age:", a)
print()
print()
print("Name:", n)
print("Class:", c)
print("Age:", a)
Q14 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 d = int(input("Enter a digit in range 1-7: "))
n = d * 10 + d + 1
n = n * 10 + d + 2
print("3 digit number =", n)
Q15 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 a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))
print("The three number are", a, b, c)
a, b = a + b, b + c
print("Numbers after swapping are", a, b, c)