Download as pdf or txt
Download as pdf or txt
You are on page 1of 133

Question Bank

* MCQ Questions
1. Is Python case sensitive when dealing with identifiers?
a) yes
b) no
c) machine dependent
d) none of the mentioned
Answer: a
Explanation: Case is always significant.

2. What is the maximum possible length of an identifier?


a) 31 characters
b) 63 characters
c) 79 characters
d) none of the mentioned
Answer: d
Explanation: Identifiers can be of any length.

3. Which of the following is invalid?


a) _a = 1
b) __a = 1
c) __str__ = 1
d) none of the mentioned
Answer: d
Explanation: All the statements will execute successfully but at the cost of reduced
readability.

4. Which of the following is an invalid variable?


a) my_string_1
b) 1st_string
c) foo
d) _
Answer: b
Explanation: Variable names should not start with a number.

5. Why are local variable names beginning with an underscore discouraged?


a) they are used to indicate a private variables of a class
b) they confuse the interpreter
c) they are used to indicate global variables
d) they slow down execution
Answer: a
Explanation: As Python has no concept of private variables, leading underscores are
used to indicate variables that must not be accessed from outside the class.

6. Which of the following is not a keyword?


a) eval
b) assert
c) nonlocal
d) pass
Answer: a
Explanation: eval can be used as a variable.

7. All keywords in Python are in _________


a) lower case
b) UPPER CASE
c) Capitalized
d) None of the mentioned
Answer: d
Explanation: True, False and None are capitalized while the others are in lower case.

8. Which of the following is true for variable names in Python?


a) unlimited length
b) all private members must have leading and trailing underscores
c) underscore and ampersand are the only two special characters allowed
d) none of the mentioned
Answer: a
Explanation: Variable names can be of any length.

9. Which of the following is an invalid statement?


a) abc = 1,000,000
b) a b c = 1000 2000 3000
c) a,b,c = 1000, 2000, 3000
d) a_b_c = 1,000,000
Answer: b
Explanation: Spaces are not allowed in variable names.

10. Which of the following cannot be a variable?


a) __init__
b) in
c) it
d) on
Answer: b
Explanation: in is a keyword.

11. What is the output of print 0.1 + 0.2 == 0.3?


a) True
b) False
c) Machine dependent
d) Error
View Answer
Answer: b
Explanation: Neither of 0.1, 0.2 and 0.3 can be represented accurately in binary. The
round off errors from 0.1 and 0.2 accumulate and hence there is a difference of
5.5511e-17 between (0.1 + 0.2) and 0.3.

12. Which of the following is not a complex number?


a) k = 2 + 3j
b) k = complex(2, 3)
c) k = 2 + 3l
d) k = 2 + 3J
Answer: c
Explanation: l (or L) stands for long.

13. What is the type of inf?


a) Boolean
b) Integer
c) Float
d) Complex
Answer: c
Explanation: Infinity is a special case of floating point numbers. It can be obtained by
float(‘inf’).

14. What does ~4 evaluate to?


a) -5
b) -4
c) -3
d) +3
Answer: a
Explanation: ~x is equivalent to -(x+1).

15.What does ~~~~~~5 evaluate to?


a) +5
b) -11
c) +11
d) -5
Answer: a
Explanation: ~x is equivalent to -(x+1).

16.Which of the following is incorrect?


a) x = 0b101
b) x = 0x4f5
c) x = 19023
d) x = 03964
Answer: d
Explanation: Numbers starting with a 0 are octal numbers but 9 isn’t allowed in octal
numbers.
17. What is the result of cmp(3, 1)?
a) 1
b) 0
c) True
d) False
Answer: a
Explanation: cmp(x, y) returns 1 if x > y, 0 if x == y and -1 if x < y.

18. Which of the following is incorrect?


a) float(‘inf’)
b) float(‘nan’)
c) float(’56’+’78’)
d) float(’12+34′)
Answer: d
Explanation: ‘+’ cannot be converted to a float.
19. What is the result of round(0.5) – round(-0.5)?
a) 1.0
b) 2.0
c) 0.0
d) None of the mentioned
Answer: b
Explanation: Python rounds off numbers away from 0 when the number to be
rounded off is exactly halfway through. round(0.5) is 1 and round(-0.5) is -1.

20. What does 3 ^ 4 evaluate to?


a) 81
b) 12
c) 0.75
d) 7
Answer: d
Explanation: ^ is the Binary XOR operator.

21. Which of the following statements create a dictionary?


a) d = {}
b) d = {“john”:40, “peter”:45}
c) d = {40:”john”, 45:”peter”}
d) All of the mentioned
Answer: d
Explanation: Dictionaries are created by specifying keys and values.
22. What will be the output of the following Python code snippet?
d = {"john":40, "peter":45}
a) “john”, 40, 45, and “peter”
b) “john” and “peter”
c) 40 and 45
d) d = (40:”john”, 45:”peter”)
Answer: b
Explanation: Dictionaries appear in the form of keys and values.

23. What will be the output of the following Python code snippet?
d = {"john":40, "peter":45}
"john" in d

a) True
b) False
c) None
d) Error

Answer: a
Explanation: In can be used to check if the key is int dictionary.

24. What will be the output of the following Python code snippet?
d1 = {"john":40, "peter":45}
d2 = {"john":466, "peter":45}
d1 == d2

a) True
b) False
c) None
d) Error

Answer: b
Explanation: If d2 was initialized as d2 = d1 the answer would be true.

25. What will be the output of the following Python code snippet?
d1 = {"john":40, "peter":45}
d2 = {"john":466, "peter":45}
d1 > d2

a) True
b) False
c) Error
d) None
Answer: c
Explanation: Arithmetic > operator cannot be used with dictionaries.
26. Which of the following is a Python tuple?
a) [1, 2, 3]
b) (1, 2, 3)
c) {1, 2, 3}
d) {}
Answer: b
Explanation: Tuples are represented with round brackets.

27. Suppose t = (1, 2, 4, 3), which of the following is incorrect?


a) print(t[3])
b) t[3] = 45
c) print(max(t))
d) print(len(t))
Answer: b
Explanation: Values cannot be modified in the case of tuple, that is, tuple is
immutable.

28. What will be the output of the following Python code?


>>>t=(1,2,4,3)
>>>t[1:3]

a) (1, 2)
b) (1, 2, 4)
c) (2, 4)
d) (2, 4, 3)
Answer: c
Explanation: Slicing in tuples takes place just as it does in strings.

29. What will be the output of the following Python code?


>>>t=(1,2,4,3)
>>>t[1:-1]

a) (1, 2)
b) (1, 2, 4)
c) (2, 4)
d) (2, 4, 3)
Answer: c
Explanation: Slicing in tuples takes place just as it does in strings.

30. What will be the output of the following Python code?


>>>t = (1, 2, 4, 3, 8, 9)
>>>[t[i] for i in range(0, len(t), 2)]

a) [2, 3, 9]
b) [1, 2, 4, 3, 8, 9]
c) [1, 4, 8]
d) (1, 4, 8)
Answer: c
Explanation: Execute in the shell to verify.

31. What will be the output of the following Python code?


d = {"john":40, "peter":45}
d["john"]

a) 40
b) 45
c) “john”
d) “peter”
Answer: a
Explanation: Execute in the shell to verify.

32. What will be the output of the following Python code?


>>>t = (1, 2)
>>>2 * t

a) (1, 2, 1, 2)
b) [1, 2, 1, 2]
c) (1, 1, 2, 2)
d) [1, 1, 2, 2]
Answer: a
Explanation: * operator concatenates tuple.

33. Which of these about a set is not true?


a) Mutable data type
b) Allows duplicate values
c) Data type with unordered values
d) Immutable data type
Answer: d
Explanation: A set is a mutable data type with non-duplicate, unordered values,
providing the usual mathematical set operations.

34. Which of the following is not the correct syntax for creating a set?
a) set([[1,2],[3,4]])
b) set([1,2,2,3,4])
c) set((1,2,3,4))
d) {1,2,3,4}
Answer: a
Explanation: The argument given for the set must be an iterable.

35. What will be the output of the following Python code?


nums = set([1,1,2,3,3,3,4,4])print(len(nums))
a) 7
b) Error, invalid syntax for formation of set
c) 4
d) 8
Answer: c
Explanation: A set doesn’t have duplicate items.

36. What will be the output of the following Python code?


a = [5,5,6,7,7,7]
b = set(a)def test(lst):
if lst in b:
return 1
else:
return 0for i in filter(test, a):
print(i,end=" ")
a) 5 5 6
b) 5 6 7
c) 5 5 6 7 7 7
d) 5 6 7 7 7

37. Which of the following statements is used to create an empty set?


a) { }
b) set()
c) [ ]
d) ( )
Answer: b
Explanation: { } creates a dictionary not a set. Only set() creates an empty set.

38. What will be the output of the following Python code?


>>> a={5,4}>>> b={1,2,4,5}>>> a<b
a) {1,2}
b) True
c) False
d) Invalid operation
Answer: b
Explanation: a<b returns True if a is a proper subset of b.

39. If a={5,6,7,8}, which of the following statements is false?


a) print(len(a))
b) print(min(a))
c) a.remove(5)
d) a[2]=45
Answer: d
Explanation: The members of a set can be accessed by their index values since the
elements of the set are unordered.

40. If a={5,6,7}, what happens when a.add(5) is executed?


a) a={5,5,6,7}
b) a={5,6,7}
c) Error as there is no add function for set data type
d) Error as 5 already exists in the set
Answer: b
Explanation: There exists add method for set data type. However 5 isn’t added again
as set consists of only non-duplicate elements and 5 already exists in the set. Execute
in python shell to verify.

41. What will be the output of the following Python code?


>>> a={4,5,6}>>> b={2,8,6}>>> a+b
a) {4,5,6,2,8}
b) {4,5,6,2,8,6}
c) Error as unsupported operand type for sets
d) Error as the duplicate item 6 is present in both sets
Answer: c
Explanation: Execute in python shell to verify.

*Answer In One Sentence :

1. What is name space in Python?


2. What are local variables and global variables in Python?
3. Is python case sensitive?
4. What is type conversion in Python?
5. Is indentation required in python?
6. What is the difference between Python Arrays and lists?
7. What is a lambda function?
8. What is self in Python?
9. How does break, continue and pass work?
10. How can you randomize the items of a list in place in Python?
11. What are python iterators?
12. How do you write comments in python?
13. What is pickling and unpickling?
14. How will you convert a string to all lowercase?
15. How will you capitalize the first letter of string?
16. How to comment multiple lines in python?
17. What are docstrings in Python?
18. What is the purpose of is, not and in operators?
19. What is a dictionary in Python?
20. What does len() do?
21. Explain split(), sub(), subn() methods of “re” module in Python.
22. What are Python packages?
23. Does Python have OOps concepts?
24. How to import modules in python?
25. How are classes created in Python?
26. What is Polymorphism in Python?
27. Define encapsulation in Python?
28. How do you do data abstraction in Python?
29. Does python make use of access specifiers?
30. How to create an empty class in Python?

* Short Notes Questions :

1. Mention five benefits of using Python?


2. Explain what is Flask & its benefits?
3. Explain the key features of Python?
4. What are the global and local variables in Python?
5. Define modules in Python?
6. Define pickling and unpickling in Python?
7. Write a program to display Fibonacci sequence in Python?
8. Write a program to check whether the given number is prime or not?
9. What is the difference between range and xrange?
10. Does multiple inheritance is supported in Python?
11. Does Python make use of access specifiers?
12. Define Constructor in Python?
13. How can we create a constructor in Python programming?
14. How Does Python Handle Memory Management?
15. What Are The Optional Statements Possible Inside A Try-Except Block
In Python?
16. What Is Slicing In Python?
17. What Is %S In Python?
18. What Is The Index In Python?
19. Is A String Immutable Or Mutable In Python?
20. How Many Basic Types Of Functions Are Available In Python?

* Short Answer Questions :

1. How Do We Write A Function In Python?


2. What Is “Call By Value” In Python?
3. What Is “Call By Reference” In Python?
4. Is It Mandatory For A Python Function To Return A Value?Comment?
5. What Does The *Args Do In Python?
6. What Does The **Kwargs Do In Python?
7. Does Python Have A Main() Method?
8. What Is The Purpose Of “End” In Python?
9. When Should You Use The “Break” In Python?
10. What Is The Difference Between Pass And Continue In Python?
11. What Does The Ord() Function Do In Python?
12. What Is Rstrip() In Python?
13. How Is Python Thread Safe?
14. How Does Python Manage The Memory?
15. What Is A Tuple In Python?
16. Is Python List A Linked List?
17. What Is Class In Python?
18. What Are Attributes And Methods In A Python Class?
19. How To Assign Values For The Class Attributes At Runtime?
20. What Is Inheritance In Python Programming?

* Long Answer Questions :

1. What is the difference between lists and tuples?


2. Explain Inheritance in Python with an example.
3. What is a dictionary in Python?
4. What are negative indexes and why are they used?
5. What are split(), sub(), and subn() methods in Python?
6. How are range and xrange different from one another?
7. Explain all file processing modes supported in Python.
8. How are Python arrays and Python lists different from each other?
9. Explain List and Queues with example?
10. Explain All OOPS Concept With example?
Department of Computer Engineering

*Important*

22616 PWP MCQ (Programming With Python)

6th Sem all subject MCQs: click here


Download pdfs: click here

22616 PWP MCQ (Important MCQ for Summer 2021 Exam) Download pdf of 22616 PWP MCQ, The
following 101,102 pdf are important for the Exam so keep that in your head. Please go through all the
MCQ. Below pdf is released by cwipedia and the credits go to a different entity.
 

Topic Wise Python Multiple Choice Questions & Answers (MCQs)

“Variable Names” 

1. Is Python case sensitive when dealing with identifiers?


a) yes
 b) no

c) machine dependent
d) none of the mentioned
View Answer
Answer: a
Explanation: Case is always significant.
2. What is the maximum possible length of an identifier?
a) 31 characters
 b) 63 characters
c) 79 characters
d) none of the mentioned
View Answer
Answer: d
Explanation: Identifiers can be of any length.
3. Which of the following is invalid?
a) _a = 1
 b) __a = 1
c) __str__ = 1
d) none of the mentioned
View Answer
Answer: d
Explanation: All the statements will execute successfully but at the cost of reduced readability.

4. Which of the following is an invalid variable?


a) my_string_1
 b) 1st_string
c) foo
d) _
View Answer
Answer: b
Explanation: Variable names should not start with a number.

5. Why are local variable names beginning with an underscore discouraged?


a) they are used to indicate a private variables of a class
 b) they confuse the interpreter

c) they are used to indicate global variables


 

d) they slow down execution


View Answer
Answer: a
Explanation: As Python has no concept of private variables, leading underscores are used to indicate variables that
must not be accessed from outside the class.
6. Which of the following is not a keyword?

a) eval
 b) assert
c) nonlocal
d) pass
View Answer
Answer: a
Explanation: eval can be used as a variable.
7. All keywords in Python are in
a) lower case
 b) UPPER CASE
c) Capitalized
d) None of the mentioned
View Answer
Answer: d
Explanation: True, False and None are capitalized while the others are in lower case.
8. Which of the following is true for variable names in Python?
a) unlimited length
 b) all private members must have leading and trailing underscore s
c) underscore and ampersand are the only two special characters allowed
d) none of the mentioned
View Answer
Answer: a
Explanation: Variable names can be of any length.
9. Which of the following is an invalid statement?
a) abc = 1,000,000
 b) a b c = 1000 2000 3000
c) a,b,c = 1000, 2000, 3000
d) a_b_c = 1,000,000
View Answer
Answer: b
Explanation: Spaces are not allowed in variable names.

10. Which of the following cannot be a variable?

a) __init__
 

 b) in
c) it
d) on
View Answer
Answer: b
Explanation: in is a keyword.

Basic Operators

1. Which is the correct operator for power(x y)?


a) X^y
 b) X**y
c) X^^y
d) None of the mentioned
View Answer
Answer: b
Explanation: In python, power operator is x**y i.e. 2**3=8.
2. Which one of these is floor division?
a) /
 b) //
c) %
d) None of the mentioned
View Answer
Answer: b
Explanation: When both of the operands are integer then python chops out the fraction part and gives you the round
off value, to get the accurate answer use floor division. This is floor division. For ex, 5/2 = 2.5 but both of the
operands are integer so answer of this expression in python is 2.To get the 2.5 answer, use floor division.
3. What is the order of precedence in python?
i) Parentheses

ii) Exponential
iii) Multiplication
iv) Division
v) Addition
vi) Subtraction
a) i,ii,iii,iv,v,vi
 b) ii,i,iii,iv,v,vi
ii,i,iii,i v,v,vi
c) ii,i,iv,iii,v,vi
d) i,ii,iii,iv,vi,v
View Answer
Answer: a
Explanation: For order of precedence, just remember this PEMDAS (similar to BODMAS)
 

4. What is the answer to this expression, 22 % 3 is?


a) 7
 b) 1
c) 0
d) 5

View Answer
Answer: b
Explanation: Modulus operator gives the remainder. So, 22%3 gives the remainder, that is, 1.

5. Mathematical operations can be performed on a string. State whether true or false.


a) True
 b) False
View Answer
Answer: b
Explanation: You can’t perform mathematical operation on string even if the string is in the form: ‘1234…’.  

6. Operators with the same precedence are evaluated in which manner?


a) Left to Right

 b) Right to Left


c) Can’t say 
say  
d) None of the mentioned
View Answer
Answer: a
Explanation: None.
7. What is the output of this expression, 3*1**3?
a) 27
 b) 9
c) 3
d) 1
View Answer
Answer: c
Explanation: First this expression will solve 1**3 because exponential has higher precedence than multiplication, so
1**3 = 1 and 3*1 = 3. Final answer is 3.
8. Which one of the following has the same precedence level?
a) Addition and Subtraction
 b) Multiplication, Division and Addition
c) Multiplication, Division, Addition and Subtraction
d) Addition and Multiplication
View Answer
Answer: a

Explanation: “Addition and Subtraction” are at the same precedence level. Similarly, “Multiplication and Division”
 

are at the same precedence level. However, Multiplication and Division operators are at a higher precedence level
than Addition and Subtraction operators.
9. The expression Int(x) implies that the variable x is converted to integer. State whether true or false.
a) True
 b) False
View Answer
Answer: a
Explanation: None.
10. Which one of the following has the highest precedence in the expression?
a) Exponential
 b) Addition
c) Multiplication
d) Parentheses
View Answer
Answer: d
Explanation: Just remember: PEMDAS, that is, Parenthesis, Exponentiation, Division, Multiplication, Addition,
Subtraction. Note that the precedence order of Division and Multiplication is the same. Likewise, the order of
Addition and Subtraction is also the same.

Data Types

1. Which of these in not a core data type?


a) Lists
 b) Dictionary
c) Tuples
d) Class
View Answer
Answer: d
Explanation: Class is a user defined data type.
2. Given a function that does not return any value, What value is thrown by default when executed in shell.
a) int
 b) bool
c) void
d) None
View Answer
Answer: d
Explanation: Python shell throws a NoneType object back.
3. Following set of commands are executed in shell, what will be the output?
1.  >>>str="hello"
2.  >>>str[:2]
3.  >>>
 

a) he
 b) lo
c) olleh
d) hello
View Answer
Answer: a
Explanation: We are printing only the 1st two bytes of string and hence the answer is “he”.  
4. Which of the following will run without errors ?
a) round(45.8)
 b) round(6352.898,2,5)
c) round()
d) round(7463.123,2,1)
View Answer
Answer: a
Explanation: Execute help(round) in the shell to get details of the parameters that are passed into the round function.
5. What is the return type of function id?

a) int
 b) float
c) bool
d) dict
View Answer
Answer: a
Explanation: Execute help(id) to find out details in python shell.id returns a integer value that is unique.
6. In python we do not specify types,it is directly interpreted by the compiler, so consider the following operation to
 be performed.
1.  >>>x = 13 ? 2
objective is to make sure x has a integer value, select all that apply (python 3.xx)

a) x = 13 // 2
 b) x = int(13 / 2)
c) x = 13 % 2
d) All of the mentioned
View Answer
Answer: d
Explanation: // is integer operation in python 3.0 and int(..) is a type cast operator.
7. What error occurs when you execute?
apple = mango
a) SyntaxError
 b) NameError
c) ValueError
 

d) TypeError
View Answer
Answer: b
Explanation: Mango is not defined hence name error.
8. Carefully observe the code and give the answer.
1.  def example(a):
2.  a = a + '2'
3.  a = a*2
4.  return a
5.  >>>example("hello")

a) indentation Error
 b) cannot perform mathematical operation on strings
c) hello2
d) hello2hello2
View Answer
Answer: a
Explanation: Python codes have to be indented properly.
9. What data type is the object below ?

L = [1, 23, ‘hello’, 1]. 


1]. 
a) list
 b) dictionary
c) array
d) tuple
View Answer
Answer: a
Explanation: List data type can store any values within it.
10. In order to store values in terms of key and value we use what core data type.
a) list
 b) tuple
c) class
d) dictionary
View Answer
Answer: d
Explanation: Dictionary stores values in terms of keys and values.
11. Which of the following results in a SyntaxError ?
a) ‘”Once upon a time…”, she said.’ 
said.’  
 b) “He said, ‘Yes!'” 
‘Yes!'”  
c) ‘3\
‘3\’ 
d) ”’That’s okay”’ 
okay”’ 

View Answer
 

Answer: c
Explanation: Carefully look at the colons.
advertisement
12. The following is displayed by a print function call:
1.  tom
2.  dick
3.  harry

Select all of the function calls that result in this output


a) print(”’tom 
print(”’tom 
\ndick
\nharry”’)
nharry”’)  
 b) print(”’tomdickharry”’) 
print(”’tomdickharry”’)  
c) print(‘tom\ndick\
print(‘tom\ndick\nharry’)
nharry’)  
d) print(‘tom 
print(‘tom 
dick
harry’)  
harry’)
View Answer

Answer: c The \n adds a new line.


Explanation:

13. What is the average value of the code that is executed below ?
1.  >>>grade1 = 80
2.  >>>grade2 = 90
3.  >>>average = (grade1 + grade2) / 2
a) 85.0
 b) 85.1
c) 95.0
d) 95.1
View Answer
Answer: a

Explanation: Cause a decimal value of 0 to appear as output.


14. Select all options that print
hello-how-are-you
a) print(‘hello’, ‘how’, ‘are’, ‘you’) 
‘you’)  
 b) print(‘hello’, ‘how’, ‘are’, ‘you’ + ‘‘--‘ * 4) 
4) 
c) print(‘hello-
print(‘hello-‘ + ‘how-are-
‘how-are-you’)
you’)  
d) print(‘hello’ + ‘-
‘ -‘ + ‘how’ + ‘-
‘-‘ + ‘are’ + ‘you’) 
‘you’) 
View Answer
Answer: c
Explanation: Execute in the shell.
15. What is the return value of trunc() ?
a) int
 

 b) bool
c) float
d) None
View Answer
Answer: a
Explanation: Execute help(math.trunc) to get details.

Precedence

1. The value of the expressions 4/(3*(2-1)) and 4/3*(2-1) is the same. State whether true or false.
a) True
 b) False
View Answer
2. The value of the expression:
4+3%5
a) 4
 b) 7
c) 2
d) 0
View Answer
Answer: b
Explanation: The order of precedence is: %, +. Hence the expression above, on simplification results in 4 + 3 = 7.
Hence the result is 7.
3. Evaluate the expression given below if A= 16 and B = 15.
A % B // A
a) 0.0
 b) 0
c) 1.0
d) 1
View Answer
Answer: b
Explanation: The above expression is evaluated as: 16%15//16, which is equal to 1//16, which results in 0.
4. Which of the following operators has its associativity from right to left?
a) +
 b) //
c) %
d) **
View Answer
Answer: d
Explanation: All of the operators shown above have associativity from left to right, except exponentiation operator
(**) which has its associativity from right to left.
 

5. What is the value of x if:


x = int(43.55+2/2)
a) 43
 b) 44
c) 22
d) 23
View Answer
Answer: b
Explanation: The expression shown above is an example of explicit conversion. It is evaluated as int(43.55+1) =
int(44.55) = 44. Hence the result of this expression is 44.
6. What is the value of the following expression?
2+4.00, 2**4.0
a) (6.0, 16.0)
 b) (6.00, 16.00)
c) (6, 16)
d) (6.00, 16.0)
View Answer
Answer: a
Explanation: The result of the expression shown above is (6.0, 16.0). This is because the result is automatically
rounded off to one decimal place.
7. Which of the following is the truncation division operator?
a) /
 b) %
c) //
d) |
View Answer
Answer: c
Explanation: // is the operator for truncation division. It
I t it called so because it returns only the integer part of the
quotient, truncating the decimal part. For example: 20//3 = 6.
8. What are the values of the following expressions:
2**(3**2)
(2**3)**2
2**3**2
a) 64, 512, 64
 b) 64, 64, 64
c) 512, 512, 512
d) 512, 64, 512
View Answer
Answer: d
Explanation: Expression 1 is evaluated as: 2**9, which is equal to 512.Expression 2 is evaluated as 8**2, which is
equal to 64. The last expression is evaluated as 2**(3**2). This is because the associativity of ** operator is from
right to left. Hence the result of the third expression is 512.
 

advertisement
9. What is the value of the following expression:
8/4/2, 8/(4/2)

a) (1.0, 4.0)
 b) (1.0, 1.0)
c) (4.0. 1.0)
d) (4.0, 4.0)
View Answer
Answer: a
Explanation: The above expressions are evaluated as: 2/2, 8/2, which is equal to (1.0, 4.0).
10. What is the value of the following expression:
float(22//3+3/3)
a) 8
 b) 8.0
c) 8.3
d) 8.33
View Answer
Answer: b
Explanation: The expression shown above is evaluated as: float( 7+1) = float(8) = 8.0. Hence the result of this
expression is 8.0.
1. What is the output of the following expression:
print(4.00/(2.0+2.0))
a) Error
 b) 1.0
c) 1.00
d) 1
View Answer
Answer: b
Explanation: The result of the expression shown above is 1.0 because print rounds off digits.
2. Consider the expression given below. The value of X is:
X = 2+9*((3*12)-8)/10

a) 30.0
 b) 30.8
c) 28.4
d) 27.2
View Answer
Answer: d
Explanation: The expression shown above is evaluated as: 2+9*(36-8)/10, which simplifies to give 2+9*(2.8), which
is equal to 2+25.2 = 27.2. Hence the result of this expression is 27.2.
3. Which of the following expressions involves coercion when evaluated in Python?
a) 4.7 – 
4.7 –  1.5
 1.5
 

 b) 7.9 * 6.3


c) 1.7 % 2
d) 3.4 + 4.6
View Answer
Answer: c
Explanation: Coercion is the implicit (automatic) conversion of operands to a common type. Coercion is
automatically performed on mixed-type expressions. The expression 1.7 % 2 is evaluated as 1.7 % 2.0 (that is,
automatic conversion of int to float).
4. What is the value of the following expression:
24//6%3, 24//4//2
a) (1,3)
 b) (0,3)
c) (1,0)
d) (3,1)
View Answer
Answer: a
Explanation: The expressions are evaluated as: 4%3 and 6//2 respectively. This results in the answer (1,3). This is
 because the associativity of both of the expressions shown above is left to right.
5. Which among the following list of operators has the highest precedence?
+, -, **, %, /, <<, >>, |
a) <<, >>
 b) **
c) |
d) %
View Answer
Answer: b
Explanation: The highest precedence is that of the exponentiation operator, that is of **.
advertisement

6. What is the value of the expression:


float(4+int(2.39)%2)
a) 5.0
 b) 5
c) 4.0
d) 4
View Answer
Answer: c
Explanation: The above expression is an example of explicit conversion. It is evaluated as: float(4+int(2.39)%2) =
float(4+2%2) = float(4+0) = 4.0. Hence the result of this expression is 4.0.
7. Which of the following expressions is an example of type conversion?
a) 4.0 + float(3)

 b) 5.3 + 6.3


 

c) 5.0 + 3
d) 3 + 7
View Answer
Answer: a
Explanation: Type conversion is nothing but explicit conversion of operands to a specific type. Options ‘b’ and ‘c’
are examples of implicit conversion whereas option ‘a’ is an example of explicit conversion or type conversion.  

8. Which of the following expressions results in an error?


a) float(‘10’) 
float(‘10’) 
 b) int(‘10’)
int(‘10’)  
c) float(’10.8’) 
float(’10.8’) 
d) int(’10.8’) 
int(’10.8’) 
View Answer
Answer: d
Explanation: All of the above examples show explicit conversion. However the expression int(’10.8’) results in an
error.

9. What is the value of the expression:


4+2**5//10

a) 3
 b) 7
c) 77
d) 0
View Answer
Answer: b
Explanation: The order of precedence is: **, //, +. The expression 4+2**5//10 is evaluated as 4+32//10, which is
equal to 4+3 = 7. Hence the result of the expression shown above is 7.
10. The expression 2**2**3 is evaluates as: (2**2)**3. State whether this statement is true or false.
a) True
 b) False

View Answer
Answer: b
Explanation: The value of the expression (2**2)**3 = 4**3 = 64. When the expression 2**2**3 is evaluated in
 python, we get the result as 256, because this expression is evaluated as 2**(2**3). This is because the associativity
of exponentiation operator (**) is from right to left and not from left to right.
Join Telegram Group click here

6th Sem all subject MCQs: click here

Download pdfs: click here

Happy Learning!
Department of Computer Engineering

*Important*

22616 PWP MCQ (Programming With Python)

6th Sem all subject MCQs: click here


Download pdfs: click here

22616 PWP MCQ (Important MCQ for Summer 2021 Exam) Download pdf of 22616 PWP MCQ, The
following 101,102 pdf are important for the Exam so keep that in your head. Please go through all the
MCQ. Below pdf is released by cwipedia and the credits go to a different entity.
https://www.pythonprogramming.in/object-oriented-programming.html

Python Functions
1
Question 1
What will be the output of the following code :
print type(type(int))
A type 'int'
B type 'type'
C Error
D0
Ans: B

Question 2
What is the output of the following code :
L = ['a','b','c','d']
print "".join(L)
A Error
B None
C abcd
D [‘a’,’b’,’c’,’d’]
Ans: (C)

Explanation: “” depicts a null string and the join function combines the elements of the list into a
string.

Question 3
What is the output of the following segment :
chr(ord('A'))
AA
BB
Ca
D Error
Ans: (A)

Explanation: ord() function converts a character into its ASCII notation and chr() converts the ASCII
to character.

Question 4
What is the output of the following program :
y =8
z = lambda x : x * y
print z(6)
A 48
B 14
C 64
D None of the above
Ans: (A)

Explanation: lambdas are concise functions and thus, result = 6 * 8

Question 5
What is called when a function is defined inside a class?
A Module
B Class
C Another Function
D Method
Ans: (D)

Question 6
Which of the following is the use of id() function in python?
A Id returns the identity of the object
B Every object doesn’t have a unique id
C All of the mentioned
D None of the mentioned
Ans: (A)

Explanation: Each object in Python has a unique id. The id() function returns the object’s id.

Question 7
What is the output of the following program :
import re
sentence = 'horses are fast'
regex = re.compile('(?P<animal>w+) (?P<verb>w+) (?P<adjective>w+)')
matched = re.search(regex, sentence)
print(matched.groupdict())
A {‘animal’: ‘horses’, ‘verb’: ‘are’, ‘adjective’: ‘fast’}
B (‘horses’, ‘are’, ‘fast’)
C ‘horses are fast’
D ‘are’
Ans: (A)

Explanation: This function returns a dictionary that contains all the matches.

Question 8
Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], what is list1 after list1.pop(1)?
A [3, 4, 5, 20, 5, 25, 1, 3]
B [1, 3, 3, 4, 5, 5, 20, 25]
C [3, 5, 20, 5, 25, 1, 3]
D [1, 3, 4, 5, 20, 5, 25]
Ans: (C)

Explanation: pop(i) removes the ith index element from the list

Question 9
time.time() returns ________
A the current time
B the current time in milliseconds
C the current time in milliseconds since midnight
D the current time in milliseconds since midnight, January 1, 1970
E the current time in milliseconds since midnight, January 1, 1970 GMT (the Unix time)
Ans: (E)

Question 10
Consider the results of a medical experiment that aims to predict whether someone is going to
develop myopia based on some physical measurements and heredity. In this case, the input
dataset consists of the person’s medical characteristics and the target variable is binary: 1 for
those who are likely to develop myopia and 0 for those who aren’t. This can be best classified
as
A Regression
B Decision Tree
C Clustering
Association
D
Rules
Ans: (B)

Explanation: Regression: It is a statistical analysis which is used to establish relation


between a response and a predictor variable. It is mainly used in finance related
applications.
Decision Tree: Decision tree is a computational method which works on descriptive
data and records the observations of each object to reach to a result.
Clustering: It is a method of grouping more similar objects in a group and the non-
similar objects to other groups.
Association Rules: It uses if-then reasoning method using the support-confidence
technique to give a result.
According to the question Decision Tree is the most suitable technique that can be
used to get best result of the experiment.

Question 1
What is the output of the following code :
print 9//2
A 4.5
B 4.0
C4
D Error
Ans: C

Question 2
Which function overloads the >> operator?
A more()
B gt()
C ge()
D None of the above
(D)

Explanation: rshift() overloads the >> operatorQuestion


3
Which operator is overloaded by the or() function?
A ||
B|
C //
D/
Ans: (B)

Explanation: or() function overloads the bitwise OR operator

Question 4
What is the output of the following program :
i =0
while i < 3:
print i
i++
print i+1
A0 2 1 3 2 4
B0 1 2 3 4 5
C Error
D1 0 2 4 3 5
Ans: (C)

Explanation: There is no operator ++ in Python

Question 1
What is the output of the following program :
print "Hello World"[::-1]
A dlroW olleH
B Hello Worl
Cd
D Error
Ans: (A)

Explanation: [::] depicts extended slicing in Python and [::-1] returns the reverse of the string.

Question 2
Given a function that does not return any value, what value is shown when executed at the
shell?
A int
B bool
C void
D None
Ans: (D)

Explanation: Python explicitly defines the None object that is returned if no value is specified.

Question 3
Which module in Python supports regular expressions?
A re
B regex
C pyregex
D None of the above
Ans: (A)

Explanation: re is a part of the standard library and can be imported using: import re.

Question 4
What is the output of the following program :
print 0.1 + 0.2 == 0.3
A True
B False
C Machine dependent
D Error
Ans: Answer: (B)

Explanation: Neither of 0.1, 0.2 and 0.3 can be represented accurately in binary. The round off
errors from 0.1 and 0.2 accumulate and hence there is a difference of 5.5511e-17 between (0.1 +
0.2) and 0.3.

Question 5
Which of the following is not a complex number?
A k = 2 + 3j
B k = complex(2, 3)
C k = 2 + 3l
D k = 2 + 3J
Ans: (C)

Explanation: l (or L) stands for long.

Question 6
What does ~~~~~~5 evaluate to?
A +5
B -11
C +11
D -5
Ans: (A)

Explanation: ~x is equivalent to -(x+1).

Question 7
Given a string s = “Welcome”, which of the following code is incorrect?
A print s[0]
B print s.lower()
C s[1] = ‘r’
D print s.strip()
Ans: (C)

Explanation: strings are immutable in Python

Question 8
________ is a simple but incomplete version of a function.
A Stub
B Function
C A function developed using bottom-up approach
D A function developed using top-down approach
Ans: (A)

Question 9
To start Python from the command prompt, use the command ______
A execute python
B go python
C python
D run python
Ans: (C)

Question 10
Which of the following is correct about Python?
A It supports automatic garbage collection.
B It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java
C Both of the above
D None of the above
Ans: (C)

Question 1
Which of these is not a core data type?
A Lists
B Dictionary
C Tuples
D Class
Ans: (D)

Explanation: Class is a user defined data type

Question 2
What data type is the object below ? L = [1, 23, ‘hello’, 1]
A List
B Dictionary
C Tuple
D Array
Ans: (A)

Explanation: [ ] defines a list

Question 3
Which of the following function convert a string to a float in python?
A int(x [,base])
B long(x [,base] )
C float(x)
D str(x)
Ans: (C)

Explanation: float(x) − Converts x to a floating-point number

Question 4
Which of the following statement(s) is TRUE?

1. A hash function takes a message of arbitrary length and generates a fixed length code.
2. A hash function takes a message of fixed length and generates a code of variable
length.
3. A hash function may give the same hash value for distinct messages.

A I only
B II and III only
C I and III only
D II only

Ans: (C)

Explanation:

Hash function is defined as any function that can be used to map data of arbitrary size of data
to a fixed size data.. The values returned by a hash function are called hash values, hash
codes, digests, or simply hashes : Statement 1 is correct
Yes, it is possible that a Hash Function maps a value to a same location in the memmory
that’s why collision occurs and we have different technique to handle this problem :
Statement 3 is coorect.
eg : we have hash function, h(x) = x mod 3

Acc to Statement 1, no matter what the value of ‘x’ is h(x) results in a fixed mapping location.
Acc. to Statement 3, h(x) can result in same mapping mapping location for different value of ‘x’ e.g. if
x = 4 or x = 7 , h(x) = 1 in both the cases, although collision occurs.

What is the output of the following program :


def myfunc(a):
a =a +2
a =a *2
return a

print myfunc(2)
A8
B 16
Indentation
C
Error
D Runtime Error
Ans: (C)

Explanation: Python creates blocks of code based on the indentation of the code. Thus, new indent
defines a new scope.

Question 2
What is the output of the expression : 3*1**3
A 27
B9
C3
D1
Ans: (C)

Explanation: Precedence of ** is higher than that of 3, thus first 1**3 will be executed and the result
will be multiplied by 3.

Question 3
What is the output of the following program :
print '{0:.2}'.format(1.0 / 3)
A 0.333333
B 0.33
C 0.333333:-2
D Error
Ans: (B)

Explanation: .2 defines the precision of the floating point number.

Question 4
What is the output of the following program :
print '{0:-2%}'.format(1.0 / 3)
A 0.33
B 0.33%
C 33.33%
D 33%
Ans: (C)

Explanation: The % converts the 0.33 to percentage with respect to 1.0

Question 5
What is the output of the following program :
i =0
while i < 3:
print i
i += 1
else:
print 0
A0 1 2 3 0
B0 1 2 0
C0 1 2
D Error
Ans: (B)

Explanation: The else part is executed when the condition in the while statement is false.

Question 6
What is the output of the following program :
i =0
while i < 5:
print(i)
i += 1
if i == 3:
break
else:
print(0)
A0 1 2 0
B0 1 2
C Error
None of the
D
above
Ans: (B)

Explanation: The else part is not executed if control breaks out of the loop.

Question 7
What is the output of the following program :
print 'cd'.partition('cd')
A (‘cd’)
B (”)
C (‘cd’, ”, ”)
D (”, ‘cd’, ”)
Ans: (D)

Explanation: The entire string has been passed as the separator hence the first and the last item of
the tuple returned are null strings.

Question 8
What is the output of the following program :
print 'abef'.partition('cd')
A (‘abef’)
B (‘abef’, ‘cd’, ”)
C (‘abef’, ”, ”)
D Error
Ans: (C)

Explanation: The separator is not present in the string hence the second and the third elements of
the tuple are null strings.

Question 9
What is the output of the following program :
print 'abcefd'.replace('cd', '12')
A ab1ef2
B abcefd
C ab1efd
D ab12ed2
Ans: (B)

Explanation: The first substring is not present in the given string and hence nothing is replaced.

Question 10
What will be displayed by the following code?
def f(value, values):
v =1
values[0] = 44
t =3
v = [1, 2, 3]
f(t, v)
print(t, v[0])
A1 1
B 1 44
C3 1
D 3 44
(D)

Explanation: The value of t=3 is passed in funcion f(value,values) , v [list] is passed as values in the
same function. The v is stored in values and values[0]=44 , changes the value at index[‘0’] in the list
hence v=[44,2,3].

What is the output of the following code? Consider Python 2.7.


print tuple[1:3] if tuple == ( 'abcd', 786 , 2.23, 'john', 70.2 ) else
tuple()
A ( 'abcd', 786 , 2.23, 'john', 70.2 )
B abcd
C (786, 2.23)
D None of the above
(D)

Predict the output of following python programs:

Program 1:

r = lambda q: q * 2
s = lambda q: q * 3
x =2
x = r(x)
x = s(x)
x = r(x)
print x

Output:

24

Explanation : In the above program r and s are lambda functions or anonymous functions
and q is the argument to both of the functions. In first step we have initialized x to 2. In
second step we have passed x as argument to the lambda function r, this will return x*2
which is stored in x. That is, x = 4 now. Similarly in third step we have passed x to lambda
function s, So x = 4*3. i.e, x = 12 now. Again in the last step, x is multiplied by 2 by passing
it to function r. Therefore, x = 24.

Program 2:

a = 4.5
b =2
print a//b
Output:

2.0

Explanation : This type of division is called truncating division where the remainder is
truncated or dropped.

Program 3:

a = True
b = False
c = False

if a or b and c:
print "GEEKSFORGEEKS"
else:
print "geeksforgeeks"

Output:

GEEKSFORGEEKS

Explanation : In Python, AND operator has higher precedence than OR operator. So, it is
evaluated first. i.e, (b and c) evaluates to false.Now OR operator is evaluated. Here, (True or
False) evaluates to True. So the if condition becomes True and GEEKSFORGEEKS is
printed as output.

Program 4:

a = True
b = False
c = False

if not a or b:
print 1
elif not a or not b and c:
print 2
elif not a or b or not b and a:
print 3
else:
print 4

Output:

Explanation: In Python the precedence order is first NOT then AND and in last OR. So the
if condition and second elif condition evaluates to False while third elif condition is evaluated
to be True resulting in 3 as output.
Program 5:

count = 1

def doThis():

global count

for i in (1, 2, 3):


count += 1

doThis()

print count

Output:

Explanation: The variable count declared outside the function is global variable and also the
count variable being referenced in the function is the same global variable defined outside of
the function. So, the changes made to variable in the function is reflected to the original
variable. So, the output of the program is 4.

Predict the output of following Python Programs.


Program 1:

class Acc:
def __init__(self, id):
self.id = id
id = 555

acc = Acc(111)
print acc.id

Output:

111

Explanation: Instantiation of the class “Acc” automatically calls the method __init__ and
passes the object as the self parameter. 111 is assigned to data attribute of the object called id.
The value “555” is not retained in the object as it is not assigned to a data attribute of the
class/object. So, the output of the program is “111”

Program 2:

for i in range(2):
print i
for i in range(4,6):
print i

Output:

0
1
4
5

Explanation: If only single argument is passed to the range method, Python considers this
argument as the end of the range and the default start value of range is 0. So, it will print all
the numbers starting from 0 and before the supplied argument.
For the second for loop the starting value is explicitly supplied as 4 and ending is 5.

Program 3:

values = [1, 2, 3, 4]
numbers = set(values)

def checknums(num):
if num in numbers:
return True
else:
return False

for i in filter(checknums, values):


print i

Output:

1
2
3
4

Explanation: The function “filter” will return all items from list values which return True
when passed to the function “checkit”. “checkit” will check if the value is in the set. Since all
the numbers in the set come from the values list, all of the original values in the list will
return True.

Program 4:

counter = {}

def addToCounter(country):
if country in counter:
counter[country] += 1
else:
counter[country] = 1

addToCounter('China')
addToCounter('Japan')
addToCounter('china')

print len(counter)

Output:

Explanation: The task of “len” function is to return number of keys in a dictionary. Here 3
keys are added to the dictionary “country” using the “addToCounter” function.
Please note carefully – The keys to a dictionary are case sensitive.
Try yourself: What happens If same key is passed twice??

Predict the output of following Python Programs.

Program 1:

class Geeks:
def __init__(self, id):
self.id = id

manager = Geeks(100)

manager.__dict__['life'] = 49

print manager.life + len(manager.__dict__)

Output:

51

Explanation : In the above program we are creating a member variable having name ‘life’ by
adding it directly to the dictionary of the object ‘manager’ of class ‘Geeks’. Total numbers of
items in the dictionary is 2, the variables ‘life’ and ‘id’. Therefore the size or the length of the
dictionary is 2 and the variable ‘life’ is assigned a value ’49’. So the sum of the variable ‘life’
and the size of the dictionary is 49 + 2 = 51.

Program 2:

a = "GeeksforGeeks "

b = 13

print a + b
Output:

An error is shown.

Explanation : As you can see the variable ‘b’ is of type integer and the variable ‘a’ is of type
string. Also as Python is a strongly typed language we cannot simply concatenate an integer
with a string. We have to first convert the integer variable to the type string to concatenate it
with a string variable. So, trying to concatenate an integer variable to a string variable, an
exception of type “TypeError” is occurred.

Program 3:

dictionary = {}
dictionary[1] = 1
dictionary['1'] = 2
dictionary[1] += 1

sum = 0
for k in dictionary:
sum += dictionary[k]

print sum

Output:

Explanation : In the above dictionary, the key 1 enclosed between single quotes and only 1
represents two different keys as one of them is integer and other is string. So, the output of
the program is 4.

Predict the output of following Python Programs.

Program 1:

nameList = ['Harsh', 'Pratik', 'Bob', 'Dhruv']

print nameList[1][-1]

Output:k

Explanation:
The index position -1 represents either the last element in a list or the last character in a
String. In the above given list of names “nameList”, the index 1 represents the second
element i.e, the second string “Pratik” and the index -1 represents the last character in the
string “Pratik”. So, the output is “k”.

Program 2:
nameList = ['Harsh', 'Pratik', 'Bob', 'Dhruv']

pos = nameList.index("GeeksforGeeks")

print pos * 5

Output:

An Exception is thrown, ValueError: 'GeeksforGeeks' is not in list

Explanation:
The task of index is to find the position of a supplied value in a given list. In the above
program the supplied value is “GeeksforGeeks” and list is nameList. As GeeksforGeeks is
not present in the list, an exception is thrown.

Program 3:

geekCodes = [1, 2, 3, 4]

geekCodes.append([5,6,7,8])

print len(geekCodes)

Output:

Explanation:
The task of append() method is to append a passed obj into an existing list. But instead of
passing a list to the append method will not merge the two lists, the entire list which is passed
is added as an element of the list. So the output is 5.

Program 4:

def addToList(listcontainer):
listcontainer += [10]

mylistContainer = [10, 20, 30, 40]


addToList(mylistContainer)
print len(mylistContainer)

Output:

Explanation:
In Python, everything is a reference and references are passed by value. Parameter passing in
Python is same as reference passing in Java. As a consequence, the function can modify the
value referred by passed argument, i.e. the value of the variable in the caller’s scope can be
changed. Here the task of the function “addToList” is to add an element 10 in the list, So this
will increase the length of list by 1. So the output of program is 5.
Program 1:

def gfgFunction():
"Geeksforgeeks is cool website for boosting up technical skills"
return 1

print gfgFunction.__doc__[17:21]

Output:cool

Explanation:
There is a docstring defined for this method, by putting a string on the first line after the start
of the function definition. The docstring can be referenced using the __doc__ attribute of the
function.
And hence it prints the indexed string.

Program 2:

class A(object):
val = 1

class B(A):
pass

class C(A):
pass

print A.val, B.val, C.val


B.val =2
print A.val, B.val, C.val
A.val =3
print A.val, B.val, C.val

Output:

1 1 1
1 2 1
3 2 3

Explanation:
In Python, class variables are internally handled as dictionaries. If a variable name is not
found in the dictionary of the current class, the class hierarchy (i.e., its parent classes) are
searched until the referenced variable name is found, if the variable is not found error is being
thrown.
So, in the above program the first call to print() prints the initialized value i.e, 1.
In the second call since B. val is set to 2, the output is 1 2 1.
The last output 3 2 3 may be surprising. Instead of 3 3 3, here B.val reflects 2 instead of 3
since it is overridden earlier.

Program 3:

check1 = ['Learn', 'Quiz', 'Practice', 'Contribute']


check2 = check1
check3 = check1[:]
check2[0] = 'Code'
check3[1] = 'Mcq'

count = 0
for c in (check1, check2, check3):
if c[0] == 'Code':
count += 1
if c[1] == 'Mcq':
count += 10

print count

Output:

12

Explanation:
When assigning check1 to check2, we create a second reference to the same list. Changes to
check2 affects check1. When assigning the slice of all elements in check1 to check3, we are
creating a full copy of check1 which can be modified independently (i.e, any change in
check3 will not affect check1).
So, while checking check1 ‘Code’ gets matched and count increases to 1, but Mcq doest gets
matched since its available only in check3.
Now checking check2 here also ‘Code’ gets matched resulting in count value to 2.
Finally while checking check3 which is separate than both check1 and check2 here only Mcq
gets matched and count becomes 12.

Program 4:

def gfg(x,l=[]):
for i in range(x):
l.append(i*i)
print(l)

gfg(2)
gfg(3,[3,2,1])
gfg(3)

Output:

[0, 1]
[3, 2, 1, 0, 1, 4]
[0, 1, 0, 1, 4]

Explanation:
The first function call should be fairly obvious, the loop appends 0 and then 1 to the empty
list, l. l is a name for a variable that points to a list stored in memory. The second call starts
off by creating a new list in a new block of memory. l then refers to this new list. It then
appends 0, 1 and 4 to this new list. So that’s great. The third function call is the weird one. It
uses the original list stored in the original memory block. That is why it starts off with 0 and
1.
Predict the output of the following Python programs. These question set will make you
conversant with List Concepts in Python programming language.

 Program 1

list1 = ['physics', 'chemistry', 1997, 2000]

list2 = [1, 2, 3, 4, 5, 6, 7 ]

print "list1[0]: ", list1[0] #statement 1


print "list1[0]: ", list1[-2] #statement 2
print "list1[-2]: ", list1[1:] #statement 3
print "list2[1:5]: ", list2[1:5] #statement 4

Output:

list1[0]: physics
list1[0]: 1997
list1[-2]: ['chemistry', 1997, 2000]
list2[1:5]: [2, 3, 4, 5]

Explanation:
To access values in lists, we use the square brackets for slicing along with the index
or indices to obtain required value available at that index.For N items in a List MAX
value of index will be N-1.
Statement 1 : This will print item located at index 0 in Output.
Statement 2 : This will print item located at index -2 i.e.second last element in
Output.
Statement 3 : This will print items located from index 1 to end of the list.
Statement 4 : This will print items located from index 1 to 4 of the list.

 Program 2

list1 = ['physics', 'chemistry', 1997, 2000]

print "list1[1][1]: ", list1[1][1] #statement 1

print "list1[1][-1]: ", list1[1][-1] #statement 2

Output:

list1[1][1]: h
list1[1][-1]: y

Explanation:
In python we can slice a list but we can also slice a element within list if it is a string.
The declaration list[x][y] will mean that ‘x’ is the index of element within a list and
‘y’ is the index of entity within that string.

 Program 3

list1 = [1998, 2002, 1997, 2000]


list2 = [2014, 2016, 1996, 2009]
print "list1 + list 2 = : ", list1 + list2 #statement 1

print "list1 * 2 = : ", list1 * 2 #statement 2

Output:

list1 + list 2 = : [1998, 2002, 1997, 2000, 2014, 2016, 1996, 2009]
list1 * 2 = : [1998, 2002, 1997, 2000, 1998, 2002, 1997, 2000]

Explanation:
When addition(+) operator uses list as its operands then the two lists will get
concatenated. And when a list id multiplied with a constant k>=0 then the same list is
appended k times in the original list.

 Program 4

list1 = range(100, 110) #statement 1


print "index of element 105 is : ", list1.index(105) #statement 2

Output:

index of element 105 is : 5

Explanation:
Statement 1 : will genetrate numbers from 100 to 110 and appent all these numbers
in the list.
Statement 2 : will give the index value of 105 in the list list1.

 Program 5

list1 = [1, 2, 3, 4, 5]
list2 = list1

list2[0] = 0;

print "list1= : ", list1 #statement 2

Output:

list1= : [0, 2, 3, 4, 5]

Explanation:
In this problem, we have provided a reference to the list1 with another name list2 but
these two lists are same which have two references(list1 and list2). So any alteration
with list2 will affect the original list.

Predict the output of the following Python programs. These question set will make you
conversant with String Concepts in Python programming language.
 Program 1

var1 = 'Hello Geeks!'


var2 = "GeeksforGeeks"

print "var1[0]: ", var1[0] # statement 1


print "var2[1:5]: ", var2[1:5] # statement 2

Output:

var1[0]: H
var2[1:5]: eeks

Explanation:
Strings are among the most popular types in Python. We can create a string by
enclosing characters within quotes. Python treats single quotes same as double
quotes. It is notable that unlike C or C++ python does not support a character type; in
fact single characters are treated as strings of length one, thus also considered a
substring. To access substrings, use the square brackets for slicing along with the
index or indices to obtain your substring.
Statement 1: will simply put character at 0 index on the output screen.
Statement 2: will put the character starting from 0 index to index 4.

 Program 2

var1 = 'Geeks'

print "Original String :-", var1

print "Updated String :- ", var1[:5] + 'for' + 'Geeks' # statement 1

Output:

Original String :- Geeks


Updated String :- GeeksforGeeks

Explanation:
Python provides a flexible way to update string in your code. Use square brackets and
specify the index from where string has to be updated and use + operator to append
the string. [x:y] operator is called Range Slice and gives the characters from the given
range.

Statement 1: In the given code tells the interpreter that from 5th index of string
present in var1 append ‘for’ and ‘Geeks’ to it.

 Program 3

para_str = """this is a long string that is made up of


several lines and non-printable characters such as
TAB ( \t ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [ \n ], or just a NEWLINE within
the variable assignment will also show up.
"""
print para_str

Output:

this is a long string that is made up of


several lines and non-printable characters such as
TAB ( ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [
], or just a NEWLINE within
the variable assignment will also show up.

Explanation:
Python’s triple quotes comes to the rescue by allowing strings to span multiple lines,
including NEWLINEs, TABs, and any other special characters.The syntax for triple
quotes consists of three consecutive single or double quotes.

 Program 4

print 'C:\\inside C directory' # statement1

print r'C:\\inside C directory' # statement2

Output:

C:\inside C directory
C:\\inside C directory

Explanation:
Raw strings do not treat the backslash as special characters at all.
Statement 1 : will print the message while considering backslash as a special
character.
Statement 2 : is a raw string that will treat backslash as a normal character.

 Program 5

print '\x25\x26'

Output:

%&

Explanation:
In the above code \x is an escape sequence that means the following 2 digits are a
hexadecimal number encoding a character. Hence the corresponding symbols will be
on the output screen.
Predict the output of the following Python programs.

 Program 1

list = [1, 2, 3, None, (1, 2, 3, 4, 5), ['Geeks', 'for', 'Geeks']]


print len(list)

Output:

Explanation:
The beauty of python list datatype is that within a list, a programmer can nest another
list, a dictionary or a tuple. Since in the code there are 6 items present in the list the
length of the list is 6.

 Program 2

list = ['python', 'learning', '@', 'Geeks', 'for', 'Geeks']

print list[::]
print list[0:6:2]
print list[ :6: ]
print list[ :6:2]
print list[ ::3]
print list[ ::-2]

Output:

['python', 'learning', '@', 'Geeks', 'for', 'Geeks']


['python', '@', 'for']
['python', 'learning', '@', 'Geeks', 'for', 'Geeks']
['python', '@', 'for']
['python', 'Geeks']
['Geeks', 'Geeks', 'learning']

Explanation:
In python list slicing can also be done by using the syntax listName[x:y:z] where x
means the initial index, y-1 defines the final index value and z specifies the step size.
If anyone of the values among x, y and z is missing the interpreter takes default value.

Note:
1. For x default value is 0 i.e. start of the list.
2. For y default value is length of the list.
3. For z default value is 1 i.e. every element of the list.

 Program 3

d1 = [10, 20, 30, 40, 50]


d2 = [1, 2, 3, 4, 5]
print d1 - d1

Output:
No Output

Explanation:
Unlike additon or relational operators not all the artihmatic operaters can use lists as
their operands. Since – minus operator can’t take lists as its operand no output will be
produced. Program will produce following error.

TypeError: unsupported operand type(s) for -: 'list' and 'list'

 Program 4

list = ['a', 'b', 'c', 'd', 'e']


print list[10:]

Output:

[]

Explanation:
As one would expect, attempting to access a member of a list using an index that
exceeds the number of members (e.g., attempting to access list[10] in the list above)
results in an IndexError. However, attempting to access a slice of a list at a starting
index that exceeds the number of members in the list will not result in an IndexError
and will simply return an empty list.

 Program 5

list = ['a', 'b', 'c']*-3


print list

Output:

[]

Explanation:
A expression list[listelements]*N where N is a integer appends N copies of list
elements in the original list. If N is a negetive integer or 0 output will be a empty list
else if N is positive list elements will be added N times to the original list.

1) What is the output of the following program?

filter_none

edit

play_arrow

brightness_4

dictionary = {'GFG' : 'geeksforgeeks.org',


'google' : 'google.com',
'facebook' : 'facebook.com'
}
del dictionary['google'];
for key, values in dictionary.items():
print(key)
dictionary.clear();
for key, values in dictionary.items():
print(key)
del dictionary;
for key, values in dictionary.items():
print(key)

a) Both b and d
b) Runtime error
c) GFG
facebook
d) facebook
GFG

Ans. (a)
Output:

facebook
GFG

Explanation: The statement: del dictionary; removes the entire dictionary, so iterating over
a deleted dictionary throws a runtime error as follows:

Traceback (most recent call last):


File "cbeac2f0e35485f19ae7c07f6b416e84.py", line 12, in
for key, values in dictionary.items():
NameError: name 'dictionary' is not defined

2) What is the output of the following program?

filter_none

edit

play_arrow

brightness_4

dictionary1 = {'Google' : 1,
'Facebook' : 2,
'Microsoft' : 3
}
dictionary2 = {'GFG' : 1,
'Microsoft' : 2,
'Youtube' : 3
}
dictionary1.update(dictionary2);
for key, values in dictionary1.items():
print(key, values)
a) Compilation error
b) Runtime error
c) (‘Google’, 1)
(‘Facebook’, 2)
(‘Youtube’, 3)
(‘Microsoft’, 2)
(‘GFG’, 1)
d) None of these

Ans. (c)
Explanation: dictionary1.update(dictionary2) is used to update the entries of dictionary1
with entries of dictionary2. If there are same keys in two dictionaries, then the value in
second dictionary is used.

3) What is the output of the following program?

filter_none

edit

play_arrow

brightness_4

dictionary1 = {'GFG' : 1,
'Google' : 2,
'GFG' : 3
}
print(dictionary1['GFG']);

a) Compilation error due to duplicate keys


b) Runtime time error due to duplicate keys
c) 3
d) 1

Ans. (c)
Explanation: Here, GFG is the duplicate key. Duplicate keys are not allowed in python. If
there are same keys in a dictionay, then the value assigned mostly recently is assigned to the
that key.

4) What is the output of the following program?

filter_none

edit

play_arrow

brightness_4

temp = dict()
temp['key1'] = {'key1' : 44, 'key2' : 566}
temp['key2'] = [1, 2, 3, 4]
for (key, values) in temp.items():
print(values, end = "")

a) Compilation error
b) {‘key1’: 44, ‘key2’: 566}[1, 2, 3, 4]
c) Runtime error
d) None of the above

Ans. (b)
Explanation: A dictionary can hold any value such as an integer, string, list or even another
dictionary holding key value pairs.
Note: This code can be executed only in python versions above 3

5) What is the output of the following program?

filter_none

edit

play_arrow

brightness_4

temp = {'GFG' : 1,
'Facebook' : 2,
'Google' : 3
}
for (key, values) in temp.items():
print(key, values, end = " ")

a) Google 3 GFG 1 Facebook 2


b) Facebook 2 GFG 1 Google 3
c) Facebook 2 Google 3 GFG 1
d) Any of the above

Ans. (d)
Explanation: Dictionaries are unordered. So any key value pairs can be added at any
location within a dictionary. Any of the output may come.
Note: This code can be executed only in python versions above 3.
Question: Describe how multithreading is achieved in Python.

Answer: Even though Python comes with a multi-threading package, if the motive behind
multithreading is to speed the code then using the package is not the go-to option.

The package has something called the GIL or Global Interpreter Lock, which is a construct. It
ensures that one and only one of the threads execute at any given time. A thread acquires the
GIL and then do some work before passing it to the next thread.

This happens so fast that to a user it seems that threads are executing in parallel. Obviously,
this is not the case as they are just taking turns while using the same CPU core. Moreover,
GIL passing adds to the overall overhead to the execution.

Hence, if you intend to use the threading package for speeding up the execution, using the
package is not recommended.

Question: Draw a comparison between the range and xrange in Python.

Answer: In terms of functionality, both range and xrange are identical. Both allow for
generating a list of integers. The main difference between the two is that while range returns
a Python list object, xrange returns an xrange object.

Xrange is not able to generate a static list at runtime the way range does. On the contrary, it
creates values along with the requirements via a special technique called yielding. It is used
with a type of object known as generators.

If you have a very enormous range for which you need to generate a list, then xrange is the
function to opt for. This is especially relevant for scenarios dealing with a memory-sensitive
system, such as a smartphone.
The range is a memory beast. Using it requires much more memory, especially if the
requirement is gigantic. Hence, in creating an array of integers to suit the needs, it can result
in a Memory Error and ultimately lead to crashing the program.

Question: Explain Inheritance and its various types in Python?

Answer: Inheritance enables a class to acquire all the members of another class. These
members can be attributes, methods, or both. By providing reusability, inheritance makes it
easier to create as well as maintain an application.

The class which acquires is known as the child class or the derived class. The one that it
acquires from is known as the superclass or base class or the parent class. There are 4 forms
of inheritance supported by Python:

Interested in Python? Enquire for the best course suited for you.

 Single Inheritance – A single derived class acquires from on single superclass.


 Multi-Level Inheritance – At least 2 different derived classes acquire from two distinct base
classes.
 Hierarchical Inheritance – A number of child classes acquire from one superclass
 Multiple Inheritance – A derived class acquires from several superclasses.

Question: Explain how is it possible to Get the Google cache age of any URL or webpage using Python.

Answer: In order to Get the Google cache age of any URL or webpage using Python, the
following URL format is used:

http://webcache.googleusercontent.com/search?q=cache:URLGOESHERE

Simply replace URLGOESHERE with the web address of the website or webpage whose
cache you need to retrieve and see in Python.

Question: Give a detailed explanation about setting up the database in Django.

Answer: The process of setting up a database is initiated by using the command edit
mysite/setting.py. This is a normal Python module with a module-level representation of
Django settings. Django relies on SQLite by default, which is easy to be used as it doesn’t
require any other installation.

SQLite stores data as a single file in the filesystem. Now, you need to tell Django how to use
the database. For this, the project’s setting.py file needs to be used. Following code must be
added to the file for making the database workable with the Django project:

DATABASES = {
'default': {
'ENGINE' : 'django.db.backends.sqlite3',
'NAME' : os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
If you need to use a database server other than the SQLite, such as MS SQL, MySQL, and
PostgreSQL, then you need to use the database’s administration tools to create a brand new
database for your Django project.

You have to modify the following keys in the DATABASE ‘default’ item to make the new
database work with the Django project:

 ENGINE – For example, when working with a MySQL database replace


‘django.db.backends.sqlite3’ with ‘django.db.backends.mysql’
 NAME – Whether using SQLite or some other database management system, the database is
typically a file on the system. The NAME should contain the full path to the file, including the
name of that particular file.

NOTE: - Settings like Host, Password, and User needs to be added when not choosing
SQLite as the database.

Check out the advantages and disadvantages of Django.

Question: How will you differentiate between deep copy and shallow copy?

Answer: We use shallow copy when a new instance type gets created. It keeps the values that
are copied in the new instance. Just like it copies the values, the shallow copy also copies the
reference pointers.

Reference points copied in the shallow copy reference to the original objects. Any changes
made in any member of the class affects the original copy of the same. Shallow copy enables
faster execution of the program.

Deep copy is used for storing values that are already copied. Unlike shallow copy, it doesn’t
copy the reference pointers to the objects. Deep copy makes the reference to an object in
addition to storing the new object that is pointed by some other object.

Changes made to the original copy will not affect any other copy that makes use of the
referenced or stored object. Contrary to the shallow copy, deep copy makes execution of a
program slower. This is due to the fact that it makes some copies for each object that is
called.

Question: How will you distinguish between NumPy and SciPy?

Answer: Typically, NumPy contains nothing but the array data type and the most basic
operations, such as basic element-wise functions, indexing, reshaping, and sorting. All the
numerical code resides in SciPy.

As one of NumPy’s most important goals is compatibility, the library tries to retain all
features supported by either of its predecessors. Hence, NumPy contains a few linear algebra
functions despite the fact that these more appropriately belong to the SciPy library.

SciPy contains fully-featured versions of the linear algebra modules available to NumPy in
addition to several other numerical algorithms.
Question: Observe the following code:
A0 = dict(zip(('a','b','c','d','e'),(1,2,3,4,5)))
A1 = range(10)A2 = sorted([i for i in A1 if i in A0])
A3 = sorted([A0[s] for s in A0])
A4 = [i for i in A1 if i in A3]
A5 =
A6 = [[i,i*i] for i in A1]
print(A0,A1,A2,A3,A4,A5,A6)

Write down the output of the code.


Answer:

A0 = {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4} # the order may vary


A1 = range(0, 10)
A2 = []
A3 = [1, 2, 3, 4, 5]
A4 = [1, 2, 3, 4, 5]
A5 =
A6 = [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]

Question: Python has something called the dictionary. Explain using an example.

Answer: A dictionary in Python programming language is an unordered collection of data


values such as a map. Dictionary holds key:value pair. It helps in defining a one-to-one
relationship between keys and values. Indexed by keys, a typical dictionary contains a pair of
keys and corresponding values.

Let us take an example with three keys, namely Website, Language, and Offering. Their
corresponding values are hackr.io, Python, and Tutorials. The code for the example will be:

dict={‘Website’:‘hackr.io’,‘Language’:‘Python’:‘Offering’:‘Tutorials’}
print dict[Website] #Prints hackr.io
print dict[Language] #Prints Python
print dict[Offering] #Prints Tutorials

Question: Python supports negative indexes. What are they and why are they used?

Answer: The sequences in Python are indexed. It consists of positive and negative numbers.
Positive numbers use 0 as the first index, 1 as the second index, and so on. Hence, any index
for a positive number n is n-1.

Unlike positive numbers, index numbering for the negative numbers start from -1 and it
represents the last index in the sequence. Likewise, -2 represents the penultimate index.
These are known as negative indexes. Negative indexes are used for:

 Removing any new-line spaces from the string, thus allowing the string to except the last
character, represented as S[:-1]
 Showing the index to representing the string in the correct order
Question: Suppose you need to collect and print data from IMDb top 250 Movies page. Write a program
in Python for doing so. (NOTE: - You can limit the displayed information for 3 fields; namely movie name,
release year, and rating.)

Answer:

from bs4 import BeautifulSoup


import requests
import sys
url = 'http://www.imdb.com/chart/top'
response = requests.get(url)
soup = BeautifulSoup(response.text)
tr = soup.findChildren("tr")
tr = iter(tr)
next(tr)
for movie in tr:
title = movie.find('td', {'class': 'titleColumn'} ).find('a').contents[0]
year = movie.find('td', {'class': 'titleColumn'} ).find('span', {'class':
'secondaryInfo'}).contents[0]
rating = movie.find('td', {'class': 'ratingColumn imdbRating'}
).find('strong').contents[0]
row = title + ' - ' + year + ' ' + ' ' + rating
print(row)

Question: Take a look at the following code:


try: if '1' != 1:
raise "someError"
else: print("someError has not occured")
except "someError": pr
int ("someError has occured")

What will be the output?


Answer: The output of the program will be “invalid code.” This is because a new exception
class must inherit from a BaseException.

Question: What do you understand by monkey patching in Python?

Answer: The dynamic modifications made to a class or module at runtime are termed as
monkey patching in Python. Consider the following code snippet:

# m.py
class MyClass:
def f(self):
print "f()"

We can monkey-patch the program something like this:

import m
def monkey_f(self):
print "monkey_f()"
m.MyClass.f = monkey_f
obj = m.MyClass()
obj.f()

Output for the program will be monkey_f().


The examples demonstrate changes made in the behavior of f() in MyClass using the function
we defined i.e. monkey_f() outside of the module m.

Question: What do you understand by the process of compilation and linking in Python?

Answer: In order to compile new extensions without any error, compiling and linking is used
in Python. Linking initiates only and only when the compilation is complete.

In the case of dynamic loading, the process of compilation and linking depends on the style
that is provided with the concerned system. In order to provide dynamic loading of the
configuration setup files and rebuilding the interpreter, the Python interpreter is used.

Question: What is Flask and what are the benefits of using it?

Answer: Flask is a web microframework for Python with Jinja2 and Werkzeug as its
dependencies. As such, it has some notable advantages:

 Flask has little to no dependencies on external libraries


 Because there is a little external dependency to update and fewer security bugs, the web
microframework is lightweight to use.
 Features an inbuilt development server and a fast debugger.

Question: What is the map() function used for in Python?

Answer: The map() function applies a given function to each item of an iterable. It then
returns a list of the results. The value returned from the map() function can then be passed on
to functions to the likes of the list() and set().

Typically, the given function is the first argument and the iterable is available as the second
argument to a map() function. Several tables are given if the function takes in more than one
arguments.

Question: What is Pickling and Unpickling in Python?

Answer: The Pickle module in Python allows accepting any object and then converting it into
a string representation. It then dumps the same into a file by means of the dump function.
This process is known as pickling.

The reverse process of pickling is known as unpickling i.e. retrieving original Python objects
from a stored string representation.

Question: Whenever Python exits, all the memory isn’t deallocated. Why is it so?

Answer: Upon exiting, Python’s built-in effective cleanup mechanism comes into play and
try to deallocate or destroy every other object.

However, Python modules that are having circular references to other objects or the objects
that are referenced from the global namespaces aren’t always deallocated or destroyed.
This is because it is not possible to deallocate those portions of the memory that are reserved
by the C library.

Question: Write a program in Python for getting indices of N maximum values in a NumPy array.

Answer:

import numpy as np
arr = np.array([1, 3, 2, 4, 5])
print(arr.argsort()[-3:][::-1])
Output:
[4 3 1]

Question: Write code to show randomizing the items of a list in place in Python along with the output.

Answer:

from random import shuffle


x = ['hackr.io', 'Is', 'The', 'Best', 'For', 'Learning', 'Python']
shuffle(x)
print(x)
Output:
['For', 'Python', 'Learning', 'Is', 'Best', 'The', 'hackr.io']

Question: Explain memory managed in Python?

Answer: Python private heap space takes place of memory management in Python. It
contains all Python objects and data structures. The interpreter is responsible to take care of
this private heap and the programmer does not have access to it. The Python memory
manager is responsible for the allocation of Python heap space for Python objects. The
programmer may access some tools for the code with the help of the core API. Python also
provides an inbuilt garbage collector, which recycles all the unused memory and frees the
memory and makes it available to heap space.

Question: What is the lambda function?

Answer: An anonymous function is known as a lambda function. This function can have
only one statement but can have any number of parameters.

a = lambda x,y : x+y


print(a(5, 6))

Question: What are Python decorators?

Answer: A specific change made in Python syntax to alter the functions easily are termed as
Python decorators.

Question: Differentiate between list and tuple.

Answer: Tuple is not mutable it can be hashed eg. key for dictionaries. On the other hand,
lists are mutable.
Question: How are arguments passed in Python? By value or by reference?

Answer: All of the Python is an object and all variables hold references to the object. The
reference values are according to the functions; as a result, the value of the reference cannot
be changed.

Question: What are the built-in types provided by the Python?

Answer:

Mutable built-in types:

 Lists
 Sets
 Dictionaries

Immutable built-in types:

 Strings
 Tuples
 Numbers

Question: How a file is deleted in Python?

Answer: The file can be deleted by either of these commands:

os.remove(filename)
os.unlink(filename)

Question: What are Python modules?

Answer: A file containing Python code like functions and variables is a Python module. A
Python module is an executable file with a .py extension.

Python has built-in modules some of which are:

 os
 sys
 math
 random
 data time
 JSON

Question: What is the // operator? What is its use?

Answer: The // is a Floor Divisionoperator used for dividing two operands with the result as
quotient displaying digits before the decimal point. For instance, 10//5 = 2 and 10.0//5.0 =
2.0.
Question: What is the split function used for?

Answer: The split function breaks the string into shorter strings using the defined separator.
It returns the list of all the words present in the string.

Question: Explain the Dogpile effect.

Answer: The event when the cache expires and websites are hit by multiple requests made by
the client at the same time. Using a semaphore lock prevents the Dogpile effect. In this
system when value expires, the first process acquires the lock and starts generating new
value.

Question: What is a pass in Python?

Answer: No-operation Python statement refers to pass. It is a place holder in the compound
statement, where there should have a blank left or nothing written there.

Question: Is Python a case sensitive language?

Answer: Yes Python is a case sensitive language.

Question: Define slicing in Python.

Answer: Slicing refers to the mechanism to select the range of items from sequence types
like lists, tuples, strings.

Question: What are docstring?

Answer: Docstring is a Python documentation string, it is a way of documenting Python


functions, classes and modules.

Question: What is [::-1} used for?

Answer: [::-1} reverses the order of an array or a sequence. However, the original array or
the list remains unchanged.

import array as arr


Num_Array=arr.array('k',[1,2,3,4,5])
Num_Array[::-1]

Question: Define Python Iterators.

Answer: Group of elements, containers or objects that can be traversed.

Question: How are comments written in Python?

Answer: Comments in Python start with a # character, they can also be written within
docstring(String within triple quotes)
Question: How to capitalize the first letter of string?

Answer: Capitalize() method capitalizes the first letter of the string, and if the letter is
already capital it returns the original string

Question: What is, not and in operators?

Answer: Operators are functions that take two or more values and returns the corresponding
result.

 is: returns true when two operands are true


 not: returns inverse of a boolean value
 in: checks if some element is present in some sequence.

Question: How are files deleted in Python?

Answer: To delete a file in Python:

1. Import OS module
2. Use os.remove() function

Question: How are modules imported in Python?

Answer: Modules are imported using the import keyword by either of the following three
ways:

import array
import array as arr
from array import *

Question: What is monkey patching?

Answer: Dynamic modifications of a class or module at run-time refers to a monkey patch.

Question: Does Python supports multiple inheritances?

Answer: Yes, in Python a class can be derived from more than one parent class.

Question: What does the method object() do?

Answer: The method returns a featureless object that is base for all classes. This method does
not take any parameters.

Question: What is pep 8?

Answer: Python Enhancement Proposal or pep 8 is a set of rules that specify how to format
Python code for maximum readability.
Question: What is namespace in Python?

Answer: A naming system used to make sure that names are unique to avoid naming
conflicts refers to as Namespace.

Question: Is indentation necessary in Python?

Answer: Indentation is required in Python if not done properly the code is not executed
properly and might throw errors. Indentation is usually done using four space characters.

Question: Define a function in Python

Answer: A block of code that is executed when it is called is defined as a function. Keyword
def is used to define a Python function.

Question: Define self in Python

Answer: An instance of a class or an object is self in Python. It is included as the first


parameter. It helps to differentiate between the methods and attributes of a class with local
variables.
Join Telegram Group click here

6th Sem all subject MCQs: click here

Download pdfs: click here

Happy Learning!
Department of Computer Engineering

*Important*

22616 PWP MCQ (Programming With Python)

6th Sem all subject MCQs: click here


Download pdfs: click here

22616 PWP MCQ (Important MCQ for Summer 2021 Exam) Download pdf of 22616 PWP MCQ, The
following 101,102 pdf are important for the Exam so keep that in your head. Please go through all the
MCQ. Below pdf is released by cwipedia and the credits go to a different entity.
Python MCQ

1. What will be the output after the following statements?

m = 28
n = 5
print(m // n)

a. 5.0
b. 6
c. 5
d. 4.0

2. What will be the output after the following statements?

m = 90
n = 7
print(m % n)

a. 6
b. 4
c. 6.0
d. 5.0

3. What will be the output after the following statements?

m = 79
n = 64
print(m < n)

a. m < n
b. False
c. True
d. No

4. What will be the output after the following statements?


m = 92
n = 35
print(m > n)

a. True
b. False
c. Yes
d. No

5. What will be the output after the following statements?

m = False
n = True
print(m and n)

a. m and n
b. False
c. True
d. mn

6. What will be the output after the following statements?

m = True
n = False
print(m or n)

a. m or n
b. False
c. True
d. mn

7. What will be the output after the following statements?

m = True
n = False
print(not m)

a. not m
b. False
c. True
d. Not defined

8. What will be the output after the following statements?

m = True
n = False
print('not n')

a. not n
b. False
c. True
d. Not defined

9. What will be the output after the following statements?

m = 7 * 5 + 8
print(m)

a. 91
b. 20
c. 47
d. 43

10. What will be the output after the following statements?

m = 9 * (3 + 12)
print(m)

a. 45
b. 159
c. 95
d. 135

11. What will be the output after the following statements?

m = '40' + '01'
print(m)
a. 4001
b. 01
c. 41
d. 40

12. What will be the output after the following statements?

m = 81 + 34
print(m)

a. 8134
b. 81
c. 115
d. 34

13. What will be the data type of n after the following statements if the user entered the
number 45?

m = input('Enter a number: ')


n = int(m)

a. Float
b. String
c. List
d. Integer

14. What is the data type of m after the following statement?

m = (41, 54, 23, 68)

a. Dictionary
b. Tuple
c. String
d. List

15. What is the data type of m after the following statement?

m = ['July', 'September', 'December']


a. Dictionary
b. Tuple
c. List
d. String

16. What will be the output after the following statements?

m = ['July', 'September', 'December']


n = m[1]
print(n)

a. [‘July’, ‘September’, ‘December’]


b. July
c. September
d. December

17. What will be the output after the following statements?

m = [45, 51, 67]


n = m[2]
print(n)

a. 67
b. 51
c. [45, 51, 67]
d. 45

18. What will be the output after the following statements?

m = [75, 23, 64]


n = m[0] + m[1]
print(n)

a. 75
b. 23
c. 64
d. 98

19. What will be the output after the following statements?


m = ['July', 'September', 'December']
n = m[0] + m[2]
print(n)

a. July
b. JulyDecember
c. JulySeptember
d. SeptemberDecember

20. What will be the output after the following statements?

m = 17
n = 5
o = m * n
print(o)

a. m * n
b. 17
c. 85
d. 5

21. What will be the output after the following statements?

m = [25, 34, 70, 63]


n = m[2] - m[0]
print(n)

a. 25
b. 45
c. 70
d. 34

22. What will be the output after the following statements?

m = [25, 34, 70, 63]


n = str(m[1]) +str(m[2])
print(n)

a. 2534
b. 95
c. 104
d. 3470

23. What will be the data type of m after the following statement?

m = [90, 'A', 115, 'B', 250]

a. List
b. String
c. Dictionary
d. Tuple

24. What will be the data type of m after the following statement?

m = 'World Wide Web'

a. List
b. String
c. Dictionary
d. Tuple

25. What will be the data type of m after the following statement?

m = {'Listen' :'Music', 'Play' : 'Games'}

a. List
b. Set
c. Dictionary
d. Tuple

26. What will be the data type of m after the following statement?

m = {'A', 'F', 'R', 'Y'}

a. List
b. Set
c. Dictionary
d. Tuple

27. What will be the data type of m after the following statement?

m = True

a. List
b. String
c. Dictionary
d. Boolean

28. What will be the data type of m after the following statements?

true = "Honesty is the best policy"


m = true

a. List
b. String
c. Dictionary
d. Boolean

29. What will be the output after the following statements?

m = {'Listen' :'Music', 'Play' : 'Games'}


print(m.keys())

a. dict_keys([‘Listen’, ‘Play’])
b. dict_keys([‘Music’, ‘Games’])
c. dict_keys({‘Listen’ :‘Music’, ‘Play’ : ‘Games’})
d. dict_keys({‘Listen’ : ‘Games’})

30. What will be the output after the following statements?

m = {'Listen' :'Music', 'Play' : 'Games'}


print(m.values())

a. dict_keys([‘Listen’, ‘Play’])
b. dict_values([‘Music’, ‘Games’])
c. dict_values({‘Listen’ :‘Music’, ‘Play’ : ‘Games’})
d. dict_values({‘Listen’ : ‘Games’})

31. What will be the output after the following statements?

m = {'Listen' :'Music', 'Play' : 'Games'}


n = m['Play']
print(n)

a. Listen
b. Music
c. Play
d. Games

32. What will be the output after the following statements?

m = {'Listen' :'Music', 'Play' : 'Games'}


n = list(m.values())
print(n[0])

a. Listen
b. Music
c. Play
d. Games

33. What will be the output after the following statements?

m = {'Listen' :'Music', 'Play' : 'Games'}


n = list(m.items())
print(n)

a. [(‘Play’, ‘Games’), (‘Listen’, ‘Music’)]


b. [(‘Listen’, ‘Music’)]
c. [(‘Play’, ‘Games’)]
d. (‘Play’, ‘Games’), (‘Listen’, ‘Music’)

34. What will be the output after the following statements?

m = 36
if m > 19:
print(100)

a. 36
b. 19
c. 100
d. m

35. What will be the output after the following statements?

m = 50
if m > 50:
print(25)
else:
print(75)

a. 50
b. m
c. 75
d. 25

36. What will be the output after the following statements?

m = 8
if m > 7:
print(50)
elif m == 7:
print(60)
else:
print(70)

a. 50
b. 60
c. 70
d. 8

37. What will be the output after the following statements?

m = 85
n = 17
print(m / n)
a. 5
b. 5.5
c. 6.0
d. 5.0

38. What will be the output after the following statements?

m = 44
n = 23
m = m + n
print(m)

a. 23
b. 44
c. 67
d. m + n

39. What will be the output after the following statements?

m = 20
n = 6
m = m * n
print(m)

a. m * n
b. 20
c. 206
d. 120

40. What will be the output after the following statements?

m = 99
n = 11
m = m - n
print(m)

a. 88
b. 11
c. 99
d. 9911
41. What will be the output after the following statements?

m = 70
n = 10
m = m % n
print(m)

a. 7
b. 70
c. 10
d. 0

42. What will be the output after the following statements?

m = 57
n = 19
o = m == n
print(o)

a. 19
b. True
c. False
d. 57

43. What will be the output after the following statements?

m = 33
if m > 33:
print('A')
elif m == 30:
print('B')
else:
print('C')

a. C
b. B
c. A
d. 33

44. What will be the output after the following statements?


m = 99
if m > 9 and m < 19:
print('AA')
elif m > 19 and m < 39:
print('BB')
elif m > 39 and m < 59:
print('CC')
else:
print('DD')

a. CC
b. DD
c. BB
d. AA

45. What will be the output after the following statements?

m = 200
if m <= 25 or m >= 200:
print('AA')
elif m <= 45 or m >= 150:
print('BB')
elif m <= 65 or m >= 100:
print('CC')
else:
print('DD')

a. CC
b. DD
c. BB
d. AA

46. What will be the output after the following statements?

m = 6
while m < 11:
print(m, end='')
m = m + 1

a. 6789
b. 5678910
c. 678910
d. 56789
47. What will be the output after the following statements?

m = 2
while m < 5:
print(m, end='')
m += 2

a. 24
b. 246
c. 2468
d. 248

48. What will be the output after the following statements?

m = 1
n = 5
while n + m < 8:
m += 1
print(m, end='')

a. 123
b. 23
c. 234
d. 2345

49. What will be the output after the following statements?

m, n = 2, 5
while n < 10:
print(n, end='')
m, n = n, m + n

a. 25
b. 58
c. 579
d. 57

50. What will be the output after the following statements?


m = 'ABC'
for i in m:
print(i, end=' ')

a. A
b. ABC
c. A B C
d. I

51. What will be the output after the following statements?

for m in range(7):
print(m, end='')

a. 0123456
b. 01234567
c. 123456
d. 1234567

52. What will be the output after the following statements?

for m in range(6,9):
print(m, end='')

a. 67
b. 678
c. 6789
d. 5678

53. What will be the output after the following statements?

for m in range(2,9,3):
print(m, end='')

a. 293
b. 369
c. 239
d. 258
54. What will be the output after the following statements?

m = ('m', 'n', 'o', 'p')


for n in m:
print(n, end=' ')

a. n
b. mnop
c. m n o p
d. (‘m’, ‘n’, ‘o’, ‘p’)

55. What will be the output after the following statements?

m = {'m', 'n', 'o', 'p'}


if 'n' in m:
print('n', end=' ')

a. n
b. mnop
c. m n o p
d. {‘m’, ‘n’, ‘o’, ‘p’}

56. What will be the output after the following statements?

m = {45 : 75, 55 : 85}


for i in m:
print(i, end=' ')

a. 45 : 75
b. 45 55
c. 55 : 85
d. 75 85

57. What will be the output after the following statements?

m = {45 : 75, 55 : 85}


for n, o in m.items():
print(n, o, end=' ')

a. 45 : 75, 55 : 85
b. {45 : 75, 55 : 85}
c. 45 55 75 85
d. 45 75 55 85

58. What will be the output after the following statements?

for m in range(6,9):
print(m, end='')
if m == 8:
break

a. 67
b. 679
c. 678
d. 6789

59. What will be the output after the following statements?

for m in range(6,9):
if m == 8:
continue
print(m, end='')

a. 67
b. 679
c. 678
d. 6789

60. What will be the output after the following statements?

m = [15, 65, 105]


n = 5 in m
print(n)

a. 15
b. [15, 65, 105]
c. True
d. False

61. What will be the output after the following statements?


m = 18
def nop() :
print(m)
nop()

a. m
b. nop
c. 18
d. mnop

62. What will be the output after the following statements?

def abc(m, n) :
print(m - n)
abc(14, 5)

a. (14, 5)
b. 145
c. m - n
d. 9

63. What will be the output after the following statements?

def abc(m=15, n=10, o=5) :


print(m * n + o)
abc()

a. 150
b. 155
c. 0
d. 225

64. What will be the output after the following statements?

def abc(m, n) :
return m * n
print(abc(7, 3))

a. 21
b. 7, 3
c. (7, 3)
d. m * n

65. What will be the output after the following statements?

def p(m, n) :
return m / n
o = p(50, 5)
print(o)

a. 5
b. 50 / 5
c. 10.0
d. 10

66. What will be the output after the following statements?

m = {'Listen' :'Music', 'Play' : 'Games'}


n = m['Music']
print(n)

a. Music
b. KeyError
c. m[‘Music’]
d. Listen

67. What will be the output after the following statements?

m = lambda n: n**3
print(m(6))

a. 6
b. 18
c. 36
d. 216

68. What does the following statement do?

import os
a. Displays the operating system name and version
b. Imports the os module
c. Imports the os function
d. Imports the directory named os

69. What will be the output after the following statements?

m = 'Play'
n = 'Games'
print(n + m)

a. Play
b. Games
c. PlayGames
d. GamesPlay

70. What will be the output after the following statements?

m = 'Play'
n = m * 2
print(n)

a. PlayPlay
b. Play
c. Play2
d. Play*2

71. What will be the output after the following statements?

m = 'Play Games'
n = m[6]
print(n)

a. m[6]
b. Play Games
c. a
d. G

72. What will be the output after the following statements?


m = 'Play Games'
n = m[7:9]
print(n)

a. ame
b. Play Games
c. Game
d. me

73. What will be the output after the following statements?

m = 'Play Games'
n = m[:]
print(n)

a. ame
b. Play Games
c. Play
d. Games

74. What does the following statement do?

m = open('games.txt', 'r')

a. Opens an existing text file named games.txt to read


b. Opens an existing text file named games.txt to write
c. Opens a new file named games.txt to read
d. Opens an existing text file named games.txt to append

75. What does the following statement do?

m = open('games.txt', 'w')

a. Opens a new file named games.txt to write


b. Opens or creates a text file named games.txt to write
c. Opens or creates a text file named games.txt to read
d. Opens or creates a text file named games.txt to append
76. What does the following statement do?

x = open('games.txt', 'a')

a. Opens a new file named games.txt to append


b. Opens or creates a text file named games.txt to write
c. Opens or creates a text file named games.txt to read
d. Opens or creates a text file named games.txt to append

77. Who is the creator of Python?

a. Albert Einstein
b. Monty Python
c. Leonardo da Vinci
d. Guido Van Rossum

78. What will be the output after the following statements?

m = False
n = True
o = False
print(m and n and o)

a. m and n
b. True
c. False
d. Error

79. In the order of precedence, which of the operation will be completed first in the
following statement?

7 * 4 + 9 - 2 / 3

a. Addition
b. Subtraction
c. Multiplication
d. Division

80. In the order of precedence, which of the operation will be completed last in the
following statement?
7 * 4 + 9 - 2 / 3

a. Addition
b. Subtraction
c. Multiplication
d. Division

81. What will be the output after the following statements?

m = 36 / 4 % 2 * 5**3
print(m)

a. 125.0
b. 0
c. 36
d. 14.0

82. What will be the output after the following statements?

m = 8 / 4 * 10 + 6 **2
print(m)

a. 32
b. 45.0
c. 56.0
d. 0.0

83. What will be the output after the following statements?

m = [4, 8]
print(m * 3)

a. [4, 8]
b. [4, 8, 4, 8]
c. [4, 8] * 3
d. [4, 8, 4, 8, 4, 8]
84. What will be the output after the following statements?

m = 67
n = m
m = 72
print(m, n)

a. 67 72
b. 72 67
c. 7267
d. 72 72

85. What will be the output after the following statements?

m = 20 * 10 // 30
n = 20 * 10.0 // 40
o = 20.0 * 10 / 50
print(m, n, o)

a. 6.5 5.0 4.5


b. 6.0 5.0 4
c. 5 6.0 4.0
d. 6 5.0 4.0

86. What will be the output after the following statements?

m = 2
for n in range(3, 15, 5):
n += m + 2
print(n)

a. 14
b. 16
c. 17
d. 19

87. What will be the output after the following statements?

m = False
print(m or not m)
a. a
b. False
c. not a
d. True

88. What will be the output after the following statements?

m = min(50, 25, 65, 0, 99)


print(m)

a. 0
b. 99
c. 25
d. (50, 25, 65, 0, 99)

89. What will be the output after the following statements?

m = [50, 25, 65, 0, 99]


n = max(m)
print(n)

a. 0
b. 99
c. 25
d. (50, 25, 65, 0, 99)

90. How many times will “Music” be printed after the following statements?

for i in range(3, 7):


print('Music')

a. 3
b. 4
c. 5
d. 6

91. What will be the output after the following statements?


m = 39
n = 61
o = (m + n) // 2
print(o)

a. 40.0
b. 50.0
c. 50
d. 55

92. What will be the output after the following statements?

m = 10*10**1
print(m)

a. 10
b. 1
c. 1000
d. 100

93. What will be the output after the following statements?

m = []
for n in range(6):
m.append(n*3)
print(m)

a. [3, 6, 9, 12, 15]


b. [0, 3, 6, 9, 12]
c. [0, 3, 6, 9, 12, 15]
d. []

94. What will be the output after the following statements?

m = [n*4 for n in range(3)]


print(m)

a. [0, 0, 0]
b. [0, 4, 8]
c. [0, 4, 8, 12]
d. [0, 4, 8, 12, 16]

95. What will be the output after the following statements?

m = [-5, -2, 0, 3, 4]
print([n*2 for n in m])

a. [-10, -4, 0, 6, 8]
b. [10, 4, 0, 6, 8]
c. [-10, -4, 0, 6]
d. [-10, -4, 0]

96. What will be the output after the following statements?

m = [5, 10, 35]


del m[:]
print(m)

a. [5, 10, 35]


b. []
c. [5, 35]
d. 5, 10, 35

97. What will be the output after the following statements?

m = 'A'
n = 'B'
o = 'C'
p = [m, n, o]
print(p)

a. [‘C’, ‘B’, ‘A’]


b. ‘C’, ‘A’, ‘B’
c. [‘C’, ‘A’, ‘B’]
d. [‘A’, ‘B’, ‘C’]

98. What will be the output after the following statements?

m = list(range(7,10))
print(m)
a. [7, 8, 9, 10]
b. list([7, 8, 9])
c. [7, 8, 9]
d. 789

99. What will be the output after the following statements?

m = [10, 25, 35]


n = sum(m)
print(n)

a. 35
b. 25
c. 10
d. 70

100. What will be the output after the following statements?

m = ['Games', 'in', 'Python']


n = 'Play' + m[0] + m[1] + m[2]
print(n)

a. PlayGamesinPython
b. Play Games in Python
c. Games in Python
d. GamesinPython

101. What will be the output after the following statements?

m = ['Play']
n = ['Games', 'in', 'Python']
o = m + n
print(o)

a. [‘Games’, ‘in’, ‘Python’, ‘Play’]


b. [‘Play Games’, ‘in’, ‘Python’]
c. [‘Play’, ‘Games’, ‘in’, ‘Python’]
d. [‘PlayGames’, ‘in’, ‘Python’]
Answer Key
1. c
2. a
3. b
4. a
5. b
6. c
7. b
8. a
9. d
10. d
11. a
12. c
13. d
14. b
15. c
16. c
17. a
18. d
19. b
20. c
21. b
22. d
23. a
24. b
25. c
26. b
27. d
28. b
29. a
30. b
31. d
32. b
33. a
34. c
35. c
36. a
37. d
38. c
39. d
40. a
41. d
42. c
43. a
44. b
45. d
46. c
47. a
48. b
49. d
50. c
51. a
52. b
53. d
54. c
55. a
56. b
57. d
58. c
59. a
60. d
61. c
62. d
63. b
64. a
65. c
66. b
67. d
68. b
69. d
70. a
71. c
72. d
73. b
74. a
75. b
76. d
77. d
78. c
79. c
80. b
81. a
82. c
83. d
84. b
85. d
86. c
87. d
88. a
89. b
90. b
91. c
92. d
93. c
94. b
95. a
96. b
97. d
98. c
99. d
100. a
101. c
Join Telegram Group click here

6th Sem all subject MCQs: click here

Download pdfs: click here

Happy Learning!
Python MCQ

1. What will be the output after the following statements?

m = 28
n = 5
print(m // n)

a. 5.0
b. 6
c. 5
d. 4.0

2. What will be the output after the following statements?

m = 90
n = 7
print(m % n)

a. 6
b. 4
c. 6.0
d. 5.0

3. What will be the output after the following statements?

m = 79
n = 64
print(m < n)

a. m < n
b. False
c. True
d. No

4. What will be the output after the following statements?


m = 92
n = 35
print(m > n)

a. True
b. False
c. Yes
d. No

5. What will be the output after the following statements?

m = False
n = True
print(m and n)

a. m and n
b. False
c. True
d. mn

6. What will be the output after the following statements?

m = True
n = False
print(m or n)

a. m or n
b. False
c. True
d. mn

7. What will be the output after the following statements?

m = True
n = False
print(not m)

a. not m
b. False
c. True
d. Not defined

8. What will be the output after the following statements?

m = True
n = False
print('not n')

a. not n
b. False
c. True
d. Not defined

9. What will be the output after the following statements?

m = 7 * 5 + 8
print(m)

a. 91
b. 20
c. 47
d. 43

10. What will be the output after the following statements?

m = 9 * (3 + 12)
print(m)

a. 45
b. 159
c. 95
d. 135

11. What will be the output after the following statements?

m = '40' + '01'
print(m)
a. 4001
b. 01
c. 41
d. 40

12. What will be the output after the following statements?

m = 81 + 34
print(m)

a. 8134
b. 81
c. 115
d. 34

13. What will be the data type of n after the following statements if the user entered the
number 45?

m = input('Enter a number: ')


n = int(m)

a. Float
b. String
c. List
d. Integer

14. What is the data type of m after the following statement?

m = (41, 54, 23, 68)

a. Dictionary
b. Tuple
c. String
d. List

15. What is the data type of m after the following statement?

m = ['July', 'September', 'December']


a. Dictionary
b. Tuple
c. List
d. String

16. What will be the output after the following statements?

m = ['July', 'September', 'December']


n = m[1]
print(n)

a. [‘July’, ‘September’, ‘December’]


b. July
c. September
d. December

17. What will be the output after the following statements?

m = [45, 51, 67]


n = m[2]
print(n)

a. 67
b. 51
c. [45, 51, 67]
d. 45

18. What will be the output after the following statements?

m = [75, 23, 64]


n = m[0] + m[1]
print(n)

a. 75
b. 23
c. 64
d. 98

19. What will be the output after the following statements?


m = ['July', 'September', 'December']
n = m[0] + m[2]
print(n)

a. July
b. JulyDecember
c. JulySeptember
d. SeptemberDecember

20. What will be the output after the following statements?

m = 17
n = 5
o = m * n
print(o)

a. m * n
b. 17
c. 85
d. 5

21. What will be the output after the following statements?

m = [25, 34, 70, 63]


n = m[2] - m[0]
print(n)

a. 25
b. 45
c. 70
d. 34

22. What will be the output after the following statements?

m = [25, 34, 70, 63]


n = str(m[1]) +str(m[2])
print(n)

a. 2534
b. 95
c. 104
d. 3470

23. What will be the data type of m after the following statement?

m = [90, 'A', 115, 'B', 250]

a. List
b. String
c. Dictionary
d. Tuple

24. What will be the data type of m after the following statement?

m = 'World Wide Web'

a. List
b. String
c. Dictionary
d. Tuple

25. What will be the data type of m after the following statement?

m = {'Listen' :'Music', 'Play' : 'Games'}

a. List
b. Set
c. Dictionary
d. Tuple

26. What will be the data type of m after the following statement?

m = {'A', 'F', 'R', 'Y'}

a. List
b. Set
c. Dictionary
d. Tuple

27. What will be the data type of m after the following statement?

m = True

a. List
b. String
c. Dictionary
d. Boolean

28. What will be the data type of m after the following statements?

true = "Honesty is the best policy"


m = true

a. List
b. String
c. Dictionary
d. Boolean

29. What will be the output after the following statements?

m = {'Listen' :'Music', 'Play' : 'Games'}


print(m.keys())

a. dict_keys([‘Listen’, ‘Play’])
b. dict_keys([‘Music’, ‘Games’])
c. dict_keys({‘Listen’ :‘Music’, ‘Play’ : ‘Games’})
d. dict_keys({‘Listen’ : ‘Games’})

30. What will be the output after the following statements?

m = {'Listen' :'Music', 'Play' : 'Games'}


print(m.values())

a. dict_keys([‘Listen’, ‘Play’])
b. dict_values([‘Music’, ‘Games’])
c. dict_values({‘Listen’ :‘Music’, ‘Play’ : ‘Games’})
d. dict_values({‘Listen’ : ‘Games’})

31. What will be the output after the following statements?

m = {'Listen' :'Music', 'Play' : 'Games'}


n = m['Play']
print(n)

a. Listen
b. Music
c. Play
d. Games

32. What will be the output after the following statements?

m = {'Listen' :'Music', 'Play' : 'Games'}


n = list(m.values())
print(n[0])

a. Listen
b. Music
c. Play
d. Games

33. What will be the output after the following statements?

m = {'Listen' :'Music', 'Play' : 'Games'}


n = list(m.items())
print(n)

a. [(‘Play’, ‘Games’), (‘Listen’, ‘Music’)]


b. [(‘Listen’, ‘Music’)]
c. [(‘Play’, ‘Games’)]
d. (‘Play’, ‘Games’), (‘Listen’, ‘Music’)

34. What will be the output after the following statements?

m = 36
if m > 19:
print(100)

a. 36
b. 19
c. 100
d. m

35. What will be the output after the following statements?

m = 50
if m > 50:
print(25)
else:
print(75)

a. 50
b. m
c. 75
d. 25

36. What will be the output after the following statements?

m = 8
if m > 7:
print(50)
elif m == 7:
print(60)
else:
print(70)

a. 50
b. 60
c. 70
d. 8

37. What will be the output after the following statements?

m = 85
n = 17
print(m / n)
a. 5
b. 5.5
c. 6.0
d. 5.0

38. What will be the output after the following statements?

m = 44
n = 23
m = m + n
print(m)

a. 23
b. 44
c. 67
d. m + n

39. What will be the output after the following statements?

m = 20
n = 6
m = m * n
print(m)

a. m * n
b. 20
c. 206
d. 120

40. What will be the output after the following statements?

m = 99
n = 11
m = m - n
print(m)

a. 88
b. 11
c. 99
d. 9911
41. What will be the output after the following statements?

m = 70
n = 10
m = m % n
print(m)

a. 7
b. 70
c. 10
d. 0

42. What will be the output after the following statements?

m = 57
n = 19
o = m == n
print(o)

a. 19
b. True
c. False
d. 57

43. What will be the output after the following statements?

m = 33
if m > 33:
print('A')
elif m == 30:
print('B')
else:
print('C')

a. C
b. B
c. A
d. 33

44. What will be the output after the following statements?


m = 99
if m > 9 and m < 19:
print('AA')
elif m > 19 and m < 39:
print('BB')
elif m > 39 and m < 59:
print('CC')
else:
print('DD')

a. CC
b. DD
c. BB
d. AA

45. What will be the output after the following statements?

m = 200
if m <= 25 or m >= 200:
print('AA')
elif m <= 45 or m >= 150:
print('BB')
elif m <= 65 or m >= 100:
print('CC')
else:
print('DD')

a. CC
b. DD
c. BB
d. AA

46. What will be the output after the following statements?

m = 6
while m < 11:
print(m, end='')
m = m + 1

a. 6789
b. 5678910
c. 678910
d. 56789
47. What will be the output after the following statements?

m = 2
while m < 5:
print(m, end='')
m += 2

a. 24
b. 246
c. 2468
d. 248

48. What will be the output after the following statements?

m = 1
n = 5
while n + m < 8:
m += 1
print(m, end='')

a. 123
b. 23
c. 234
d. 2345

49. What will be the output after the following statements?

m, n = 2, 5
while n < 10:
print(n, end='')
m, n = n, m + n

a. 25
b. 58
c. 579
d. 57

50. What will be the output after the following statements?


m = 'ABC'
for i in m:
print(i, end=' ')

a. A
b. ABC
c. A B C
d. I

51. What will be the output after the following statements?

for m in range(7):
print(m, end='')

a. 0123456
b. 01234567
c. 123456
d. 1234567

52. What will be the output after the following statements?

for m in range(6,9):
print(m, end='')

a. 67
b. 678
c. 6789
d. 5678

53. What will be the output after the following statements?

for m in range(2,9,3):
print(m, end='')

a. 293
b. 369
c. 239
d. 258
54. What will be the output after the following statements?

m = ('m', 'n', 'o', 'p')


for n in m:
print(n, end=' ')

a. n
b. mnop
c. m n o p
d. (‘m’, ‘n’, ‘o’, ‘p’)

55. What will be the output after the following statements?

m = {'m', 'n', 'o', 'p'}


if 'n' in m:
print('n', end=' ')

a. n
b. mnop
c. m n o p
d. {‘m’, ‘n’, ‘o’, ‘p’}

56. What will be the output after the following statements?

m = {45 : 75, 55 : 85}


for i in m:
print(i, end=' ')

a. 45 : 75
b. 45 55
c. 55 : 85
d. 75 85

57. What will be the output after the following statements?

m = {45 : 75, 55 : 85}


for n, o in m.items():
print(n, o, end=' ')

a. 45 : 75, 55 : 85
b. {45 : 75, 55 : 85}
c. 45 55 75 85
d. 45 75 55 85

58. What will be the output after the following statements?

for m in range(6,9):
print(m, end='')
if m == 8:
break

a. 67
b. 679
c. 678
d. 6789

59. What will be the output after the following statements?

for m in range(6,9):
if m == 8:
continue
print(m, end='')

a. 67
b. 679
c. 678
d. 6789

60. What will be the output after the following statements?

m = [15, 65, 105]


n = 5 in m
print(n)

a. 15
b. [15, 65, 105]
c. True
d. False

61. What will be the output after the following statements?


m = 18
def nop() :
print(m)
nop()

a. m
b. nop
c. 18
d. mnop

62. What will be the output after the following statements?

def abc(m, n) :
print(m - n)
abc(14, 5)

a. (14, 5)
b. 145
c. m - n
d. 9

63. What will be the output after the following statements?

def abc(m=15, n=10, o=5) :


print(m * n + o)
abc()

a. 150
b. 155
c. 0
d. 225

64. What will be the output after the following statements?

def abc(m, n) :
return m * n
print(abc(7, 3))

a. 21
b. 7, 3
c. (7, 3)
d. m * n

65. What will be the output after the following statements?

def p(m, n) :
return m / n
o = p(50, 5)
print(o)

a. 5
b. 50 / 5
c. 10.0
d. 10

66. What will be the output after the following statements?

m = {'Listen' :'Music', 'Play' : 'Games'}


n = m['Music']
print(n)

a. Music
b. KeyError
c. m[‘Music’]
d. Listen

67. What will be the output after the following statements?

m = lambda n: n**3
print(m(6))

a. 6
b. 18
c. 36
d. 216

68. What does the following statement do?

import os
a. Displays the operating system name and version
b. Imports the os module
c. Imports the os function
d. Imports the directory named os

69. What will be the output after the following statements?

m = 'Play'
n = 'Games'
print(n + m)

a. Play
b. Games
c. PlayGames
d. GamesPlay

70. What will be the output after the following statements?

m = 'Play'
n = m * 2
print(n)

a. PlayPlay
b. Play
c. Play2
d. Play*2

71. What will be the output after the following statements?

m = 'Play Games'
n = m[6]
print(n)

a. m[6]
b. Play Games
c. a
d. G

72. What will be the output after the following statements?


m = 'Play Games'
n = m[7:9]
print(n)

a. ame
b. Play Games
c. Game
d. me

73. What will be the output after the following statements?

m = 'Play Games'
n = m[:]
print(n)

a. ame
b. Play Games
c. Play
d. Games

74. What does the following statement do?

m = open('games.txt', 'r')

a. Opens an existing text file named games.txt to read


b. Opens an existing text file named games.txt to write
c. Opens a new file named games.txt to read
d. Opens an existing text file named games.txt to append

75. What does the following statement do?

m = open('games.txt', 'w')

a. Opens a new file named games.txt to write


b. Opens or creates a text file named games.txt to write
c. Opens or creates a text file named games.txt to read
d. Opens or creates a text file named games.txt to append
76. What does the following statement do?

x = open('games.txt', 'a')

a. Opens a new file named games.txt to append


b. Opens or creates a text file named games.txt to write
c. Opens or creates a text file named games.txt to read
d. Opens or creates a text file named games.txt to append

77. Who is the creator of Python?

a. Albert Einstein
b. Monty Python
c. Leonardo da Vinci
d. Guido Van Rossum

78. What will be the output after the following statements?

m = False
n = True
o = False
print(m and n and o)

a. m and n
b. True
c. False
d. Error

79. In the order of precedence, which of the operation will be completed first in the
following statement?

7 * 4 + 9 - 2 / 3

a. Addition
b. Subtraction
c. Multiplication
d. Division

80. In the order of precedence, which of the operation will be completed last in the
following statement?
7 * 4 + 9 - 2 / 3

a. Addition
b. Subtraction
c. Multiplication
d. Division

81. What will be the output after the following statements?

m = 36 / 4 % 2 * 5**3
print(m)

a. 125.0
b. 0
c. 36
d. 14.0

82. What will be the output after the following statements?

m = 8 / 4 * 10 + 6 **2
print(m)

a. 32
b. 45.0
c. 56.0
d. 0.0

83. What will be the output after the following statements?

m = [4, 8]
print(m * 3)

a. [4, 8]
b. [4, 8, 4, 8]
c. [4, 8] * 3
d. [4, 8, 4, 8, 4, 8]
84. What will be the output after the following statements?

m = 67
n = m
m = 72
print(m, n)

a. 67 72
b. 72 67
c. 7267
d. 72 72

85. What will be the output after the following statements?

m = 20 * 10 // 30
n = 20 * 10.0 // 40
o = 20.0 * 10 / 50
print(m, n, o)

a. 6.5 5.0 4.5


b. 6.0 5.0 4
c. 5 6.0 4.0
d. 6 5.0 4.0

86. What will be the output after the following statements?

m = 2
for n in range(3, 15, 5):
n += m + 2
print(n)

a. 14
b. 16
c. 17
d. 19

87. What will be the output after the following statements?

m = False
print(m or not m)
a. a
b. False
c. not a
d. True

88. What will be the output after the following statements?

m = min(50, 25, 65, 0, 99)


print(m)

a. 0
b. 99
c. 25
d. (50, 25, 65, 0, 99)

89. What will be the output after the following statements?

m = [50, 25, 65, 0, 99]


n = max(m)
print(n)

a. 0
b. 99
c. 25
d. (50, 25, 65, 0, 99)

90. How many times will “Music” be printed after the following statements?

for i in range(3, 7):


print('Music')

a. 3
b. 4
c. 5
d. 6

91. What will be the output after the following statements?


m = 39
n = 61
o = (m + n) // 2
print(o)

a. 40.0
b. 50.0
c. 50
d. 55

92. What will be the output after the following statements?

m = 10*10**1
print(m)

a. 10
b. 1
c. 1000
d. 100

93. What will be the output after the following statements?

m = []
for n in range(6):
m.append(n*3)
print(m)

a. [3, 6, 9, 12, 15]


b. [0, 3, 6, 9, 12]
c. [0, 3, 6, 9, 12, 15]
d. []

94. What will be the output after the following statements?

m = [n*4 for n in range(3)]


print(m)

a. [0, 0, 0]
b. [0, 4, 8]
c. [0, 4, 8, 12]
d. [0, 4, 8, 12, 16]

95. What will be the output after the following statements?

m = [-5, -2, 0, 3, 4]
print([n*2 for n in m])

a. [-10, -4, 0, 6, 8]
b. [10, 4, 0, 6, 8]
c. [-10, -4, 0, 6]
d. [-10, -4, 0]

96. What will be the output after the following statements?

m = [5, 10, 35]


del m[:]
print(m)

a. [5, 10, 35]


b. []
c. [5, 35]
d. 5, 10, 35

97. What will be the output after the following statements?

m = 'A'
n = 'B'
o = 'C'
p = [m, n, o]
print(p)

a. [‘C’, ‘B’, ‘A’]


b. ‘C’, ‘A’, ‘B’
c. [‘C’, ‘A’, ‘B’]
d. [‘A’, ‘B’, ‘C’]

98. What will be the output after the following statements?

m = list(range(7,10))
print(m)
a. [7, 8, 9, 10]
b. list([7, 8, 9])
c. [7, 8, 9]
d. 789

99. What will be the output after the following statements?

m = [10, 25, 35]


n = sum(m)
print(n)

a. 35
b. 25
c. 10
d. 70

100. What will be the output after the following statements?

m = ['Games', 'in', 'Python']


n = 'Play' + m[0] + m[1] + m[2]
print(n)

a. PlayGamesinPython
b. Play Games in Python
c. Games in Python
d. GamesinPython

101. What will be the output after the following statements?

m = ['Play']
n = ['Games', 'in', 'Python']
o = m + n
print(o)

a. [‘Games’, ‘in’, ‘Python’, ‘Play’]


b. [‘Play Games’, ‘in’, ‘Python’]
c. [‘Play’, ‘Games’, ‘in’, ‘Python’]
d. [‘PlayGames’, ‘in’, ‘Python’]
Answer Key

1. c
2. a
3. b
4. a
5. b
6. c
7. b
8. a
9. d
10. d
11. a
12. c
13. d
14. b
15. c
16. c
17. a
18. d
19. b
20. c
21. b
22. d
23. a
24. b
25. c
26. b
27. d
28. b
29. a
30. b
31. d
32. b
33. a
34. c
35. c
36. a
37. d
38. c
39. d
40. a
41. d
42. c
43. a
44. b
45. d
46. c
47. a
48. b
49. d
50. c
51. a
52. b
53. d
54. c
55. a
56. b
57. d
58. c
59. a
60. d
61. c
62. d
63. b
64. a
65. c
66. b
67. d
68. b
69. d
70. a
71. c
72. d
73. b
74. a
75. b
76. d
77. d
78. c
79. c
80. b
81. a
82. c
83. d
84. b
85. d
86. c
87. d
88. a
89. b
90. b
91. c
92. d
93. c
94. b
95. a
96. b
97. d
98. c
99. d
100. a
101. c

You might also like