Advance Python Quiz - Test Your Expert Python Skills

Reviewed by Samy Boulos
Samy Boulos, MSc (Computer Science) |
Data Engineer
Review Board Member
Samy Boulos is an experienced Technology Consultant with a diverse 25-year career encompassing software development, data migration, integration, technical support, and cloud computing. He leverages his technical expertise and strategic mindset to solve complex IT challenges, delivering efficient and innovative solutions to clients.
, MSc (Computer Science)
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 Vineedk
V
Vineedk
Community Contributor
Quizzes Created: 2 | Total Attempts: 10,056
Questions: 15 | Attempts: 9,471

SettingsSettingsSettings
Advance Python Quiz - Test Your Expert Python Skills - Quiz

If you're a programmer, you likely have some knowledge of Python. Test your expertise with our 'Advanced Python Quiz Questions with Answers' and see how well you know advanced Python concepts! It's an easy and interesting way to revise your concepts and identify areas where you might need more study.

This quiz covers a wide range of topics, from complex algorithms to intricate data structures, ensuring a thorough evaluation of your Python skills. Challenge yourself today and discover how much you know about advanced Python. Take this quiz to not only test your knowledge but also to learn new Read moretechniques and deepen your understanding of this versatile programming language. Good luck and happy coding!


Advance Python Questions and Answers

  • 1. 

    Which of the following Python features allows you to define a function that can be paused and resumed, maintaining its state between executions?

    • A.

      Decorators

    • B.

      Generators

    • C.

      Context Managers

    • D.

      Lambdas

    Correct Answer
    B. Generators
    Explanation
    Generators are a feature in Python that allows you to define a function that can be paused and resumed, maintaining its state between executions. This is done using the yield statement. When the generator's function is called, it returns an iterator object but does not start execution immediately. When the next() method is called on the iterator, the function executes until it encounters the yield statement, returning the yielded value. The function can be resumed from where it left off when next() is called again.

    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 all the attributes of the instance using the dir() function. For each attribute, it checks if it is callable (a method) using the callable() function. If it is callable, it calls the method. However, there are no methods defined in the NumFactory class that can be called. Therefore, an exception is thrown when trying to call a non-existent method.

    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 called with an argument "%d %s" % (print_header.category, print_header.text). This means that the value of print_header.category is substituted for "%d" and the value of print_header.text is substituted for "%s".

    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.

      D

    • E.

      An exception is thrown

    Correct Answer
    C. C
    Explanation
    The code creates a new list called names2, which contains the lowercase versions of each name in names1. The expression names2[2] accesses the third element of names2, which is "chales". The expression names2[2][0] then accesses the first character of "chales", which is "c". Therefore, the output will be "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 attempts to find the index of "Edward" in the list names1 using the index() method. Since "Edward" is not in the list, the index() method raises a ValueError exception. As a result, the program does not print an index; instead, it throws an exception with a message indicating that "Edward" is not in the list.

    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. When the program is run, an instance of the Person class is created and the getAge method is called on that instance. The getAge method prints the value of __name__, which is a special variable that holds the name of the current module. In this case, since the program is run directly as the main module, the value of __name__ is "__main__". Therefore, the output of the program will be "__main__".

    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 given 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 the string "backup.txt", which is true. Therefore, sum is incremented by 1. The second if statement also uses the match() method, but since the pattern does not match the string "text.back", this if statement is false and does not increment sum. The third if statement uses the search() method to check if the pattern is found anywhere in the string "backup.txt", which is true. Therefore, sum is incremented by 4. The fourth if statement also uses the search() method and matches the pattern in the string "text.back", so sum is incremented by 8. The final value of sum is 13, which is printed.

    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
    The initial balance of the account is 100. Then, 800 is deposited, resulting in a balance of 900. After that, 500 is withdrawn, resulting in a balance of 400. The account balance is then increased by 200, resulting in a balance of 600. When the account is loaded from the archive file, the balance remains the same at 600. Therefore, the numbers that get printed are 600 and 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 correct answer is "Error is generated by program". This is because the child class constructor does not call the parent class constructor, so the v1 attribute of the parent class 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 given code will not successfully print the days and then the months. The code is missing a closing parenthesis ")" after "months" in the print statement. Therefore, it will result in a syntax error.

    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 will print 3. This is because the condition in the third elif statement is true. The condition is "not x or y or not y and x". Since x is True and y is False, the condition "not y and x" evaluates to True. Therefore, the print statement inside the third elif block will be executed.

    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
    In Python 2.6 or earlier, the code as written would raise a SyntaxError because the syntax used for handling multiple exceptions in a single except block is incorrect. The correct syntax for catching multiple exceptions in Python 2.6 or earlier is to use a tuple of exceptions:
    python
    Copy code
    try: accessSecureSystem() except (AccessError, SecurityError): print "error type 1" continueWork()
    With this corrected syntax, the code will print "error type 1" if accessSecureSystem raises an exception of either AccessError or SecurityError type. If no exception is raised, it will simply continue to continueWork().

    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 tries to access the value associated with the key 'password' in the dictionary kvps. However, the dictionary declaration is incorrect. In Python, dictionaries are declared using curly braces ({}) and colons (:). The correct declaration should be kvps = {'user': 'bill', 'password': 'hillary'}. Therefore, when trying to access the value using kvps['password'], it will result in a 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 provided Python code defines a function called simpleFunction with a docstring describing its purpose. The print statement extracts a specific substring (characters 10 to 13) from this docstring and prints it. In this instance, it prints the word "cool," offering a succinct representation of the function's nature as outlined in the docstring. The code demonstrates the use of docstrings for documenting functions and extracting information from them.

    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 check if the pattern "back" is present in the given strings. The first two conditions use the match() function, which checks if the pattern matches the entire string. Since "backup.txt" starts with "back", the first condition is true and sum is incremented by 1. However, "text.back" does not start with "back", so the second condition is false and sum remains unchanged. The next two conditions use the search() function, which checks if the pattern is present anywhere in the string. Both "backup.txt" and "text.back" contain "back", so both conditions are true and sum is incremented by 4 and 8 respectively. Therefore, the final value of sum is 1 + 4 + 8 = 13.

    Rate this question:

Samy Boulos |MSc (Computer Science) |
Data Engineer
Samy Boulos is an experienced Technology Consultant with a diverse 25-year career encompassing software development, data migration, integration, technical support, and cloud computing. He leverages his technical expertise and strategic mindset to solve complex IT challenges, delivering efficient and innovative solutions to clients.

Quiz Review Timeline +

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

  • Current Version
  • Sep 01, 2024
    Quiz Edited by
    ProProfs Editorial Team

    Expert Reviewed by
    Samy Boulos
  • Feb 05, 2013
    Quiz Created by
    Vineedk
Back to Top Back to top
Advertisement
×

Wait!
Here's an interesting quiz for you.

We have other quizzes matching your interest.