Advanced Python Test Quiz

Approved & Edited by ProProfs Editorial Team
The editorial team at ProProfs Quizzes consists of a select group of subject experts, trivia writers, and quiz masters who have authored over 10,000 quizzes taken by more than 100 million users. This team includes our in-house seasoned quiz moderators and subject matter experts. Our editorial experts, spread across the world, are rigorously trained using our comprehensive guidelines to ensure that you receive the highest quality quizzes.
Learn about Our Editorial Process
| By Bhargav.baggi
B
Bhargav.baggi
Community Contributor
Quizzes Created: 1 | Total Attempts: 2,150
Questions: 15 | Attempts: 2,150

SettingsSettingsSettings
Advanced Python Test Quiz - Quiz

Advanced Python Test


Questions and Answers
  • 1. 

    What gets printed (with python version 3.X) assuming the user enters the following at the prompt? #: foo  a = input("#: ")   print a

    • A.

      F

    • B.

      Foo

    • C.

      Not a number

    • D.

      An exception is thrown

    Correct Answer
    B. Foo
    Explanation
    The correct answer is "foo". This is because the user input is assigned to the variable "a" using the input() function. The input() function reads a line of text from the user and returns it as a string. Therefore, when the value "foo" is entered at the prompt, it is stored in the variable "a". The print statement then outputs the value of "a", which is "foo".

    Rate this question:

  • 2. 

    What gets printed? class NumFactory:     def __init__(self, n):         self.val = n     def timesTwo(self):         self.val *= 2     def plusTwo(self):         self.val += 2   f = NumFactory(2) for m in dir(f):     mthd = getattr(f,m)     if callable(mthd):         mthd()   print f.val

    • A.

      2

    • B.

      4

    • C.

      6

    • D.

      8

    • E.

      An exception is thrown

    Correct Answer
    E. An exception is thrown
    Explanation
    The code creates an instance of the NumFactory class with an initial value of 2. It then iterates over the methods of the instance using the dir() function. For each method, it checks if the method is callable using the callable() function. If the method is callable, it calls the method. However, the code does not handle the case where the method does not exist, which results in an exception being thrown. Therefore, the correct answer is that an exception is thrown.

    Rate this question:

  • 3. 

    What gets printed? def print_header(str):     print "+++%s+++" % str     print_header.category = 1 print_header.text = "some info"   print_header("%d %s" %  \ (print_header.category, print_header.text))

    • A.

      +++1 some info+++

    • B.

      +++%s+++

    • C.

      1

    • D.

      Some info

    Correct Answer
    A. +++1 some info+++
    Explanation
    The function print_header is defined with a parameter "str". Inside the function, it prints "+++" followed by the value of "str" followed by "+++".

    Then, the function is assigned two attributes: "category" with a value of 1 and "text" with a value of "some info".

    Finally, the function is called with the arguments "%d %s" % (print_header.category, print_header.text). This will substitute the values of "print_header.category" and "print_header.text" into the string and print it.

    Therefore, the output will be "+++1 some info+++".

    Rate this question:

  • 4. 

    What gets printed? names1 = ['Amir', 'Barry', 'Chales', 'Dao'] names2 = [name.lower() for name in names1]   print names2[2][0]

    • A.

      I

    • B.

      A

    • C.

      C

    • D.

      C

    • E.

      An exception is thrown

    Correct Answer
    C. C
    Explanation
    The code creates a new list called names2, which contains all the names from names1 converted to lowercase. The expression names2[2] retrieves the third name from names2, which is "chales". The index [0] is then used to retrieve the first character of "chales", which is "c". Therefore, the correct answer is "c".

    Rate this question:

  • 5. 

    What gets printed? names1 = ['Amir', 'Barry', 'Chales', 'Dao']   loc = names1.index("Edward")   print loc

    • A.

      -1

    • B.

      0

    • C.

      4

    • D.

      Edward

    • E.

      An exception is thrown

    Correct Answer
    E. An exception is thrown
    Explanation
    The code tries to find the index of the name "Edward" in the list "names1" using the index() method. However, since "Edward" is not present in the list, the index() method will raise a ValueError exception. Therefore, the correct answer is "An exception is thrown".

    Rate this question:

  • 6. 

     Assuming the filename for the code below is /usr/lib/python/person.py and the program is run as:  python /usr/lib/python/person.py  What gets printed? class Person:     def __init__(self):         pass       def getAge(self):         print __name__   p = Person() p.getAge()

    • A.

      Person

    • B.

      GetAge

    • C.

      Usr.lib.python.person

    • D.

      __main__

    • E.

      An exception is thrown

    Correct Answer
    D. __main__
    Explanation
    The code defines a class called Person with an empty constructor and a method called getAge that prints the value of __name__. When the code is run, an instance of the Person class is created and the getAge method is called on that instance. Since the code is being run directly as the main script, the value of __name__ is "__main__", so that is what gets printed.

    Rate this question:

  • 7. 

    What gets printed? import re sum = 0   pattern = 'back' if re.match(pattern, 'backup.txt'):     sum += 1 if re.match(pattern, 'text.back'):     sum += 2 if re.search(pattern, 'backup.txt'):     sum += 4 if re.search(pattern, 'text.back'):     sum += 8   print sum

    • A.

      3

    • B.

      7

    • C.

      13

    • D.

      14

    • E.

      15

    Correct Answer
    C. 13
    Explanation
    The pattern 'back' is matched in both 'backup.txt' and 'text.back' using re.search(). Therefore, sum is increased by 4 and 8, resulting in a final value of 12.

    Rate this question:

  • 8. 

    What numbers get printed import pickle   class account:         def __init__(self, id, balance):                self.id = id                self.balance = balance         def deposit(self, amount):                self.balance += amount         def withdraw(self, amount):                self.balance -= amount   myac = account('123', 100) myac.deposit(800) myac.withdraw(500)   fd = open( "archive", "w" ) pickle.dump( myac, fd) fd.close()   myac.deposit(200) print myac.balance   fd = open( "archive", "r" ) myac = pickle.load( fd ) fd.close()   print myac.balance

    • A.

      500 300

    • B.

      500 500

    • C.

      600 400

    • D.

      600 600

    • E.

      300 500

    Correct Answer
    C. 600 400
    Explanation
    After creating an instance of the account class with an initial balance of 100, the deposit method is called with an amount of 800, increasing the balance to 900. Then, the withdraw method is called with an amount of 500, decreasing the balance to 400. The instance is then serialized using the pickle.dump() function and saved to a file named "archive". The deposit method is called again with an amount of 200, increasing the balance to 600. The balance is printed, resulting in the output "600". The file "archive" is then opened and the serialized instance is loaded using the pickle.load() function. The balance is printed again, resulting in the output "400". Therefore, the correct answer is "600 400".

    Rate this question:

  • 9. 

    What gets printed? class parent:     def __init__(self, param):         self.v1 = param   class child(parent):     def __init__(self, param):         self.v2 = param   obj = child(11) print "%d %d" % (obj.v1, obj.v2)

    • A.

      None None

    • B.

      None 11

    • C.

      11 None

    • D.

      11 11

    • E.

      Error is generated by program

    Correct Answer
    E. Error is generated by program
    Explanation
    The code will generate an error because the child class does not have an explicit call to the parent class's constructor. As a result, the parent class's constructor is not called and the variable "v1" is not initialized. Therefore, when trying to print "obj.v1", an error is generated.

    Rate this question:

  • 10. 

    The following code will successfully print the days and then the months daysOfWeek = ['Monday',               'Tuesday',               'Wednesday',               'Thursday',               'Friday',               'Saturday',               'Sunday']   months =             ['Jan', \                       'Feb', \                       'Mar', \                       'Apr', \                       'May', \                       'Jun', \                       'Jul', \                       'Aug', \                       'Sep', \                       'Oct', \                       'Nov', \                       'Dec']   print "DAYS: %s, MONTHS %s" %     (daysOfWeek, months)

    • A.

      True

    • B.

      False

    Correct Answer
    B. False
    Explanation
    The code will not successfully print the days and then the months. The reason is that there is a syntax error in the code. The print statement is missing parentheses around the arguments. It should be written as "print("DAYS: %s, MONTHS %s" % (daysOfWeek, months))" to correctly format and print the days and months.

    Rate this question:

  • 11. 

    What gets printed? x = True y = False z = False   if not x or y:     print 1 elif not x or not y and z:     print 2 elif not x or y or not y and x:     print 3 else:     print 4

    • A.

      1

    • B.

      2

    • C.

      3

    • D.

      4

    Correct Answer
    C. 3
    Explanation
    The code first checks the condition "not x or y" which evaluates to True since x is True and y is False. Therefore, the code executes the corresponding print statement and prints 1. The other conditions are not checked because the first condition is True.

    Rate this question:

  • 12. 

    In python 2.6 or earlier, the code will print error type 1 if accessSecureSystem raises an exception of either AccessError type or SecurityError type try:   accessSecureSystem() except AccessError, SecurityError:   print "error type 1"   continueWork()

    • A.

      True

    • B.

      False

    Correct Answer
    B. False
    Explanation
    The code will not print "error type 1" if accessSecureSystem raises an exception of either AccessError type or SecurityError type. The correct answer is false because the except statement should specify the exception types separately using the "as" keyword, like "except AccessError as e, SecurityError as se:".

    Rate this question:

  • 13. 

    What gets printed? kvps  = {"user","bill", "password","hillary"}   print kvps['password']

    • A.

      User

    • B.

      Bill

    • C.

      Password

    • D.

      Hillary

    • E.

      Nothing. Python syntax error

    Correct Answer
    E. Nothing. Python syntax error
    Explanation
    The given code attempts to access the value associated with the key 'password' in the dictionary kvps using the square bracket notation. However, the dictionary is initialized with incorrect syntax. The correct syntax for initializing a dictionary is using the colon (:) to separate the key-value pairs, not a comma (,). Therefore, the code will result in a Python syntax error.

    Rate this question:

  • 14. 

    What gets printed? def simpleFunction():     "This is a cool simple function that returns 1"     return 1   print simpleFunction.__doc__[10:14]

    • A.

      SimpleFunction

    • B.

      Simple

    • C.

      Func

    • D.

      Function

    • E.

      Cool

    Correct Answer
    E. Cool
    Explanation
    The code defines a function called simpleFunction that returns the value 1. The function also has a docstring, which is a string that provides a brief description of the function. The code then prints a portion of the docstring, specifically the characters at indices 10 to 14. In this case, the characters at those indices are "cool", so "cool" would be printed.

    Rate this question:

  • 15. 

    What gets printed? import re sum = 0   pattern = 'back' if re.match(pattern, 'backup.txt'):     sum += 1 if re.match(pattern, 'text.back'):     sum += 2 if re.search(pattern, 'backup.txt'):     sum += 4 if re.search(pattern, 'text.back'):     sum += 8   print sum

    • A.

      3

    • B.

      7

    • C.

      13

    • D.

      14

    • E.

      15

    Correct Answer
    C. 13
    Explanation
    The code uses regular expressions to match and search for the pattern "back" in different strings. The first if statement uses the match method to check if the pattern matches "backup.txt", which it does, so sum is incremented by 1. The second if statement uses the match method to check if the pattern matches "text.back", which it does not, so sum remains the same. The third if statement uses the search method to check if the pattern is found in "backup.txt", which it does, so sum is incremented by 4. The fourth if statement uses the search method to check if the pattern is found in "text.back", which it does, so sum is incremented by 8. Therefore, the final value of sum is 13.

    Rate this question:

Quiz Review Timeline +

Our quizzes are rigorously reviewed, monitored and continuously updated by our expert board to maintain accuracy, relevance, and timeliness.

  • Current Version
  • Aug 18, 2023
    Quiz Edited by
    ProProfs Editorial Team
  • Oct 20, 2016
    Quiz Created by
    Bhargav.baggi
Back to Top Back to top
Advertisement
×

Wait!
Here's an interesting quiz for you.

We have other quizzes matching your interest.