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)
By Vineedk
V
Vineedk
Community Contributor
Quizzes Created: 2 | Total Attempts: 10,971
| Attempts: 10,360 | Questions: 15
Please wait...
Question 1 / 15
0 %
0/100
Score 0/100
1. What gets printed?
kvps  = {"user","bill", "password","hillary"}
 
print kvps['password']

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.

Submit
Please wait...
About This Quiz
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... see moreadvanced 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 techniques and deepen your understanding of this versatile programming language. Good luck and happy coding! see less

2. What gets printed?  
def simpleFunction():
    "This is a cool simple function that returns 1"
    return 1

 
print simpleFunction.__doc__[10:14]

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.
Submit
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))

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+++".

Submit
4. What gets printed?  
names1 = ['Amir', 'Barry', 'Chales', 'Dao']

 
loc = names1.index("Edward")

 
print loc

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.

Submit
5. 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

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.

Submit
6. 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

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.

Submit
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

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.

Submit
8. 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

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.

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

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.

Submit
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)

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.

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

 
print names2[2][0]

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".

Submit
12.  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()

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__".

Submit
13. 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

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.

Submit
14. 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)

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.

Submit
15. 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()

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().

Submit
View My Results
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 (Updated): Sep 1, 2024 +

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
Cancel
  • All
    All (15)
  • Unanswered
    Unanswered ()
  • Answered
    Answered ()
What gets printed?...
What gets printed? ...
What gets printed?...
What gets printed? ...
What numbers get printed...
What gets printed?...
What gets printed?...
What gets printed?...
Which of the following Python features allows you to define a function...
The following code will successfully print the days and then the...
What gets printed? ...
 Assuming the filename for the code below is...
What gets printed? ...
What gets printed?...
In python 2.6 or earlier, the code will print error type 1 if...
Alert!

Advertisement