Advanced Python Test Quiz

Reviewed by Editorial Team
The ProProfs editorial team is comprised of experienced subject matter experts. They've collectively created over 10,000 quizzes and lessons, serving over 100 million users. Our team includes in-house content moderators and subject matter experts, as well as a global network of rigorously trained contributors. All adhere to our comprehensive editorial guidelines, ensuring the delivery of high-quality content.
Learn about Our Editorial Process
| By Bhargav.baggi
B
Bhargav.baggi
Community Contributor
Quizzes Created: 1 | Total Attempts: 2,327
| Attempts: 2,327 | Questions: 15
Please wait...
Question 1 / 15
0 %
0/100
Score 0/100
1. What gets printed (with python version 3.X) assuming the user enters the following at the prompt? #: foo 
a = input("#: ")
 
print a

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

Submit
Please wait...
About This Quiz
Advanced Python Test Quiz - Quiz

The Advanced Python Test Quiz assesses in-depth knowledge of Python programming. It includes questions on input\/output operations, object-oriented programming, error handling, and string manipulation, targeting experienced programmers to... see morevalidate their Python skills. see less

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

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

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

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

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

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

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.

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

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.

Submit
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

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

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

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

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

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

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

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

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

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

Submit
View My Results

Quiz Review Timeline (Updated): Aug 18, 2023 +

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
Cancel
  • All
    All (15)
  • Unanswered
    Unanswered ()
  • Answered
    Answered ()
What gets printed (with python version 3.X) assuming the user enters...
What gets printed?...
What gets printed?...
What gets printed?...
What gets printed?...
What gets printed?...
What gets printed?...
What numbers get printed...
What gets printed?...
The following code will successfully print the days and then the...
What gets printed?...
In python 2.6 or earlier, the code will print error type 1 if...
 Assuming the filename for the code below is...
What gets printed?...
What gets printed?...
Alert!

Advertisement