Python Quiz-4

Q1. Which of the following statement will read entire content of a text file as string?

  1. txtfile = open(‘a.txt’, ‘r’)
    txtfile.read()
  2. txtfile = open(‘a.txt’, ‘r’)
    txtfile.readline()
  3. txtfile = open(‘a.txt’, ‘r’)
    txtfile.readlines()
  4. txtfile = open(‘a.txt’, ‘r’)
    txtfile.reads()

Answer: 1
Explanation: txtfile.read() Read at most n characters from stream. This method will read from underlying buffer until we have n characters or we hit End of file. If n is negative or omitted, read until End of file.

Q2. Which of the following creates iterable elements?

  1. continue
  2. range
  3. break
  4. pass

Answer: 2
Explanation: range(stop) -> range object
range(start, stop[, step]) -> range object
Return an object that produces a sequence of integers from start (inclusive)to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, …, j-1. start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3. These are exactly the valid indices for a list of 4 elements. When step is given, it specifies the increment (or decrement).

Q3. Which of the following is default mode in open() function?

  1. ‘a’ – append
  2. ‘w’ – write
  3. ‘r’ – read
  4. ‘x’ – create

Answer: 3
Explanation: ‘r’ => open for reading (default).

Q4. In s1 = “theai” and s2 = “learner”. Output of the print(2*s1[:2]+s2) will be:

  1. thethelearner
  2. eelearner
  3. thlearner
  4. ththlearner

Answer: 4
Explanation: => print(2*s1[:2]+s2)
=> print(2*’th’+s2)
=> print(‘thth’+s2)
=> print(‘ththlearner’)
=> ththlearner

Q5. In Python scope, what does LEGB rule stands for?

  1. Local, Enclosed, Global, and Basic
  2. Local, Enclosing, General, and Built-in
  3. Local, Enclosing, Global, and Basic
  4. Local, Enclosing, Global, and Built-in

Q6. In Python, which of the following rule is used to decide the order in which the namespaces are to be searched for scope resolution?

  1. LEGB rule (Local, Enclosed, General, Built-in)
  2. LEGB rule (Local, Enclosed, Global, Built-in)
  3. ELGB rule (Enclosed, Local, Global, Built-in)
  4. ELGB rule (Enclosed, Local, Genral, Built-in)

Answer: 1
Explanation: Since x1 and x2 refers to the same object in the memory, adding the items in the x2 will also add items in x1.

Q8. if x = [2, 4, 6, 8], which of the following operation will change x to [2, 4, 8]?

  1. del x[2]
  2. x.remove(6)
  3. x[2:3] = []
  4. All of the above!

Answer: 4
Explanation: del x[2] => will delete the item at index 2.
x.remove(6) => will remove the first occurance of value 6.
x[2:3] = [] => will replace the value at index 2 to nothing.

Leave a Reply