Python Advanced Quiz Questions With Answers

Reviewed by Samy Boulos
Samy Boulos, MSC, Computer Science |
Computer Expert
Review Board Member
With over 25 years of expertise, Samy is a seasoned Senior Technology Consultant. His extensive background spans diverse areas such as software development, data migration, Apple and Office 365 integration, computer helpdesk support, data engineering, and cloud computing. A dedicated professional, Samy combines technical proficiency with a strategic mindset, ensuring optimal solutions for complex technological challenges. His wealth of experience positions him as a reliable and knowledgeable consultant in navigating the ever-evolving landscape of IT and technology.
, 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: 9,327
Questions: 15 | Attempts: 8,872

SettingsSettingsSettings
Python Advanced Quiz Questions With Answers - Quiz

If you are a programmer then you must have some knowledge of python. Try this 'python advanced quiz questions with answers' and get to test your python knowledge today! Are you just getting into programming and have recently started studying advanced python? Don't worry. It is an easy and interesting subject. Take this quiz to revise your concepts and you might also get to know what areas you need to study more on. All the best!


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" because the variable "a" is assigned the value that the user enters at the prompt using the input() function. In this case, the user enters "foo" at the prompt, so the value of "a" is "foo". The print statement then prints 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 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
  • 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 will not print "error type 1" if the accessSecureSystem() function raises an exception of either AccessError type or SecurityError type. The correct answer is false because the except statement should specify each exception type separately, not separated by a comma. Therefore, the code will raise a syntax error.

    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 |
Computer Expert
With over 25 years of expertise, Samy is a seasoned Senior Technology Consultant. His extensive background spans diverse areas such as software development, data migration, Apple and Office 365 integration, computer helpdesk support, data engineering, and cloud computing. A dedicated professional, Samy combines technical proficiency with a strategic mindset, ensuring optimal solutions for complex technological challenges. His wealth of experience positions him as a reliable and knowledgeable consultant in navigating the ever-evolving landscape of IT and technology.

Quiz Review Timeline +

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

  • Current Version
  • Mar 08, 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.