Python Essentials 2 – Module 4 Test Answers (Completion)

Python Essentials 2 Module 4 Completion – Module Test Answers

Python Essentials 2: PE2: Module 4. Miscellaneous test Answers full new questions

1. What keyword would you use to define an anonymous function?

  • afun
  • yield
  • lambda
  • def
Explanation: Remember that in Python, a lambda function is a single line function declared with no name – in other words anonymous.

2. Select the true statements. (Select two answers)

  • The lambda function can accept any number of arguments
  • The lambda function can evaluate multiple expressions
  • The lambda function can evaluate only one expression
  • The lambda function can accept a maximum of two arguments
Explanation: Remember that a lambda function can have any number of arguments, but it can only evaluate a single expression.

3. Look at the code below:

my_list = [1, 2, 3]
# Insert line of code here.
print(foo)

Which snippet would you insert in order for the program to output the following result (tuple):

(1, 4, 27)
  • foo = list(map(lambda x: x*x, my_list))
  • foo = tuple(map(lambda x: x**x, my_list))
  • foo = tuple(map(lambda x: x*x, my_list))
  • foo = list(map(lambda x: x**x, my_list))
Explanation:

In order to obtain the tuple mentioned, a map function is used. It takes the lambda function lambda x: x**x and the list my_list as arguments. It performs the exponentiation operation x**x defined within the lambda function with each of the lists elements [1, 2, 3]. The result is cast to a tuple and printed in the console.

4. Look at the code below:

my_tuple = (0, 1, 2, 3, 4, 5, 6)
# Insert line of code here.
print(foo)

Which snippet would you insert in order for the program to output the following result (list):

[2, 3, 4, 5, 6]
  • foo = tuple(filter(lambda x: x-0 and x-1, my_tuple))
  • foo = tuple(filter(lambda x: x>1, my_tuple))
  • foo = list(filter(lambda x: x==0 and x==1, my_tuple))
  • foo = list(filter(lambda x: x-0 and x-1, my_tuple))
Explanation:

In order to obtain the list mentioned, a filter function is used. It takes the lambda function lambda x: x-0 and x-1 and the tuple my_tuple as arguments. It performs the operation x: x-0 and x-1 defined within the lambda function, filtering the tuple elements in the index positions 0 and 1, meaning that they are not shown. The result is cast to a list and printed on the console.

5. What is the expected result of executing the following code?

def I():
    s = 'abcdef'
    for c in s[::2]:
        yield c
 
 
for x in I():
    print(x, end='')
  • It will print ace
  • It will print bdf
  • It will print an empty line
  • It will print abcdef
Explanation:

Let’s analyze this code snippet:

  • The code begins by executing the for x in I(): loop.
  • It uses the x variable to iterate through what I(): yields, and outputs it on the same line due to the end=” argument in the print function.
  • Once the I(): iterator is invoked, it initializes a string that contains the characters s = ‘abcdef’.
  • A for loop iterates though the characters within the s string using the c variable.
  • Due to the [::2] notation, the loop will only iterate through every two characters, yielding one on each iteration. In other words, it begins on the first character, skips to the third, and finally to the fifth.
  • Since there is no seventh character, the execution comes to an end.
  • The characters ace are printed in the console.

6. What is the expected result of executing the following code?

def fun(n):
    s = '+'
    for i in range(n):
        s += s
        yield s
 
 
for x in fun(2):
    print(x, end='');
  • It will print ++
  • It will print ++++++
  • It will print +
  • It will print +++
Explanation:

Let’s analyze this code snippet:

  • The code begins by executing the for x in fun(2): loop.
  • It uses the x variable to iterate through what fun(2): yields, and outputs it on the same line due to the end=” argument in the print function.
  • Once the fun(2): iterator is invoked, it initializes a string that contains the character s = ‘+’.
  • A for loop uses the range function with 2 as its argument, which was sent to the iterator when it was invoked. The for loop will iterate twice (the values for the i variable are 0 and 1).
  • In the first iteration, the s += s operation is applied to the string, and the new string s = ‘++’ is yielded and outputted in the console.
  • In the second iteration, the s += s operation is again applied to the last produced string, and the new string s = ‘++++’ is yielded and outputted in the console.
  • The final result shown in the console is ++++++ .

7. What is the expected result of executing the following code?

def o(p):
    def q():
        return '*' * p
    return q
 
 
r = o(1)
s = o(2)
print(r() + s())
  • It will print *
  • It will print ****
  • It will print ***
  • It will print **
Explanation:

This code snippet implements Closures, which are inner functions enclosed within an outer function. Let’s analyze this code snippet:

  • The code begins by creating a Closure named r by invoking the outer function o(1). The Closure contains the inner function q() that will return the result of the operation ‘*’ * 1, which is * .
  • A second Closure named s is created by invoking the outer function o(2). The Closure contains the inner function q() that will return the result of the operation ‘*’ * 2, which is ** .
  • Finally, both closures are invoked within a print function concatenating their results. Therefore, the console output is ***.

8. Which of the following open modes allow you to perform read operations? (Select two answers)

  • r
  • a
  • r+
  • w
Explanation:

These are the open modes in Python:

  • r – opens a file for reading.
  • w – opens a file for writing.
  • a – opens a file for appending at the end. Creates a new file if it does not exist.
  • t – opens in text mode.
  • b – opens in binary mode.
  • + – opens a file for updating (reading and writing).

9. What is the meaning of the value represented by errno.EEXIST ?

  • Permission denied
  • File exists
  • Bad file number
  • File doesn’t exist
Explanation:

Remember that errno.EEXIST means that the file or directory trying to be created already exists.

10. What is the expected result of the following code?

b = bytearray(3)
print(b)
  • bytearray(b’3′)
  • bytearray(b’\x00\x00\x00′)
  • bytearray(0, 0, 0)
  • 3
Explanation:

Remember that the bytearray() function creates an array of bytes. Since 3 is specified as an argument, the b bytearray will consist of 3 empty bytes. Then, the print function outputs them to console: bytearray(b’\x00\x00\x00′).

11. What is the expected result of the following code?

import os
 
os.mkdir('pictures')
os.chdir('pictures')
os.mkdir('thumbnails')
os.chdir('thumbnails')
os.mkdir('tmp')
os.chdir('../')
 
print(os.getcwd())
  • It prints the path to the pictures directory
  • It prints the path to the root directory
  • It prints the path to the thumbnails directory
  • It prints the path to the tmp directory
Explanation:

Let’s analyze this code snippet:

  • The first line imports the os module, which handles functions that interact with the Operating System.
  • The second line creates a directory named pictures.
  • The third line changes the current working directory to the pictures folder.
  • The fourth line creates a directory named thumbnails.
  • The fifth line changes the current working directory to the thumbnails folder.
  • The sixth line creates a directory named tmp.
  • The seventh line exits the current working directory.
  • The eighth line prints the path to the current working directory which is now the pictures folder.

12. What is the expected result of the following code?

import os
 
os.mkdir('thumbnails')
os.chdir('thumbnails')
 
sizes = ['small', 'medium', 'large']
 
for size in sizes:
    os.mkdir(size)
 
print(os.listdir())
  • [‘.’, ‘large’, ‘small’, ‘medium’]
  • [‘large’, ‘small’, ‘medium’]
  • [‘.’, ‘..’, ‘large’, ‘small’, ‘medium’]
  • []
Explanation:

Let’s analyze this code snippet:

  • The first line imports the os module, which handles functions that interact with the Operating System.
  • The second line creates a directory named thumbnails.
  • The third line changes the current working directory to the thumbnails folder.
  • The fourth line creates a list named sizes that contains three elements ‘small’, ‘medium’, and ‘large’.
  • The fifth and sixth lines are a for loop that iterates through the sizes list and creates three folders within the current working directory. Each folder is named after each element in the size list.
  • The seventh line prints the existing directories (in a list format) within the current working directory, which is the thumbnails folder.
  • The output is [‘large’, ‘small’, ‘medium’].

13. What is the expected result of the following code?

from datetime import date
 
date_1 = date(1992, 1, 16)
date_2 = date(1991, 2, 5)
 
print(date_1 - date_2)
  • 345
  • 345, 0:00:00
  • 345 days
  • 345 days, 0:00:00
Explanation:

Let’s analyze this code snippet:

  • The first line imports the datetime function from the date module.
  • The second line creates a date object named date_1. The set date is January 16, 1992.
  • The third line creates a date object named date_2. The set date is February 5, 1991.
  • The fourth line is a print function that outputs the difference between date_1 and date_2 using the operator.
  • The result is show in the console. Remember, the output format expresses days, hours, minutes and seconds, since they can also be specified.

14. What is the expected result of the following code?

from datetime import datetime
 
datetime = datetime(2019, 11, 27, 11, 27, 22)
print(datetime.strftime('%y/%B/%d %H:%M:%S'))
  • 19/November/27 11:27:22
  • 19/11/27 11:27:22
  • 2019/Nov/27 11:27:22
  • 2019/11/27 11:27:22
Explanation:

Let’s analyze this code snippet:

  • The first line imports the datetime function from the datetime module.
  • The second line creates a datetime object named datetime. The arguments represent the year, month, day, hours, minutes, and seconds.
  • The third line formats the date using the strftime method.
  • The %y argument formats the year without the century digits, and the result is 19.
  • The %B argument formats the month to its full name, and the result is November.
  • The %d argument formats the day to two digits. In this case, the result stays the same, which is 27.
  • The %H argument formats the hours to a 24 hour format. In this case, the result stays the same, which is 11.
  • The %M argument formats the minutes to two digits. In this case, the result stays the same, which is 27.
  • The %S argument formats the seconds to two digits. In this case, the result stays the same, which is 22.
  • The arguments are separated by slashes and colons. The output printed in the console is 19/November/27 11:27:22.

15. Which program will produce the following output:

Mo Tu We Th Fr Sa Su

A:

import calendar
print(calendar.weekheader(2))

B:

import calendar
print(calendar.weekheader())

C:

import calendar
print(calendar.weekheader(3))

D:

import calendar
print(calendar.week)
  • C
  • B
  • A
  • D
Explanation:

The requested output represents the weekdays with only two letters. Therefore, the calendar.weekheader() method must receive 2 as an argument.

16. What is the expected result of the following code?

import calendar
 
c = calendar.Calendar()
 
for weekday in c.iterweekdays():
    print(weekday, end=" ")
  • Mo Tu We Th Fr Sa Su
  • 1 2 3 4 5 6 7
  • Su Mo Tu We Th Fr Sa
  • 0 1 2 3 4 5 6
Explanation:

Let’s analyze the code:

  • Line 1: the calendar module is imported.
  • Line 3: a c object is created from the Calendar() class provided by the calendar module. The Calendar() class constructor takes no optional firstweekday parameter, which means its value is equal to 0 by default (0 is equal to Monday).
  • Lines 5 and 6: the for loop and the Calendar() class method named iterweekdays are used to iterate through the days of the week, and return an iterator for each week day number, starting from 0 (Monday), to 6 (Sunday). The values are printed to the console.

Leave a Reply

Your email address will not be published. Required fields are marked *