├── __version__.py
├── src
└── exercices
│ ├── resources
│ ├── subjects.csv
│ ├── todo.db
│ ├── contacts.csv
│ ├── exam_report.csv
│ ├── books.xml
│ ├── exam_results.csv
│ └── forecast.xml
│ ├── tk_prac.py
│ ├── tk_practice.py
│ ├── csv_work.py
│ ├── xml_change_temp.py
│ ├── server_checker.py
│ ├── change_temperature_from_xml.py
│ ├── logging_practice.py
│ ├── site_checker.py
│ ├── sitechecker.py
│ ├── build_xml.py
│ ├── json_dec_enc.py
│ ├── encoder_decoder_json.py
│ ├── sqlite_task.py
│ ├── csv_writer.py
│ └── cars_practice.py
├── .gitignore
├── README.md
└── dumps
├── 4. API.md
├── 5. FILES.md
├── 3. TKINTER.md
├── 2. BEST PRACTICES.md
└── 1. POO.md
/__version__.py:
--------------------------------------------------------------------------------
1 | __version__ = 1.6
2 |
--------------------------------------------------------------------------------
/src/exercices/resources/subjects.csv:
--------------------------------------------------------------------------------
1 | maths
2 | physics
3 |
--------------------------------------------------------------------------------
/src/exercices/resources/todo.db:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/anthonywainer/pcpp1_certification_dumps/HEAD/src/exercices/resources/todo.db
--------------------------------------------------------------------------------
/src/exercices/resources/contacts.csv:
--------------------------------------------------------------------------------
1 | Name,Phone
2 | mother,222-555-101
3 | father,222-555-102
4 | wife,222-555-103
5 | mother-in-law,222-555-104
--------------------------------------------------------------------------------
/src/exercices/resources/exam_report.csv:
--------------------------------------------------------------------------------
1 | Exam Name,Number of Candidates,Number of Passed Exams,Number of Failed Exams,Best Score,Worst Score
2 | Maths,8,4,6,90,33
3 | Physics,3,0,3,66,50
4 | Biology,5,2,3,88,23
5 |
--------------------------------------------------------------------------------
/src/exercices/resources/books.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Antoine de Saint-Exupéry
5 | 1943
6 |
7 |
8 | William Shakespeare
9 | 1603
10 |
11 |
--------------------------------------------------------------------------------
/src/exercices/tk_prac.py:
--------------------------------------------------------------------------------
1 | import tkinter as tk
2 |
3 | window = tk.Tk()
4 | canvas = tk.Canvas(window, width=400, height=400, bg='yellow')
5 | canvas.create_line(0, 0, 200, 200, 150,100, 250,30,
6 | arrow=tk.BOTH, fill='red', smooth=True, width=3)
7 | button = tk.Button(window, text="Quit", command=window.destroy)
8 | canvas.grid(row=0)
9 | button.grid(row=1)
10 | window.mainloop()
11 |
12 |
--------------------------------------------------------------------------------
/src/exercices/tk_practice.py:
--------------------------------------------------------------------------------
1 | import tkinter as tk
2 |
3 | window = tk.Tk()
4 | canvas = tk.Canvas(window, width=400, height=400, bg='yellow')
5 | canvas.create_line(0, 0, 200, 200, 150,100, 250,30,
6 | arrow=tk.BOTH, fill='red', smooth=True, width=3)
7 | button = tk.Button(window, text="Quit", command=window.destroy)
8 | canvas.grid(row=0)
9 | button.grid(row=1)
10 | window.mainloop()
11 |
12 |
--------------------------------------------------------------------------------
/src/exercices/resources/exam_results.csv:
--------------------------------------------------------------------------------
1 | Exam Name,Candidate ID,Score,Grade
2 | Maths,C000007,44,Fail
3 | Physics,C000001,50,Fail
4 | Biology,C000001,30,Fail
5 | Maths,C000005,50,Fail
6 | Biology,C000002,45,Fail
7 | Physics,C000006,66,Fail
8 | Maths,C000009,74,Pass
9 | Maths,C000010,74,Pass
10 | Biology,C000003,70,Pass
11 | Maths,C000012,55,Fail
12 | Maths,C000013,33,Fail
13 | Biology,C000004,88,Pass
14 | Maths,C000014,90,Pass
15 | Maths,C000005,82,Pass
16 | Biology,C000011,23,Fail
17 | Maths,C000008,44,Fail
18 | Maths,C000008,54,Fail
19 | Physics,C000003,54,Fail
--------------------------------------------------------------------------------
/src/exercices/resources/forecast.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | -
4 | Monday
5 | 28
6 |
7 | -
8 | Tuesday
9 | 27
10 |
11 | -
12 | Wednesday
13 | 28
14 |
15 | -
16 | Thursday
17 | 29
18 |
19 | -
20 | Friday
21 | 29
22 |
23 | -
24 | Saturday
25 | 31
26 |
27 | -
28 | Sunday
29 | 32
30 |
31 |
--------------------------------------------------------------------------------
/src/exercices/csv_work.py:
--------------------------------------------------------------------------------
1 | import csv
2 |
3 |
4 | class PhoneContact:
5 | def __init__(self, name, phone):
6 | self.name = name
7 | self.phone = phone
8 |
9 |
10 | class Phone:
11 | def __init__(self):
12 | self.contacts = []
13 |
14 | def load_contacts_from_csv(self, file):
15 | with open(file, newline='') as csvfile:
16 | fieldnames = ['Name', 'Phone']
17 | reader = csv.DictReader(csvfile, fieldnames)
18 | for row in reader:
19 | self.contacts.append(PhoneContact(row['Name'], row['Phone']))
20 |
21 | def search_contacts(self, phrase):
22 | count = 0
23 | for contact in self.contacts:
24 | if phrase.lower() in contact.name.lower() \
25 | or phrase in contact.phone:
26 | print('{0} ({1})'.format(contact.name, contact.phone))
27 | count += 1
28 | if count == 0:
29 | print("No contacts found")
30 |
31 |
32 | phone = Phone()
33 | phone.load_contacts_from_csv('resources/contacts.csv')
34 | phrase = input("Search contacts: ")
35 | phone.search_contacts(phrase)
36 |
--------------------------------------------------------------------------------
/src/exercices/xml_change_temp.py:
--------------------------------------------------------------------------------
1 | import xml.etree.ElementTree as ET
2 |
3 |
4 | class TemperatureConverter:
5 | def convert_celsius_to_fahrenheit(self, temperature_in_celsius):
6 | return 9.0 / 5.0 * temperature_in_celsius + 32
7 |
8 |
9 | class ForecastXmlParser:
10 | def __init__(self, temperature_converter):
11 | self.temperature_converter = temperature_converter
12 |
13 | def parse(self, file):
14 | tree = ET.parse(file)
15 | root = tree.getroot()
16 | for child in root:
17 | day = child.find('day').text
18 | temperature_in_celsius = int(child.find(
19 | 'temperature_in_celsius').text)
20 | temperature_in_fahrenheit = round(
21 | self.temperature_converter.convert_celsius_to_fahrenheit(
22 | temperature_in_celsius), 1)
23 | print('{0}: {1} Celsius, {2} Fahrenheit'.format(
24 | day, temperature_in_celsius, temperature_in_fahrenheit))
25 |
26 |
27 | temperature_converter = TemperatureConverter()
28 | forecast_xml_parser = ForecastXmlParser(temperature_converter)
29 | forecast_xml_parser.parse('forecast.xml')
30 |
--------------------------------------------------------------------------------
/src/exercices/server_checker.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import requests
3 |
4 | if len(sys.argv) not in [2, 3]:
5 | print("Improper number of arguments: at least one is required " +
6 | "and not more than two are allowed:")
7 | print("- http server's address (required)")
8 | print("- port number (defaults to 80 if not specified)")
9 | exit(1)
10 |
11 | addr = sys.argv[1]
12 | URI = 'http://' + sys.argv[1]
13 | if len(sys.argv) == 3:
14 | try:
15 | port = int(sys.argv[2])
16 | if not 1 <= port <= 65535:
17 | raise ValueError
18 | except ValueError:
19 | print("Port number is invalid - exiting.")
20 | exit(2)
21 | URI += ':' + str(port)
22 | URI += '/'
23 |
24 | try:
25 | response = requests.head("URI")
26 | except requests.exceptions.InvalidURL:
27 | print("The given URL '" + sys.argv[1] + "' is invalid.")
28 | exit(3)
29 | except requests.exceptions.ConnectionError:
30 | print("Cannot connect to '" + addr + "'.")
31 | exit(4)
32 | except requests.exceptions.RequestException:
33 | print("Some problems appeared - sorry.")
34 | exit(5)
35 |
36 | print(response.status_code, response.reason)
37 |
--------------------------------------------------------------------------------
/src/exercices/change_temperature_from_xml.py:
--------------------------------------------------------------------------------
1 | import xml.etree.ElementTree as ET
2 |
3 |
4 | class TemperatureConverter:
5 | def convert_celsius_to_fahrenheit(self, temperature_in_celsius):
6 | return 9.0 / 5.0 * temperature_in_celsius + 32
7 |
8 |
9 | class ForecastXmlParser:
10 | def __init__(self, temperature_converter):
11 | self.temperature_converter = temperature_converter
12 |
13 | def parse(self, file):
14 | tree = ET.parse(file)
15 | root = tree.getroot()
16 | for child in root:
17 | day = child.find('day').text
18 | temperature_in_celsius = int(child.find(
19 | 'temperature_in_celsius').text)
20 | temperature_in_fahrenheit = round(
21 | self.temperature_converter.convert_celsius_to_fahrenheit(
22 | temperature_in_celsius), 1)
23 | print('{0}: {1} Celsius, {2} Fahrenheit'.format(
24 | day, temperature_in_celsius, temperature_in_fahrenheit))
25 |
26 |
27 | temperature_converter = TemperatureConverter()
28 | forecast_xml_parser = ForecastXmlParser(temperature_converter)
29 | forecast_xml_parser.parse('forecast.xml')
30 |
--------------------------------------------------------------------------------
/src/exercices/logging_practice.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import random
3 |
4 | FORMAT = '%(levelname)s - %(message)s'
5 |
6 |
7 | class BatterySimulation:
8 | def __init__(self, logger):
9 | self.logger = logger
10 |
11 | def simulate_last_hour(self):
12 | for minute in range(1, 60 + 1):
13 | temperature = random.randint(20, 40)
14 |
15 | if temperature < 30:
16 | self.logger.debug('{0} C'.format(temperature))
17 | elif temperature >= 30 and temperature <= 35:
18 | self.logger.warning('{0} C'.format(temperature))
19 | elif temperature > 35:
20 | self.logger.critical('{0} C'.format(temperature))
21 | else:
22 | raise Exception('Temperature out of range.')
23 |
24 |
25 | logger = logging.getLogger('battery.temperature')
26 | logger.setLevel(logging.DEBUG)
27 |
28 | handler = logging.FileHandler('resources/battery_temperature.log', mode='w')
29 | handler.setLevel(logging.DEBUG)
30 |
31 | formatter = logging.Formatter(FORMAT)
32 | handler.setFormatter(formatter)
33 |
34 | logger.addHandler(handler)
35 |
36 | battery_simulation = BatterySimulation(logger)
37 | battery_simulation.simulate_last_hour()
--------------------------------------------------------------------------------
/src/exercices/site_checker.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import socket
3 |
4 | if len(sys.argv) not in [2, 3]:
5 | print("Improper number of arguments: at least one is required" +
6 | "and not more than two are allowed:")
7 | print("- http server's address (required)")
8 | print("- port number (defaults to 80 if not specified)")
9 | exit(1)
10 |
11 | addr = sys.argv[1]
12 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
13 | if len(sys.argv) == 3:
14 | try:
15 | port = int(sys.argv[2])
16 | if not 1 <= port <= 65535:
17 | raise ValueError
18 | except ValueError:
19 | print("Port number is invalid - exiting.")
20 | exit(2)
21 | else:
22 | port = 80
23 |
24 | try:
25 | sock.connect((addr, port))
26 | except socket.timeout:
27 | print("The server" + addr + "seems to be dead - sorry.")
28 | exit(3)
29 | except socket.gaierror:
30 | print("Server address" + addr + "is invalid or malformed - sorry.")
31 | exit(4)
32 |
33 | request = b"HEAD / HTTP/1.0\r\nHost: " + \
34 | bytes(addr, "utf8") + \
35 | b"\r\nConnection:close\r\n\r\n"
36 |
37 | sock.send(request)
38 | answer = sock.recv(100).decode("utf8")
39 | sock.shutdown(socket.SHUT_RDWR)
40 | sock.close()
41 | print(answer[:answer.find('\r')])
42 |
--------------------------------------------------------------------------------
/src/exercices/sitechecker.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import socket
3 |
4 | if len(sys.argv) not in [2, 3]:
5 | print("Improper number of arguments: at least one is required" +
6 | "and not more than two are allowed:")
7 | print("- http server's address (required)")
8 | print("- port number (defaults to 80 if not specified)")
9 | exit(1)
10 |
11 | addr = sys.argv[1]
12 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
13 | if len(sys.argv) == 3:
14 | try:
15 | port = int(sys.argv[2])
16 | if not 1 <= port <= 65535:
17 | raise ValueError
18 | except ValueError:
19 | print("Port number is invalid - exiting.")
20 | exit(2)
21 | else:
22 | port = 80
23 |
24 | try:
25 | sock.connect((addr, port))
26 | except socket.timeout:
27 | print("The server" + addr + "seems to be dead - sorry.")
28 | exit(3)
29 | except socket.gaierror:
30 | print("Server address" + addr + "is invalid or malformed - sorry.")
31 | exit(4)
32 |
33 | request = b"HEAD / HTTP/1.0\r\nHost: " + \
34 | bytes(addr, "utf8") + \
35 | b"\r\nConnection:close\r\n\r\n"
36 |
37 | sock.send(request)
38 | answer = sock.recv(100).decode("utf8")
39 | sock.shutdown(socket.SHUT_RDWR)
40 | sock.close()
41 | print(answer[:answer.find('\r')])
42 |
--------------------------------------------------------------------------------
/src/exercices/build_xml.py:
--------------------------------------------------------------------------------
1 | import xml.etree.ElementTree as ET
2 |
3 |
4 | class XmlTreeHelper:
5 | def add_tags_with_text(self, parent, tags):
6 | elements = []
7 | for tag in tags:
8 | element = ET.SubElement(parent, tag)
9 | element.text = tags[tag]
10 | elements.append(element)
11 | return elements
12 |
13 |
14 | root = ET.Element('shop')
15 |
16 | category = ET.SubElement(root, 'category', {'name': 'Vegan Products'})
17 |
18 | product_1 = ET.SubElement(category, 'product', {'name': 'Good Morning Sunshine'})
19 | product_2 = ET.SubElement(category, 'product', {'name': 'Spaghetti Veganietto'})
20 | product_3 = ET.SubElement(category, 'product', {'name': 'Fantastic Almond Milk'})
21 |
22 | xml_tree_helper = XmlTreeHelper()
23 |
24 | xml_tree_helper.add_tags_with_text(product_1, {
25 | 'type': 'cereals',
26 | 'producer': 'OpenEDG Foods Limited',
27 | 'price': '9.90',
28 | 'currency': 'USD'
29 | })
30 |
31 | xml_tree_helper.add_tags_with_text(product_2, {
32 | 'type': 'pasta',
33 | 'producer': 'Programmers Eat Pasta Gmbh',
34 | 'price': '14.49',
35 | 'currency': 'EUR'
36 | })
37 |
38 | xml_tree_helper.add_tags_with_text(product_3, {
39 | 'type': 'beverages',
40 | 'producer': 'Drinks4Coders Inc.',
41 | 'price': '19.75',
42 | 'currency': 'USD'
43 | })
44 |
45 | # ET.dump(root)
46 |
47 | tree = ET.ElementTree(root)
48 | tree.write('resources/shop.xml', 'UTF-8', True)
49 |
--------------------------------------------------------------------------------
/src/exercices/json_dec_enc.py:
--------------------------------------------------------------------------------
1 | import json
2 |
3 |
4 | class Vehicle:
5 | def __init__(self, registration_number, year_of_production, passenger, mass):
6 | self.registration_number = registration_number
7 | self.year_of_production = year_of_production
8 | self.passenger = passenger
9 | self.mass = mass
10 |
11 |
12 | class MyEncoder(json.JSONEncoder):
13 | def default(self, veh):
14 | if isinstance(veh, Vehicle):
15 | return veh.__dict__
16 | else:
17 | return super().default(self, veh)
18 |
19 |
20 | class MyDecoder(json.JSONDecoder):
21 | def __init__(self):
22 | json.JSONDecoder.__init__(self, object_hook=self.decode_vehicle)
23 |
24 | def decode_vehicle(self, veh):
25 | return Vehicle(**veh)
26 |
27 |
28 | print("What can I do for you?")
29 | print("1 - produce a JSON string describing a vehicle")
30 | print("2 - decode a JSON string into vehicle data")
31 | answer = ''
32 | while answer not in ['1', '2']:
33 | answer = input("Your choice: ")
34 | if answer == '1':
35 | rn = input("Registration number: ")
36 | yop = int(input("Year of production: "))
37 | psg = input("Passenger [y/n]: ").upper() == 'Y'
38 | mss = float(input("Vehicle mass: "))
39 | vehicle = Vehicle(rn, yop, psg, mss)
40 | print("Resulting JSON string is:")
41 | print(json.dumps(vehicle, cls=MyEncoder))
42 | else:
43 | json_str = input("Enter vehicle JSON string: ")
44 | try:
45 | new_car = json.loads(json_str, cls=MyDecoder)
46 | print(new_car.__dict__)
47 | except TypeError:
48 | print("The JSON string doesn't describe a valid vehicle")
49 | print("Done")
50 |
--------------------------------------------------------------------------------
/src/exercices/encoder_decoder_json.py:
--------------------------------------------------------------------------------
1 | import json
2 |
3 |
4 | class Vehicle:
5 | def __init__(self, registration_number, year_of_production, passenger, mass):
6 | self.registration_number = registration_number
7 | self.year_of_production = year_of_production
8 | self.passenger = passenger
9 | self.mass = mass
10 |
11 |
12 | class MyEncoder(json.JSONEncoder):
13 | def default(self, veh):
14 | if isinstance(veh, Vehicle):
15 | return veh.__dict__
16 | else:
17 | return super().default(self, veh)
18 |
19 |
20 | class MyDecoder(json.JSONDecoder):
21 | def __init__(self):
22 | json.JSONDecoder.__init__(self, object_hook=self.decode_vehicle)
23 |
24 | def decode_vehicle(self, veh):
25 | return Vehicle(**veh)
26 |
27 |
28 | print("What can I do for you?")
29 | print("1 - produce a JSON string describing a vehicle")
30 | print("2 - decode a JSON string into vehicle data")
31 | answer = ''
32 | while answer not in ['1', '2']:
33 | answer = input("Your choice: ")
34 | if answer == '1':
35 | rn = input("Registration number: ")
36 | yop = int(input("Year of production: "))
37 | psg = input("Passenger [y/n]: ").upper() == 'Y'
38 | mss = float(input("Vehicle mass: "))
39 | vehicle = Vehicle(rn, yop, psg, mss)
40 | print("Resulting JSON string is:")
41 | print(json.dumps(vehicle, cls=MyEncoder))
42 | else:
43 | json_str = input("Enter vehicle JSON string: ")
44 | try:
45 | new_car = json.loads(json_str, cls=MyDecoder)
46 | print(new_car.__dict__)
47 | except TypeError:
48 | print("The JSON string doesn't describe a valid vehicle")
49 | print("Done")
50 |
--------------------------------------------------------------------------------
/src/exercices/sqlite_task.py:
--------------------------------------------------------------------------------
1 | import sqlite3
2 |
3 |
4 | class Todo:
5 | def __init__(self):
6 | self.conn = sqlite3.connect('resources/todo.db')
7 | self.c = self.conn.cursor()
8 | self.create_tasks_table()
9 |
10 | def create_tasks_table(self):
11 | self.c.execute('''CREATE TABLE IF NOT EXISTS tasks (
12 | id INTEGER PRIMARY KEY,
13 | name TEXT NOT NULL,
14 | priority INTEGER NOT NULL
15 | );''')
16 |
17 | def add_task(self):
18 | name = input('Enter task name: ')
19 | priority = int(input('Enter priority: '))
20 |
21 | if len(name) == 0 or priority < 1:
22 | return
23 |
24 | if self.find_task(name) is not None:
25 | return
26 |
27 | self.c.execute(
28 | 'INSERT INTO tasks (name, priority) VALUES (?,?)',
29 | (name, priority))
30 | self.conn.commit()
31 |
32 | def find_task(self, name):
33 | self.c.execute('SELECT * FROM tasks WHERE name = ?', (name,))
34 | return self.c.fetchone()
35 |
36 | def show_tasks(self):
37 | for row in self.c.execute('SELECT * FROM tasks'):
38 | print(row)
39 |
40 | def change_priority(self):
41 | task_id = int(input('Enter task id: '))
42 | new_priority = int(input('Enter new priority: '))
43 |
44 | if new_priority < 1:
45 | return
46 |
47 | self.c.execute(
48 | 'UPDATE tasks SET priority = ? WHERE id = ?',
49 | (new_priority, task_id))
50 | self.conn.commit()
51 |
52 | def delete_task(self):
53 | task_id = int(input('Enter task id: '))
54 |
55 | self.c.execute('DELETE FROM tasks WHERE id = ?', (task_id,))
56 | self.conn.commit()
57 |
58 |
59 | class Menu:
60 | def __init__(self):
61 | self.app = Todo()
62 |
63 | def open(self):
64 | self.open = True
65 | while self.open:
66 | self.draw()
67 | option = int(input('Choose an option [1-5]: '))
68 |
69 | if option == 1:
70 | self.app.show_tasks()
71 | elif option == 2:
72 | self.app.add_task()
73 | elif option == 3:
74 | self.app.change_priority()
75 | elif option == 4:
76 | self.app.delete_task()
77 | elif option == 5:
78 | self.close()
79 | else:
80 | input('Option not found. Please choose an option again...')
81 |
82 | def draw(self):
83 | print('1. Show Tasks')
84 | print('2. Add Task')
85 | print('3. Change Priority')
86 | print('4. Delete Task')
87 | print('5. Exit')
88 |
89 | def close(self):
90 | self.open = False
91 |
92 |
93 | menu = Menu()
94 | menu.open()
95 |
--------------------------------------------------------------------------------
/src/exercices/csv_writer.py:
--------------------------------------------------------------------------------
1 | import csv
2 |
3 |
4 | class ExamData:
5 | def __init__(self, exam_name):
6 | self.exam_name = exam_name
7 | self.candidates = []
8 | self.number_of_passed_exams = 0
9 | self.number_of_failed_exams = 0
10 | self.best_score = 0
11 | self.worst_score = 100
12 |
13 | def get_number_of_cadidates(self):
14 | return len(set(self.candidates))
15 |
16 |
17 | class ExamResultReader:
18 | def __init__(self, filename):
19 | self.filename = filename
20 | self.data = {}
21 |
22 | def prepare_data(self):
23 | with open(self.filename, newline='') as csvfile:
24 | fieldnames = ['Exam Name', 'Candidate ID', 'Score', 'Grade']
25 | reader = csv.DictReader(csvfile, fieldnames=fieldnames)
26 | row_count = 0
27 | for row in reader:
28 | row_count += 1
29 | if row_count == 1:
30 | continue
31 | exam_data = self.get_exam_data(row['Exam Name'])
32 | exam_data.candidates.append(row['Candidate ID'])
33 | if row['Grade'] == 'Pass':
34 | exam_data.number_of_passed_exams += 1
35 | else:
36 | exam_data.number_of_failed_exams += 1
37 | exam_data.best_score = max(
38 | exam_data.best_score,
39 | int(row['Score'])
40 | )
41 | exam_data.worst_score = min(
42 | exam_data.worst_score,
43 | int(row['Score'])
44 | )
45 | return self.data
46 |
47 | def get_exam_data(self, exam_name):
48 | if exam_name not in self.data:
49 | exam_data = ExamData(exam_name)
50 | self.data[exam_name] = exam_data
51 | return self.data[exam_name]
52 |
53 |
54 | class ExamReport:
55 | def __init__(self, data):
56 | self.data = data
57 |
58 | def generate(self, filename):
59 | with open(filename, 'w', newline='') as csvfile:
60 | fieldnames = [
61 | 'Exam Name',
62 | 'Number of Candidates',
63 | 'Number of Passed Exams',
64 | 'Number of Failed Exams',
65 | 'Best Score',
66 | 'Worst Score'
67 | ]
68 | writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
69 | writer.writeheader()
70 | for key, exam_data in self.data.items():
71 | number_of_cadidates = exam_data.get_number_of_cadidates()
72 | writer.writerow({
73 | 'Exam Name': exam_data.exam_name,
74 | 'Number of Candidates': number_of_cadidates,
75 | 'Number of Passed Exams': exam_data.number_of_passed_exams,
76 | 'Number of Failed Exams': exam_data.number_of_failed_exams,
77 | 'Best Score': exam_data.best_score,
78 | 'Worst Score': exam_data.worst_score
79 | })
80 |
81 |
82 | exam_result_reader = ExamResultReader('resources/exam_results.csv')
83 | data = exam_result_reader.prepare_data()
84 | exam_report = ExamReport(data)
85 | exam_report.generate('exam_report.csv')
86 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ### Python template
2 | # Byte-compiled / optimized / DLL files
3 | __pycache__/
4 | *.py[cod]
5 | *$py.class
6 |
7 | # C extensions
8 | *.so
9 |
10 | # Distribution / packaging
11 | .Python
12 | build/
13 | develop-eggs/
14 | dist/
15 | downloads/
16 | eggs/
17 | .eggs/
18 | lib/
19 | lib64/
20 | parts/
21 | sdist/
22 | var/
23 | wheels/
24 | share/python-wheels/
25 | *.egg-info/
26 | .installed.cfg
27 | *.egg
28 | MANIFEST
29 |
30 | # PyInstaller
31 | # Usually these files are written by a python script from a template
32 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
33 | *.manifest
34 | *.spec
35 |
36 | # Installer logs
37 | pip-log.txt
38 | pip-delete-this-directory.txt
39 |
40 | # Unit test / coverage reports
41 | htmlcov/
42 | .tox/
43 | .nox/
44 | .coverage
45 | .coverage.*
46 | .cache
47 | nosetests.xml
48 | coverage.xml
49 | *.cover
50 | *.py,cover
51 | .hypothesis/
52 | .pytest_cache/
53 | cover/
54 |
55 | # Translations
56 | *.mo
57 | *.pot
58 |
59 | # Django stuff:
60 | *.log
61 | local_settings.py
62 | db.sqlite3
63 | db.sqlite3-journal
64 |
65 | # Flask stuff:
66 | instance/
67 | .webassets-cache
68 |
69 | # Scrapy stuff:
70 | .scrapy
71 |
72 | # Sphinx documentation
73 | docs/_build/
74 |
75 | # PyBuilder
76 | .pybuilder/
77 | target/
78 |
79 | # Jupyter Notebook
80 | .ipynb_checkpoints
81 |
82 | # IPython
83 | profile_default/
84 | ipython_config.py
85 |
86 | # pyenv
87 | # For a library or package, you might want to ignore these files since the code is
88 | # intended to run in multiple environments; otherwise, check them in:
89 | # .python-version
90 |
91 | # pipenv
92 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
93 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
94 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
95 | # install all needed dependencies.
96 | #Pipfile.lock
97 |
98 | # poetry
99 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
100 | # This is especially recommended for binary packages to ensure reproducibility, and is more
101 | # commonly ignored for libraries.
102 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
103 | #poetry.lock
104 |
105 | # pdm
106 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
107 | #pdm.lock
108 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
109 | # in version control.
110 | # https://pdm.fming.dev/#use-with-ide
111 | .pdm.toml
112 |
113 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
114 | __pypackages__/
115 |
116 | # Celery stuff
117 | celerybeat-schedule
118 | celerybeat.pid
119 |
120 | # SageMath parsed files
121 | *.sage.py
122 |
123 | # Environments
124 | .env
125 | .venv
126 | env/
127 | venv/
128 | ENV/
129 | env.bak/
130 | venv.bak/
131 |
132 | # Spyder project settings
133 | .spyderproject
134 | .spyproject
135 |
136 | # Rope project settings
137 | .ropeproject
138 |
139 | # mkdocs documentation
140 | /site
141 |
142 | # mypy
143 | .mypy_cache/
144 | .dmypy.json
145 | dmypy.json
146 |
147 | # Pyre type checker
148 | .pyre/
149 |
150 | # pytype static type analyzer
151 | .pytype/
152 |
153 | # Cython debug symbols
154 | cython_debug/
155 |
156 | # PyCharm
157 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
158 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
159 | # and can be added to the global gitignore or merged into this file. For a more nuclear
160 | # option (not recommended) you can uncomment the following to ignore the entire idea folder.
161 | #.idea/
162 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # 📚 PCPP1™ – Certified Professional in Python Programming 1 (Exam PCPP-32-10x) Dumps
2 |
3 | ## 🌟 Overview
4 |
5 | This README describes my experience with the PCPP1 exam. This exam is intended to assess one's
6 | knowledge and skills in Python programming. I'd like to offer some analysis of the exam, covering my preparation, the
7 | structure of the test and my general experience.
8 |
9 | ## 📖 Background
10 |
11 | I made the decision to work toward the PCPP1 certification in order to improve my Python programming abilities and
12 | get recognition for my knowledge. Being certified in Python, a flexible and popular programming language, can lead to
13 | number of job opportunities.
14 |
15 | ## 📋 Preparation
16 |
17 | ### 📚 Study Materials
18 |
19 | I prepared for the PCPP1 exam using a combination of study materials, including:
20 |
21 | * **Official Python Institute PCPP1 Certification Guide:** This comprehensive guide covered all the topics required for
22 | the exam. It provided in-depth explanations, examples, and practice questions.
23 |
24 | 1) [Advanced OOP](https://edube.org/study/pcpp1-1)
25 | 1) [Best Practices and Standardization](https://edube.org/study/pcpp1-2)
26 | 1) [GUI Programming](https://edube.org/study/pcpp1-2)
27 | 1) [Network Programming](https://edube.org/study/pcpp1-3)
28 | 1) [File Processing and Communicating with a Program's Environment](https://edube.org/study/pcpp1-4)
29 |
30 | Some exercises you can find [in](src/exercices).
31 |
32 | * **Practice Exams**:
33 | I took multiple practice exams to get a feel for the exam format and to identify areas where I needed more practice.
34 | Some of the files in this repository are owned by [*OpenEDG*](dumps/1.%20POO.md).
35 |
36 | Dumps that I recommend consist of six parts with 70 questions: [Udemy - Paweł Krakowiak](https://www.udemy.com/course/pcpp1-certified-professional-in-python-programming/) it is
37 | worth every penny. I can't share in this repo for privacy reasons.
38 | If you are interested, I can share some with you. Write me: [email](awainerc@gmail.com)
39 |
40 | * **Python Documentation**:
41 | The official Python documentation was an invaluable resource. It helped me understand Python concepts in detail.
42 | Particularly
43 | about [TKinter](https://docs.python.org/3/library/tk.html), [request](https://requests.readthedocs.io/en/latest/)
44 | and https://docs.python.org/3/library/socket.html
45 |
46 | ### 🖥️ **Hands-on Coding**
47 |
48 | I spent a significant amount of time coding in Python to gain practical experience. Writing code and solving
49 | real-world problems helped reinforce my understanding of Python.
50 | I recommend to install [NodeJS](https://nodejs.org/en/download) to simulate server to consume API and Sockets.
51 |
52 | ### 🗓️ **Study Schedule**
53 |
54 | I created a study schedule that spanned several weeks. This allowed me to cover all the topics thoroughly without
55 | feeling rushed.
56 | If you already have the predecessor to this exam, PCAP, and it has not been a long time since you studied it,
57 | It will be much easier to organize your schedule. I studied one module every two weeks because I took the PCAP two years ago.
58 | ago.
59 |
60 | ## 📝 The Exam
61 |
62 | ### 📋 Format
63 |
64 | The PCPP1 exam consists of a series of multiple-choice questions and coding exercises (45 in total). The questions cover
65 | various Python topics, including POO(Study all), Tkinter, API(requests), Socket and a little about network(TCP|UDP). The
66 | coding exercises require candidates to write Python code to solve specific problems.
67 |
68 | ### ⏳ Time Management
69 |
70 | Managing time during the exam is crucial. I allocated a specific amount of time for each section, To be honest you have
71 | plenty of time, make sure you give it two or three checks until you are sure.
72 |
73 | ### 🖥️ Exam Environment
74 |
75 | I took the PCPP1 exam remotely, which required a stable internet connection and a quiet environment. One thing to take
76 | into account here is that the VUE platform through which the exam is given, is disgusting, personally I do not recommend
77 | it to anyone but it's the only way at the moment and many companies use it, their graphics are old and unpleasant.
78 |
79 | ### 💡 Tips
80 |
81 | Read each question carefully and ensure you understand the requirements before attempting to answer.
82 |
83 | * For coding exercises, Don't be nervous, you are not going to write code, but you will need to concentrate to analyze,
84 | pay attention to each sign, space or character. The exercises are not difficult but they are to be careful in the
85 | details.
86 |
87 | * Double-check your answers before submitting. It's easy to make simple mistakes, so review your work.
88 |
89 | ## 🏆 My Experience
90 |
91 | The PCPP1 exam was challenging but rewarding. It tested my knowledge of Python thoroughly. However, I would have to say
92 | that this exam was a bit complex, there are some very tricky questions and besides technical knowledge you need
93 | experience with the language or tools.
94 |
95 | Don't be discouraged, life is a challenge.
96 |
97 | ## 🎉 Conclusion
98 |
99 | For this exam you need dedication, my recommendation is if you are starting in the Python world and you want to achieve
100 | this, first take the PCEP, second the PCAP and then don't let more time pass by, study this one,
101 | It is possible to get this one without having the previous certifications, but you need a lot of experience with the
102 | concepts of programming, networking, GUI and file management in Python.
103 |
104 | Passing the PCPP1 exam was a significant milestone in my journey to becoming a certified Python programmer. It validated
105 | my Python skills and provided me with a valuable certification recognized in the industry.
106 |
107 | I encourage anyone looking to enhance their Python programming skills to consider pursuing the PCPP1 certification. With
108 | the right preparation and determination, it's an achievable goal that can open doors to exciting career opportunities in
109 | Python development.
110 |
111 | If you have any questions or need advice on preparing for the PCPP1 exam, feel free to reach out. I'm here to help!
112 |
113 | Best regards,
114 |
115 | @anthonywainer
116 |
117 | Feel free to personalize and expand upon this repo to share your unique experience with the PCPP1 exam. Congratulations
118 | on arriving here!
119 |
--------------------------------------------------------------------------------
/src/exercices/cars_practice.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 | Service_URI = 'http://localhost:3000/cars/'
5 | h_close = {'Connection': 'Close'}
6 | h_content = {'Content-Type': 'application/json'}
7 | column_headers = ["id", "brand", "model", "production_year", "convertible"]
8 | column_widths = [10, 15, 10, 20, 15]
9 |
10 |
11 | def check_server(cid=None):
12 | uri = Service_URI
13 | if cid:
14 | uri += str(cid)
15 | try:
16 | res = requests.head(uri, headers=h_close)
17 | except requests.exceptions.RequestException:
18 | return False
19 | return res.status_code == requests.codes.ok
20 |
21 |
22 | def print_menu():
23 | print("+-----------------------------------+")
24 | print("| Vintage Cars Database |")
25 | print("+-----------------------------------+")
26 | print("M E N U")
27 | print("=======")
28 | print("1. List cars")
29 | print("2. Add new car")
30 | print("3. Delete car")
31 | print("4. Update car")
32 | print("0. Exit")
33 |
34 |
35 | def read_user_choice():
36 | ok = False
37 | while not ok:
38 | answer = input("Enter your choice (0..4): ")
39 | ok = answer in ['0', '1', '2', '3', '4']
40 | if ok:
41 | return answer
42 | print("Bad choice!")
43 |
44 |
45 | def print_header():
46 | for (head, width) in zip(column_headers, column_widths):
47 | print(head.ljust(width), end='| ')
48 | print()
49 |
50 |
51 | def print_car(car):
52 | for (name, width) in zip(column_headers, column_widths):
53 | print(str(car[name]).ljust(width), end='| ')
54 | print()
55 |
56 |
57 | def list_cars():
58 | try:
59 | res = requests.get(Service_URI)
60 | except requests.exceptions.RequestException:
61 | print("Communication error :(")
62 | return
63 | cars = res.json()
64 | if len(cars) == 0:
65 | print("*** Database is empty ***")
66 | return
67 | print_header()
68 | for car in cars:
69 | print_car((car))
70 | print()
71 |
72 |
73 | def name_is_valid(name):
74 | for char in name:
75 | if not (char.isspace() or char.isdigit() or char.isalpha()):
76 | return False
77 | return True
78 |
79 |
80 | def enter_id():
81 | while True:
82 | id = input("Car ID (empty string to exit): ")
83 | if not id or id.isspace():
84 | return None
85 | if not id.isdigit():
86 | print("Invalid ID - re-enter.")
87 | continue
88 | return int(id)
89 |
90 |
91 | def enter_production_year():
92 | while True:
93 | prod_year = input("Car production year (empty string to exit): ")
94 | if not prod_year or prod_year.isspace():
95 | return None
96 | if not prod_year.isdigit() or not 1900 <= int(prod_year) <= 2023:
97 | print("Invalid production year - re-enter.")
98 | continue
99 | return int(prod_year)
100 |
101 |
102 | def enter_name(what):
103 | while True:
104 | name = input("Car " + what + " (empty string to exit): ")
105 | if name == '' or name.isspace():
106 | return None
107 | if not name_is_valid(name):
108 | print(what.title() + ' contains illegal characters - re-enter.')
109 | continue
110 | return name.title()
111 |
112 |
113 | def enter_convertible():
114 | while True:
115 | conv = input("Is this car convertible? [y/n] (empty string to exit): ")
116 | if conv == '':
117 | return None
118 | if conv.upper() not in ['Y', 'N']:
119 | print("Invalid input - re-enter.")
120 | continue
121 | return conv in ['y', 'Y']
122 |
123 |
124 | def delete_car():
125 | while True:
126 | id = enter_id()
127 | if not id:
128 | return
129 | try:
130 | res = requests.delete(Service_URI + str(id))
131 | except requests.exceptions.RequestException:
132 | print('Communication error - delete failed.')
133 | return
134 | if res.status_code == requests.codes.not_found:
135 | print("Unknown ID - nothing has been deleted")
136 | continue
137 | print("Success!")
138 |
139 |
140 | def input_car_data(with_id):
141 | if with_id:
142 | car_id = enter_id()
143 | if car_id is None:
144 | return {}
145 | else:
146 | car_id = 0
147 | brand = enter_name('brand')
148 | if brand is None:
149 | return {}
150 | model = enter_name('model')
151 | if model is None:
152 | return {}
153 | prod_year = enter_production_year()
154 | if prod_year is None:
155 | return {}
156 | conv = enter_convertible()
157 | if conv is None:
158 | return {}
159 | return {'id': car_id, 'brand': brand, 'model': model, 'production_year': prod_year, 'convertible': conv}
160 |
161 |
162 | def add_car():
163 | new_car = input_car_data(True)
164 | if not new_car:
165 | return
166 | try:
167 | res = requests.post(Service_URI, headers=h_content, data=json.dumps(new_car))
168 | except requests.exceptions.RequestException:
169 | print('Communication error - adding new car failed')
170 | return
171 | if res.status_code != 201:
172 | print("Duplicated car ID - adding new car failed")
173 |
174 |
175 | def update_car():
176 | while True:
177 | car_id = enter_id()
178 | if not car_id:
179 | return
180 | if not check_server(car_id):
181 | print("Car ID not found in the database.")
182 | else:
183 | break
184 | car = input_car_data(False)
185 | if not car:
186 | return
187 |
188 | car["id"] = car_id
189 | try:
190 | res = requests.put(Service_URI + str(car_id), headers=h_content, data=json.dumps(car))
191 | except requests.exceptions.RequestException:
192 | print('Communication error - updating car data failed')
193 | return
194 | if res.status_code != requests.codes.ok:
195 | print("Duplicated car ID - adding new car failed")
196 |
197 |
198 | while True:
199 | if not check_server():
200 | print("Server is not responding - quitting!")
201 | exit(1)
202 | print_menu()
203 | choice = read_user_choice()
204 | if choice == '0':
205 | print("Bye!")
206 | exit(0)
207 | elif choice == '1':
208 | list_cars()
209 | elif choice == '2':
210 | add_car()
211 | elif choice == '3':
212 | delete_car()
213 | elif choice == '4':
214 | update_car()
215 |
--------------------------------------------------------------------------------
/dumps/4. API.md:
--------------------------------------------------------------------------------
1 | # 4. Questions PCPP1 - API
2 |
3 | 1. 👉**An IP4 address consists of:**
4 | 1. 32 bits
5 | 1. 64 bits
6 | 1. 16 bits
7 | \
8 |
9 | *🗝️ Ans. i*
10 | \
11 |
12 | 1. 👉**Double parentheses used in the following invocation:**
13 |
14 | ```python
15 | sock.connect((srvaddr, 80))
16 | ```
17 | are:
18 |
19 | 1. redundant and should be removed
20 | 1. redundant but acceptable in this context
21 | 1. necessary as the invocation's argument is a tuple
22 | \
23 |
24 | *🗝️ Ans. iii*
25 | \
26 |
27 | 1. 👉**JSON is in fact:**
28 | 1. a UTF text
29 | 1. a binary data stream
30 | 1. an ASCII text
31 | \
32 |
33 | *🗝️ Ans. i*
34 | \
35 |
36 | 1. 👉**An empty value, described by Python as None, is reflected by the JSON element named:**
37 | 1. NULL
38 | 1. null
39 | 1. Null
40 | \
41 |
42 | *🗝️ Ans. ii*
43 | \
44 |
45 | 1. 👉**An object of any class:**
46 | 1. is not JSON-serializable by default
47 | 1. is always JSON-serializable
48 | 1. is either JSON-serializable by default, or can be turned into such an object
49 | \
50 |
51 | *🗝️ Ans. i*
52 | \
53 |
54 | 1. 👉**An XML comment is a text surrounded by:**
55 | 1. < * and *>
56 | 1. ``
57 | 1. // and
58 | \
59 |
60 | *🗝️ Ans. ii*
61 | \
62 |
63 | 1. 👉**The number placed after the colon inside the following invocation, describes:**
64 |
65 | ```python
66 | r = requests.get('http://localhost:3000')
67 | ```
68 |
69 | 1. the request timeout (in milliseconds)
70 | 1. the maximum length of the request
71 | 1. the server's port number
72 | \
73 |
74 | *🗝️ Ans. iii*
75 | \
76 |
77 | 1. 👉**The following invocation:**
78 |
79 | ```python
80 | requests.delete('http://uri/resource')
81 | ```
82 |
83 | requires that the specified:
84 |
85 | 1. client-server connection should be dropped
86 | 1. request should be deleted from the client
87 | 1. resource should be deleted from the server
88 | \
89 |
90 | *🗝️ Ans. iii*
91 | \
92 |
93 | 1. 👉**Updating a resource:**
94 |
95 | ```python
96 | requests.delete('http://uri/resource')
97 | ```
98 |
99 | is usually performed by the HTTP method called:
100 |
101 | 1. MODIFY
102 | 1. PUT
103 | 1. UPDATE
104 | \
105 |
106 | *🗝️ Ans. ii*
107 | \
108 |
109 | 1. 👉**If a request requires some additional parameters, they are all placed inside one URI and separated by:**
110 | 1. `i`
111 | 1. `&`
112 | 1. `+`
113 | 1. `a space`
114 | \
115 |
116 | *🗝️ Ans. ii*
117 | \
118 |
119 | 1. 👉**The following symbol:**
120 |
121 | ```python
122 | socket.timeout
123 | ```
124 | is the name of:
125 |
126 | 1. an exception
127 | 1. a class
128 | 1. a function
129 | 1. a method
130 | \
131 |
132 | *🗝️ Ans. i*
133 | \
134 |
135 | 1. 👉**What happens when a resource intended for removal does not exist?**
136 |
137 | ```python
138 | r = requests.delete("http://uri/resource")
139 | ```
140 |
141 | 1. `r.status_code` is set to `requests.codes.not_found`
142 | 1. headers is empty
143 | 1. r is set to None
144 | 1. an exception is raised
145 | \
146 |
147 | *🗝️ Ans. i*
148 | \
149 |
150 | 1. 👉**Each XML document contains: (select all that apply)**
151 | 1. any(excluding zero) number of root elements
152 | 1. exactly one root element
153 | 1. any(including zero) number of root elements
154 | 1. any(including zero) number of non-root elements
155 | \
156 |
157 | *🗝️ Ans. ii, iv*
158 | \
159 |
160 | 1. 👉**If the word CRUD is taken as a sorting criterium, which of the following is a properly sorted list of HTTP verbs?
161 | **
162 | 1. GET, DELETE, PUT, POST
163 | 1. DELETE, POST, GET, PUT
164 | 1. POST, GET, PUT, DELETE
165 | 1. POST, PUT, DELETE, GET
166 | \
167 |
168 | *🗝️ Ans. iii*
169 | \
170 |
171 | 1. 👉**The term keep-alive refers to:**
172 | 1. the way in which the server keeps itself running
173 | 1. the client's mode of connection management
174 | 1. the server's mode of connection management
175 | 1. the way in which the client keeps itself running
176 | \
177 |
178 | *🗝️ Ans. ii*
179 | \
180 |
181 | 1. 👉**Port (or service) number is an int value whose length is equal to:**
182 | 1. 8 bits
183 | 1. 32 bits
184 | 1. 16 bits
185 | 1. 64 bits
186 | \
187 |
188 | *🗝️ Ans. iii*
189 | \
190 |
191 | 1. 👉**UDP is a protocol featured by the following traits: (select all that apply)**
192 | 1. it is an example of connection-oriented protocol
193 | 1. it does not use handshakes
194 | 1. it is primarily used by HTTP
195 | 1. it is faster than TCP
196 | \
197 |
198 | *🗝️ Ans. ii, iv*
199 | \
200 |
201 | 1. 👉**The `SOCK_STREAM` symbol describes a socket which is able to transmit single:**
202 | 1. bits
203 | 1. characters
204 | 1. int values
205 | 1. datagrams
206 | \
207 |
208 | *🗝️ Ans. iv*
209 | \
210 |
211 | 1. 👉**The following invocation:**
212 |
213 | ```python
214 | requests.get('http://localhost:3000')
215 | ```
216 | returns:
217 |
218 | 1. an integer number
219 | 1. a string of non-zero length
220 | 1. None
221 | 1. an object
222 | \
223 |
224 | *🗝️ Ans. iv*
225 | \
226 |
227 | 1. 👉**The `json.loads()` method: (select all that apply)**
228 | 1. returns a string
229 | 1. takes Python data as its argument
230 | 1. takes a JSON string as its argument
231 | 1. returns a JSON object
232 | \
233 |
234 | *🗝️ Ans. iii, iv*
235 | \
236 |
237 | 1. 👉**The word REST is an acronym and the letter S stands for:**
238 | 1. State
239 | 1. Semi
240 | 1. Synchronous
241 | 1. Serial
242 | \
243 |
244 | *🗝️ Ans. i*
245 | \
246 |
247 | 1. 👉**An empty JSON object looks like:**
248 | 1. {}
249 | 1. ()
250 | 1. []
251 | \
252 |
253 | *🗝️ Ans. i*
254 | \
255 |
256 | 1. 👉**In the JSON processing context, the term deserialization:**
257 | 1. refers to nothing as there is no such thing as JSON deserialization
258 | 1. names a process in which a JSON string is remodeled and transformed into a new JSON string
259 | 1. names a process in which a JSON string is turned into Python data
260 | 1. names a process in which the Python data is turned into a JSON string
261 | \
262 |
263 | *🗝️ Ans. iii*
264 | \
265 |
266 | 1. 👉**Which of the following presents the proper form of putting a quote inside a JSON string?**
267 | 1. " “ "
268 | 1. ‘ “ ‘
269 | 1. “ \” “
270 | 1. " “” “
271 | \
272 |
273 | *🗝️ Ans. iii*
274 | \
275 |
276 | 1. 👉**A value, described by Python as True, is reflected by the JSON element called:**
277 | 1. 1
278 | 1. TRUE
279 | 1. true
280 | 1. True
281 | \
282 |
283 | *🗝️ Ans. iii*
284 | \
285 |
286 | 1. 👉**A DTD is:**
287 | 1. a synonym for an XML document
288 | 1. one of the possible types of an XML document
289 | 1. a part of an XML document
290 | 1. a document describing the structure of an XML document
291 | \
292 |
293 | *🗝️ Ans. iv*
294 | \
295 |
296 | 1. 👉**The recv method's argument:**
297 |
298 | ```python
299 | answ = sock.recv(10000)
300 | ```
301 |
302 | 1. the length of a single message that the socket can accept
303 | 1. how many messages the socket can accept
304 | 1. is a number which specifies:
305 | 1. how long recv is ready to wait for data
306 | 1. the length of recv's internal buffer
307 | \
308 |
309 | *🗝️ Ans. v*
310 | \
311 |
312 | 1. 👉**The `json.dumps()` method: (select all that apply)**
313 | 1. takes Python data as its argument
314 | 1. takes a JSON string as its argument
315 | 1. returns Python data
316 | 1. returns a JSON string
317 | \
318 |
319 | *🗝️ Ans. i, iv*
320 | \
321 |
322 | 1. 👉**If you want to put an integer number into a JSON string, you can do so using radices:**
323 | 1. 16
324 | 1. 10
325 | 1. 8
326 | 1. 2
327 | \
328 |
329 | *🗝️ Ans. ii*
330 | \
331 |
332 | 1. 👉**When the request module is not able to establish a connection with the desired server:**
333 |
334 | ```python
335 | r = requests.get(uri)
336 | ```
337 |
338 | 1. is equal to None
339 | 1. is set to integer zero
340 | 1. an exception is raised
341 | 1. is an empty object
342 | \
343 |
344 | *🗝️ Ans. iii*
--------------------------------------------------------------------------------
/dumps/5. FILES.md:
--------------------------------------------------------------------------------
1 | # 5. Questions PCPP1 - FILES
2 |
3 | 1. 👉**Which of the following methods exist in the `DictWriter` object provided by the csv module? (Select all that
4 | apply.)**
5 | 1. `write`
6 | 1. `writerow`
7 | 1. `writeseparator`
8 | 1. `writeheader`
9 | \
10 |
11 | *🗝️ Ans. ii, iv*
12 | \
13 |
14 | 1. 👉**Which of the following logging levels has the highest value?**
15 | 1. ERROR
16 | 1. CRITICAL
17 | 1. WARNING
18 | 1. DEBUG
19 | \
20 |
21 | *🗝️ Ans. ii*
22 | \
23 |
24 | 1. 👉**Which of the following expressions is the correct interpolation syntax used in INI files?**
25 | 1. `%(localhost)i`
26 | 1. `%(localhost)s`
27 | 1. `%localhost%`
28 | 1. `%(localhost)`
29 | \
30 |
31 | *🗝️ Ans. ii*
32 | \
33 |
34 | 1. 👉**Which of the following calls will return the root logger?**
35 | 1. ```python
36 | import logging
37 | logger = logging.getLogger( __main__)
38 | ```
39 | 1. ```python
40 | import logging
41 | logger = logging.getRootLogger()
42 | ```
43 | 1. ```python
44 | import logging
45 | logger = logging.getLogger()
46 | ```
47 | 1. ```python
48 | import logging
49 | logger = logging.getLogger('root')
50 | ```
51 |
52 | \
53 |
54 | *🗝️ Ans. iii*
55 | \
56 |
57 |
58 | 1. 👉**Which of the following logs represents the default formatting of the root logger?**
59 | 1. root:CRITICAL:Message
60 | 1. Message:CRITICAL:root
61 | 1. Message:root:CRITICAL
62 | 1. CRITICAL:root:Message
63 | \
64 |
65 | *🗝️ Ans. iv*
66 | \
67 |
68 | 1. 👉**What is the result of the following code?**
69 |
70 | ```python
71 | import configparser
72 |
73 | config = configparser.ConfigParser()
74 | config['DEFAULT'] = {'host': 'localhost', 'env': 'dev'}
75 | config['mysql'] = {'host': 'localhost', 'env': 'dev'}
76 | config['postgresql'] = {'host': '127.0.0.1', 'env': 'prod'}
77 | config['mongodb'] = {}
78 |
79 | print(config['mysql']['env'])
80 | print(config['postgresql']['env'])
81 | print(config['mongodb']['env'])
82 | ```
83 | 1. dev \
84 | prod
85 |
86 | 1. dev \
87 | dev \
88 | dev
89 |
90 | 1. dev \
91 | prod \
92 | dev
93 |
94 | 1. An exception will be raised.
95 | \
96 |
97 | *🗝️ Ans. iii*
98 | \
99 |
100 | 1. 👉**Select the code snippets that represent the correct connection to the database. (Select all that apply.)**
101 |
102 | 1. ```python
103 | import sqlite3
104 | conn = sqlite3.connect(':memory:')
105 | ```
106 |
107 | 1. ```python
108 | import sqlite3
109 | conn = sqlite3.connect()
110 | ```
111 |
112 | 1. ```python
113 | import sqlite3
114 | conn = sqlite3.connect('C:\\sqlite store.db')
115 | ```
116 |
117 | 1. ```python
118 | import sqlite3
119 | conn = sqlite3.conn('C:\\sqlite\store.db')
120 | ```
121 |
122 | \
123 |
124 | *🗝️ Ans. i, iii*
125 | \
126 |
127 |
128 | 1. 👉**What is the name of the section in INI files that contains entries for the other sections?**
129 | 1. INI
130 | 1. MAIN
131 | 1. GLOBAL
132 | 1. DEFAULT
133 |
134 | *🗝️ Ans. iv*
135 |
136 | 1. 👉**Which of the following SELECT statements have the correct syntax? (Select all that apply.)**
137 |
138 | id
139 | name
140 | fruit
141 |
142 | 1. `SELECT FROM fruit;`
143 | 1. `SELECT * FROM fruit;`
144 | 1. `SELECT id, name FROM fruit;`
145 | 1. `SELECT ALL FROM fruit;`
146 | \
147 |
148 | *🗝️ Ans. ii, iii*
149 | \
150 |
151 | 1. 👉**Select the XML modules available in the Python standard library: (Select all that apply.)**
152 | 1. `xml.parser`
153 | 1. `xml.processor`
154 | 1. `xml.etree.ElementTree`
155 | 1. `xml.dom.minidom`
156 | \
157 |
158 | *🗝️ Ans. iii, iv*
159 | \
160 |
161 | 1. 👉**Which of the following methods is used to find elements in the `xml.etree.ElementTree` module? (Select all that
162 | apply.)**
163 | 1. `findone`
164 | 1. `findall`
165 | 1. `iter`
166 | 1. `find`
167 | \
168 |
169 | *🗝️ Ans. ii, iv*
170 | \
171 |
172 | 1. 👉**Which of the following attributes have the `LogRecord` object? (Select all that apply.)**
173 | 1. `%(levelname)s`
174 | 1. `%(asctime)s`
175 | 1. `%(name)s`
176 | 1. `%(message)s`
177 | \
178 |
179 | *🗝️ Ans. all*
180 | \
181 |
182 | 1. 👉**Which of the following logging levels has the lowest value?**
183 | 1. INFO
184 | 1. WARNING
185 | 1. DEBUG
186 | 1. NOTSET
187 | \
188 |
189 | *🗝️ Ans. iv*
190 | \
191 |
192 | 1. 👉**Select the true statements about XML: (Select all that apply.)**
193 |
194 | 1. Each element contains at least one attribute.
195 | 1. Each XML document must have a root element.
196 | 1. Each open XML tag must have a corresponding closing tag.
197 | 1. Each XML document must have a prolog.
198 | \
199 |
200 | *🗝️ Ans. ii, iii*
201 | \
202 |
203 | 1. 👉**Which of the following strings are used to separate key/value entries in INI files? (Select all that apply.)**
204 | 1. `:`
205 | 1. `=`
206 | 1. `=>`
207 | 1. `-`
208 | \
209 |
210 | *🗝️ Ans. i, ii*
211 | \
212 |
213 | 1. 👉**Select the classes provided by the `sqlite3` module. (Select all that apply.)**
214 | 1. Query
215 | 1. Cursor
216 | 1. Transaction
217 | 1. Connection
218 | \
219 |
220 | *🗝️ Ans. ii, iv*
221 | \
222 |
223 | 1. 👉**Which of the following features describe SQLite? (Select all that apply.)**
224 | 1. serverless
225 | 1. zero-configuration
226 | 1. self-contained
227 | 1. transactional
228 | \
229 |
230 | *🗝️ Ans. all*
231 | \
232 |
233 | 1. 👉**Which of the following methods exist in the sqlite3 module? (Select all that apply.)**
234 | 1. `fetchone`
235 | 1. `find`
236 | 1. `fetchall`
237 | 1. `findall`
238 | \
239 |
240 | *🗝️ Ans. i, iii*
241 | \
242 |
243 | 1. 👉**In the csv module, reading data from a csv file is possible using: (Select all that apply.)**
244 |
245 | 1. the `reader` function
246 | 1. the `CsvReader` class
247 | 1. the `DictReader` class
248 | 1. the `read_csv` function
249 | \
250 |
251 | *🗝️ Ans. i, iii*
252 | \
253 |
254 | 1. 👉**A typical INI file consists of: (Select all that apply.)**
255 | 1. key/value entries
256 | 1. sections
257 | 1. attributes
258 | 1. groups
259 | \
260 |
261 | *🗝️ Ans. i, ii*
262 | \
263 |
264 | 1. 👉**An XML document includes: (Select all that apply.)**
265 | 1. a prolog
266 | 1. a root element
267 | 1. attributes
268 | 1. properties
269 | \
270 |
271 | *🗝️ Ans. i, ii, iii*
272 | \
273 |
274 | 1. 👉**What is the default encoding of an XML document?**
275 | 1. `UTF-16`
276 | 1. `ISO-8859-2`
277 | 1. `Windows-1250`
278 | 1. `UTF-8`
279 | \
280 |
281 | *🗝️ Ans. iv*
282 | \
283 |
284 | 1. 👉**Which of the following examples will run correctly? (Select all that apply.)**
285 |
286 | 1. ```python
287 | import csv
288 |
289 | with open('subjects.csv', 'w', newline='') as csvfile:
290 | writer = csv.DictWriter(csvfile)
291 | writer.writerow({'Name': 'maths'})
292 | writer.writerow({'Name': 'physics'})
293 | ```
294 |
295 | 1. ```python
296 | import csv
297 |
298 | with open('subjects.csv', 'w', newline='') as csvfile:
299 | writer = csv.DictWriter(csvfile)
300 | writer.writeheader()
301 | writer.writerow({'Name': 'maths'})
302 | writer.writerow({'Name': 'physics'})
303 | ```
304 |
305 | 1. ```python
306 | import csv
307 | with open('subjects.csv', 'w', newline='') as csvfile:
308 | fieldnames = ['Name']
309 |
310 | writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
311 | writer.writeheader()
312 | writer.writerow({'Name': 'maths'})
313 | writer.writerow({'Name': 'physics'})
314 | ```
315 |
316 | 1. ```python
317 | import csv
318 |
319 | with open('subjects.csv', 'w', newline='') as csvfile:
320 | fieldnames = ['Name']
321 |
322 | writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
323 | writer.writerow({'Name': 'maths'})
324 | writer.writerow({'Name': 'physics'})
325 | ```
326 |
327 | \
328 |
329 | *🗝️ Ans. iii, iv*
330 | \
331 |
332 |
333 | 1. 👉**Which one of the following methods returns the root element in the `xml.etree.ElementTree` module?**
334 | 1. `parent`
335 | 1. `getroot`
336 | 1. `getparent`
337 | 1. `root`
338 | \
339 |
340 | *🗝️ Ans. ii*
341 | \
342 |
343 | 1. 👉**Which of the following methods do not exist in the sqlite3 module? (Select all that apply.)**
344 | 1.`executeone`
345 | 1.`executemany`
346 | 1.`executeall`
347 | 1.`execute`
348 | \
349 |
350 | *🗝️ Ans. i, iii*
351 | \
352 |
353 | 1. 👉**In the csv module, saving data to a csv file is possible using: (Select all that apply.)**
354 | 1. the `DictWriter` class
355 | 1. the `Csv_writer` class
356 | 1. the `writer` function
357 | 1. the `write_csv` function
358 | \
359 |
360 | *🗝️ Ans. i, iii*
361 | \
362 |
363 | 1. 👉**Which one of the following methods saves the changes made to a database?**
364 | 1. `close`
365 | 1. `execute`
366 | 1. `commit`
367 | 1. `save`
368 | \
369 |
370 | *🗝️ Ans. iii*
371 | \
372 |
373 | 1. 👉**Select the methods for parsing an XML document provided by the `xml.etree.ElementTree` module: (Select all that
374 | apply.)**
375 | 1. `parsexml`
376 | 1. `parsefromstring`
377 | 1. `fromstring`
378 | 1. `parse`
379 | \
380 |
381 | *🗝️ Ans. iii, iv*
--------------------------------------------------------------------------------
/dumps/3. TKINTER.md:
--------------------------------------------------------------------------------
1 | # 3. Questions PCPP1 - TKINTER
2 |
3 | 1. 👉**A paradigm used in GUI programming is called:**
4 | 1. Low-Level Programming
5 | 1. Event-Driven Programming
6 | 1. Artificial Intelligence
7 | 1. Stream-Oriented Programming
8 | \
9 |
10 | *🗝️ Ans. ii*
11 | \
12 |
13 | 1. 👉**If your window's size is `200x200`, what are the coordinates of the pixel located in top-right window corner?**
14 | 1. `x=0, y=0`
15 | 1. `x=200, y=200`
16 | 1. `x=200, y=0`
17 | 1. `x=0, y=200`
18 | \
19 |
20 | *🗝️ Ans. iii*
21 | \
22 |
23 | 1. 👉**Which of the following are Tkinter geometry managers?**
24 | 1. `pack()`
25 | 1. `put()`
26 | 1. `place()`
27 | 1. `grid()`
28 | \
29 |
30 | *🗝️ Ans. i, iii, iv*
31 | \
32 |
33 | 1. 👉**The color described as `#008800` is:**
34 | 1. dark green
35 | 1. grey
36 | 1. light blue
37 | 1. purple
38 | \
39 |
40 | *🗝️ Ans. i*
41 | \
42 |
43 | 1. 👉**The very first argument of each widget constructor can be:**
44 | 1. any integer number
45 | 1. an enclosing frame widget
46 | 1. an object of any class
47 | 1. a root window
48 | \
49 |
50 | *🗝️ Ans. ii, iv*
51 | \
52 |
53 | 1. 👉**If you want to assign a callback to a widget which lacks the command property, which method would you use?**
54 | 1. `bind()`
55 | 1. `callback()`
56 | 1. `assign()`
57 | 1. `command()`
58 | \
59 |
60 | *🗝️ Ans. i*
61 | \
62 |
63 | 1. 👉**If you want to set a wdg widget's property named x with an integer value of 100, which of the code lines would you
64 | use?**
65 | 1. `wdg.set(x, 100)`
66 | 1. `wdg(x=100)`
67 | 1. `wdg["x"] = 100`
68 | 1. `wdg.config(x=100)`
69 | \
70 |
71 | *🗝️ Ans. iii, iv*
72 | \
73 |
74 | 1. 👉**Look at the code below. Enter an appropriate line of code which will cause the application to quit immediately.**
75 |
76 | ```python
77 | import tkinter
78 |
79 | def q():
80 | ...
81 |
82 | w = tkinter.Tk()
83 | b = tkinter.Button(w, text='Quit', command=q)
84 | b.pack()
85 |
86 | w.mainloop()
87 | ```
88 |
89 | \
90 |
91 | *🗝️ Ans. `w.destroy()`*
92 | \
93 |
94 |
95 | 1. 👉**What is the expected result of running the following code?**
96 |
97 | ```python
98 | from tkinter import *
99 |
100 | W = Tk()
101 | s = StringVar()
102 | n = int(s)
103 |
104 | print(n)
105 | ```
106 | 1. it will print 0
107 | 1. it will raise an exception
108 | 1. it will print an empty line
109 | 1. it won't start
110 | \
111 |
112 | *🗝️ Ans. ii*
113 | \
114 |
115 | 1. 👉**Let's assume that you're working on a project and have found out that manual invoking of your own callback can
116 | simplify the code. What can you do now?**
117 | 1. invoke the `callback()` method from within a particular widget
118 | 1. nothing; it's impossible
119 | 1. invoke the `invoke()` method from within a particular widget
120 | 1. invoke the root window's method named `call()`
121 | \
122 |
123 | *🗝️ Ans. iii*
124 | \
125 |
126 | 1. 👉**You want the b button to have white background. Which line of code used instead of `...` will make it happen?**
127 |
128 | ```python
129 | from tkinter import *
130 |
131 | w = Tk()
132 | b = Button(w, text="Button")
133 |
134 | ...
135 |
136 | b.pack()
137 | w.mainloop ()
138 | ```
139 | 1. b.setbackgorund(white)
140 | 1. b.bg = 0xFFFFFF
141 | 1. b.config(bg='white')
142 | 1. b["bg"] = "#FFFFFF"
143 | \
144 |
145 | *🗝️ Ans. iii, iv*
146 | \
147 |
148 | 1. 👉**What can be said about the Message widget?**
149 | 1. it sends a message to console
150 | 1. it's very similar to the Label widget
151 | 1. it can automatically format its inner text
152 | 1. it opens a modal dialog window
153 | \
154 |
155 | *🗝️ Ans. ii, iii*
156 | \
157 |
158 | 1. 👉**What can be said about the Entry widget?**
159 | 1. the input field content can be accessed as the `get()` method's result
160 | 1. it can grab and lose focus
161 | 1. the input field content can be accessed through an observable variable
162 | 1. the text processed by the widget cannot be changed programmatically
163 | \
164 |
165 | *🗝️ Ans. i, ii, iii*
166 | \
167 |
168 | 1. 👉**You decided not to allow the user to change your application window's size. What would you do?**
169 | 1. invoke the `lockmainwindow()` function
170 | 1. it cannot be done as the user is always allowed to change any window's size
171 | 1. set the windows's locked property to True
172 | 1. invoke the `resizable()` method from within the root window object
173 | \
174 |
175 | *🗝️ Ans. iv*
176 | \
177 |
178 | 1. 👉**Your window is `200x200` pixels and fully filled with the Canvas widget. You want to draw a diagonal starting in
179 | top-left and ending in bottom-right corner. Complete the code below to achieve this effect.**
180 |
181 | ```python
182 | from tkinter import *
183 |
184 | w = Tk()
185 | c = Canvas (w, height=200, width=200)
186 | c.pack()
187 | c.create_line(...)
188 | w.mainloop()
189 | ```
190 |
191 | \
192 |
193 | *🗝️ Ans. `0, 0, 200, 200`*
194 | \
195 |
196 |
197 | 1. 👉**A widget deployed inside a window by the `grid()` geometry manager: (Select three answers and explain)**
198 | 1. can occupy more than one cell in the same column
199 | 1. can occupy more than one cell in the same row
200 | 1. can occupy the whole window's interior
201 | 1. can be adjusted with pixel accuracy
202 | \
203 |
204 | *🗝️ Ans. i, ii, iii*
205 | \
206 |
207 | 1. 👉**fg is a short name for a widget's property called:**
208 | 1. foreground
209 | 1. foregroundcolor
210 | 1. foreground_color
211 | 1. foregroundcolor_global
212 | \
213 |
214 | *🗝️ Ans. i*
215 | \
216 |
217 | 1. 👉**A color model used by Tkinter is:**
218 | 1. additive
219 | 1. subtractive
220 | 1. cylindrical
221 | 1. cubic
222 | \
223 |
224 | *🗝️ Ans. i*
225 | \
226 |
227 | 1. 👉**The anchor property uses the so-called:**
228 | 1. compass coordinates
229 | 1. integral coordinates
230 | 1. polar coordinates
231 | 1. cylindrical coordinates
232 | \
233 |
234 | *🗝️ Ans. i*
235 | \
236 |
237 | 1. 👉**Tkinter represents fonts as:**
238 | 1. tuples
239 | 1. strings
240 | 1. integer numbers
241 | 1. objects of class Font
242 | \
243 |
244 | *🗝️ Ans. i*
245 | \
246 |
247 | 1. 👉**Complete the code to make the b1 button focused.**
248 |
249 | ```python
250 | from tkinter import *
251 |
252 | w = Tk()
253 | b1 = Button(w, text="A")
254 | bl.pack()
255 |
256 | b2 = Button(w, text="B")
257 | b2.pack()
258 |
259 | ...
260 | w.mainloop()
261 | ```
262 |
263 | \
264 |
265 | *🗝️ Ans. `b1.focus_set()`*
266 | \
267 |
268 |
269 | 1. 👉**The width argument passed to the `place()` manager describes a widget size in:**
270 | 1. pixels
271 | 1. characters
272 | 1. inches
273 | 1. millimeters
274 | \
275 |
276 | *🗝️ Ans. i*
277 | \
278 |
279 | 1. 👉**What do you name an event assigned to pressing the "q" key?**
280 | 1. `q`
281 | 1. ``
282 | 1. `Key-Q`
283 | 1. ``
284 | \
285 |
286 | *🗝️ Ans. i*
287 | \
288 |
289 | 1. 👉**An observable variable can:**
290 | 1. own its own callbacks(one or more)
291 | 1. trigger a callback when its value is set
292 | 1. contain a tuple
293 | 1. be a list
294 | \
295 |
296 | *🗝️ Ans. i, ii*
297 | \
298 |
299 | 1. 👉**Which of the following will change the text displayed by the Label widget? (Select two answers)**
300 | 1. `label['text'] = 'change'`
301 | 1. `label.config(text='change')`
302 | 1. `label('text') = 'change'`
303 | 1. `label.text = 'change'`
304 | \
305 |
306 | *🗝️ Ans. i, ii*
307 | \
308 |
309 | 1. 👉**If you want a widget to be completely deaf, you can assign a symbol named tkinter. DISABLED to the property named:
310 | **
311 | 1. state
312 | 1. status
313 | 1. isenabled
314 | 1. isdisabled
315 | \
316 |
317 | *🗝️ Ans. i*
318 | \
319 |
320 | 1. 👉**The Checkbutton widget can use an observable variable to: (Select two answers)**
321 | 1. read the current state of the widget
322 | 1. set the current state of the widget
323 | 1. change the widget's label
324 | 1. move the widget to a new location
325 | \
326 |
327 | *🗝️ Ans. i, ii*
328 | \
329 |
330 | 1. 👉**GUI elements, designed to receive user gestures, are called:**
331 | 1. controls
332 | 1. widgets
333 | 1. rudders
334 | 1. fins
335 | \
336 |
337 | *🗝️ Ans. i, ii*
338 | \
339 |
340 | 1. 👉**Which one of the geometry managers produces different layouts depending on the order of invocations?**
341 | 1. `pack()`
342 | 1. `place()`
343 | 1. `grid()`
344 | 1. there is no such geometry manager
345 | \
346 |
347 | *🗝️ Ans. i*
348 | \
349 |
350 | 1. 👉**The event named `` is assigned to:**
351 | 1. a single middle-click of the mouse button
352 | 1. the currently focused Radiobutton
353 | 1. the currently focused Checkbutton
354 | 1. the power button
355 | \
356 |
357 | *🗝️ Ans. i*
358 | \
359 |
360 | 1. 👉**What can be said about callbacks? (Select two answers)**
361 | 1. one callback can be bound to more than one widget
362 | 1. it is possible to change a callback bound to a widget
363 | 1. setting the command property is the only way to bound a callback
364 | 1. callbacks can be invoked directly from within any part of the code
365 | \
366 |
367 | *🗝️ Ans. i, ii*
368 | \
369 |
370 | 1. 👉**Complete the code in order to create the main window object:**
371 |
372 | ```python
373 | import tkinter
374 |
375 | wnd = ...
376 | wnd.mainloop()
377 | ```
378 |
379 | \
380 |
381 | *🗝️ Ans. `tkinter.Tk()`*
382 | \
383 |
384 |
385 | 1. 👉**Radiobuttons will belong to the same group if they:**
386 | 1. use the same observable variable
387 | 1. have the same name
388 | 1. are assigned to the same object
389 | 1. are deployed in the same column
390 | \
391 |
392 | *🗝️ Ans. i*
393 | \
394 |
395 | 1. 👉**Which of the following describe a shade of grey? (Select two answers)**
396 | 1. `#COCOCO`
397 | 1. `#888888`
398 | 1. `#122112`
399 | 1. `#abcdef`
400 | \
401 |
402 | *🗝️ Ans. i, ii*
403 | \
404 |
405 | 1. 👉**Which of the following data can be obtained from the event object? (Select two answers)**
406 | 1. the mouse cursor location
407 | 1. the event type
408 | 1. current time
409 | 1. the number of the mouse button clicks (if any of the mouse buttons has been clicked)
410 | \
411 |
412 | *🗝️ Ans. i, ii*
413 | \
414 |
415 | 1. 👉**Events scheduled with the `after()` method invocation:**
416 | 1. can be canceled with the `after_cancel()` method invocation
417 | 1. can be canceled with the `cancel_event()` method invocation
418 | 1. the subsequent invocation of the `after()` method with time set to 0
419 | 1. cannot be canceled
420 | \
421 |
422 | *🗝️ Ans. i*
423 | \
424 |
425 | 1. 👉**Complete the code to color the frame interior in black:**
426 |
427 | ```python
428 | import tkinter as tk
429 |
430 | w = tk.Tk()
431 | f = tk.Frame(w)
432 | f.place (width=100, height=100)
433 | f['bg'] = "...”
434 |
435 | w.mainloop()
436 | ```
437 |
438 | \
439 |
440 | *🗝️ Ans. `#000000`*
441 | \
442 |
443 |
444 | 1. 👉**What is assigned to the x variable when the following assignment takes place?**
445 |
446 | > x = IntVar()
447 |
448 | 1. an object carrying 0
449 | 1. an integer value equal to 0
450 | 1. a string set to "0"
451 | 1. the None value
452 | \
453 |
454 | *🗝️ Ans. i*
455 | \
456 |
457 | 1. 👉**The Canvas widget method named create _arc () can display an arc in:**
458 | 1. three shapes
459 | 1. two shapes
460 | 1. one shape
461 | 1. four shapes
462 | \
463 |
464 | *🗝️ Ans. i*
465 | \
466 |
467 | 1. 👉**Tkinter is an interface to a GUI toolkit named:**
468 | 1. Tk
469 | 1. GTK
470 | 1. Qt
471 | 1. Tkl
472 | \
473 |
474 | *🗝️ Ans. i*
--------------------------------------------------------------------------------
/dumps/2. BEST PRACTICES.md:
--------------------------------------------------------------------------------
1 | # 2. Questions PCPP1 - BEST PRACTICES
2 |
3 | 1. 👉**Which one of the naming styles is recommended by PEP 8 for package names?**
4 | 1. A lower-case word or words that are not separated, e.g. `mypackagename`
5 | 1. mixed case word or words that are not separated, e.g. `myPackageName`.
6 | 1. A lower-case word or words that are separated, e.g. `my _package_name`
7 | 1. A CamelCase word or words that are not separated, e.g. `MyPackageName`
8 | \
9 |
10 | *🗝️ Ans. i*
11 | \
12 |
13 | 1. 👉**How can you access docstrings upon file execution?**
14 | 1. By using the `__doc__` attribute or the `help()` function.
15 | 1. You cannot access docstrings upon execution. They can only be accessed by analyzing the code in the source file.
16 | 1. By using the `doc()` function or the `__help__` method.
17 | 1. By using the `doc()` function or the help() function.
18 | 1. By using the `get_docstrings` method or the docs attribute.
19 | \
20 |
21 | *🗝️ Ans. i*
22 | \
23 |
24 | 1. 👉**Select the true statements related to `PEP 8` recommendations for line breaks and continuation lines. (Select two
25 | answers.)**
26 | 1. It is recommended that you break lines before binary operators, not after them.
27 | 1. There is no specific recommendation for line breaks with regard to binary operators.
28 | 1. Under no circumstances are you allowed to split code lines in Python 3.
29 | 1. You should limit all code lines to a maximum of 100 characters, and docstrings/comments to a maximum of 79
30 | characters.
31 | 1. You should limit all code lines to a maximum of 79 characters, and docstrings/comments to a maximum of 72
32 | characters.
33 | \
34 |
35 | *🗝️ Ans. i, v*
36 | \
37 |
38 |
39 | 1. 👉**Which snippet is consistent with PEP 8 recommendations for making comparisons to the `None` object?**
40 | 1. ```python
41 | if a == None:
42 | print("Hello, World!")
43 | ```
44 | 1. ```python
45 | if not a == None:
46 | print("Hello, World!")
47 | ```
48 | 1. ```python
49 | if a None:
50 | print("Hello, World!")
51 | ```
52 | 1. ```python
53 | if not a is None:
54 | print("Hello, World!")
55 | ```
56 | 1. ```python
57 | if a is None:
58 | print("Hello, World!")
59 | ```
60 |
61 | \
62 |
63 | *🗝️ Ans. v*
64 | \
65 |
66 |
67 | 1. 👉**Which of the following statements are consistent with PEP 8 recommendations for using comments, inline comments,
68 | and block comments? (Select two answers)**
69 | 1. Block comments should be delimited by the """ signs.
70 | 1. You should write comments as complete sentences (capitalize the first word and end the sentence with a period).
71 | 1. Block comments should generally refer to the code that follows them.
72 | 1. Block comments should be delimited by the ''' signs.
73 | 1. Block comments should generally refer to the code that precedes them.
74 | 1. Inline comments are the preferred type of comments in Python 3 and should be used in most cases.
75 | \
76 |
77 | *🗝️ Ans. ii, iii*
78 | \
79 |
80 | 1. 👉**Select the true statement related to PEP 8 recommendations for using blank lines.**
81 | 1. It is recommended that you should not use blank lines in your code in order to make it more compact and
82 | maintainable.
83 | 1. It is recommended that you should use one blank line to surround top-level function and class definitions, and
84 | one
85 | blank line to surround method definitions inside a class.
86 | 1. It is recommended that you should use two blank lines to surround top-level function and class definitions, and
87 | two
88 | blank lines to surround method definitions inside a class.
89 | 1. It is recommended that you should use two blank lines to surround top-level function and class definitions, and
90 | one
91 | blank line to surround method definitions inside a class.
92 | \
93 |
94 | *🗝️ Ans. iv*
95 | \
96 |
97 | 1. 👉**Which of the following snippets are consistent with PEP 8 recommendations for using whitespace? (Select two
98 | answers)**
99 | 1. ```python
100 | foo = (cat[ 51], None, { "year": 1985 }, "int")
101 | if 5 in foo:
102 | print ("Yes!")
103 | else:
104 | print ("No!")
105 | ```
106 | 1. ```python
107 | horse[0:3], goat[1:3:5], cow[3:5:], zebra[1::5]
108 | ```
109 | 1. ```python
110 | my_dict = { 'spam': 'one', 'foo': 'bar', 'egg': 'two'}
111 | ```
112 | 1. ```python
113 | horse [0: 3], goat [1: 3: 5], cow [3: 5:1, zebra [1: :5]
114 | ```
115 | 1. ```python
116 | foo = (cat[5], None, {"year": 1985}, 'int')
117 | if 5 in foo: print ("Yes!"); print("No!")
118 | ```
119 |
120 | \
121 |
122 | *🗝️ Ans. ii, v*
123 | \
124 |
125 |
126 | 1. 👉**The PEPs that describe new language features and implementations are called:**
127 | 1. Informational PEPs.
128 | 1. Implementational PEPs.
129 | 1. Process PEPS.
130 | 1. F&L PEPS.
131 | 1. Standard Track PEPs.
132 | \
133 |
134 | *🗝️ Ans. v*
135 | \
136 |
137 | 1. 👉**Who is a PEP champion? (Select the best answer.)**
138 | 1. A person who has a new idea for the development of the Python language and submits this idea to the Python's
139 | Steering
140 | Council.
141 | 1. A person who belongs to the Python Core Developers' team, who's responsible for accepting and rejecting PEPS.
142 | 1. It's another name for Python's BDFL, the title reserved for Guido van Rossum, the original creator of Python and
143 | PEP
144 | documentation.
145 | 1. A person who writes a PEP proposal, puts it up for discussion in subject-related forums, and tries to reach a
146 | community consensus over it.
147 | \
148 |
149 | *🗝️ Ans. iv*
150 | \
151 |
152 | 1. 👉**What is PEP? (Select the best answer.)**
153 | 1. One of the parts of the Style Guide for Python Code documentation, which provides information about code layout,
154 | naming conventions, and programming recommendations. It's a synonymous term for PEP 8.
155 | 1. One of the parts of the Style Guide for Python Code documentation, which provides information about coding
156 | conventions, best practices, and stylistic guidelines. It's a synonymous term for PEP 8.
157 | 1. One of the parts of the Python Developer's Guide documentation, which only contains the list of accepted and
158 | implemented Python Enhancement Proposals, known as PEPs.
159 | 1. One of the parts of the Python Developer's Guide documentation, which contains the list of all Python Enhancement
160 | Proposals, known as PEPs.
161 | 1. One of the parts of the Python Developer's Guide documentation, which contains the list of Python Enhancement
162 | Proposals that are currently under consideration, known as PEPs.
163 | \
164 |
165 | *🗝️ Ans. iv*
166 | \
167 |
168 | 1. 👉**Who is the PEPs' primary audience? (Select the best answer.)**
169 | 1. Python teachers and Python's Core Developers.
170 | 1. Python developers and the Python community.
171 | 1. Project and product managers.
172 | 1. C, C++, and Java programmers.
173 | \
174 |
175 | *🗝️ Ans. ii*
176 | \
177 |
178 | 1. 👉**What instruction(s) will you use to output the Zen of Python aphorisms in the console window?**
179 | 1. import this
180 | 1. import zen
181 | 1. import pep20
182 | 1. print (pep20)
183 | 1. import zen
184 | 1. print (pep20)
185 | 1. import pep20
186 | \
187 |
188 | *🗝️ Ans. i*
189 | \
190 |
191 | 1. 👉**Select the true statement about the Zen of Python aphorism Flat is better than nested.**
192 | 1. You should not nest your code to prevent the occurrence of long execution times and delayed interpreter response.
193 | 1. Nesting code makes it much easier to understand and follow, but you should not nest more than three levels deep.
194 | 1. Nesting code makes it more difficult to follow, and - if possible - you should not nest more than three levels
195 | deep.
196 | 1. Nesting code makes it more difficult to understand, and you should not nest more than five levels deep.
197 | 1. Flat code is not effective as it is more difficult to maintain.
198 | \
199 |
200 | *🗝️ Ans. iii*
201 | \
202 |
203 | 1. 👉**Select the statements about Python docstrings with regard to PEP 257. (Select two answers.).**
204 | 1. You should surround your docstrings with triple single quotes (‘’’)
205 | 1. One-line docstrings should describe (e.g. "Does this"), not prescribe (e.g. "Do this") the code segment's effect.
206 | 1. Docstrings should occur as the first statement in a module/function/class/method.
207 | 1. Attribute docstrings are located immediately after another docstring, and their role is to provide additional
208 | context
209 | information.
210 | 1. Multi-line docstrings should have a summary line followed by one blank line and a more elaborate description.
211 | \
212 |
213 | *🗝️ Ans. iii, v*
214 | \
215 |
216 | 1. 👉**Select the true statements related to PEP 8 recommendations for code layout. (Select two answers.)**
217 | 1. You should use four spaces per indentation level.
218 | 1. You cannot mix tabs and spaces for indentation in Python 3.
219 | 1. You are allowed to mix tabs and spaces in Python 3 as long as the indentation level is the same.
220 | 1. Tabs are generally preferred over spaces for indentation in Python 3.
221 | 1. You should use four tabs per indentation level.
222 | \
223 |
224 | *🗝️ Ans. i, ii*
225 | \
226 |
227 | 1. 👉**Which of the following snippets is consistent with the Zen of Python philosophy with regard to exception
228 | handling? (Select the best answer.)**
229 | 1. ```python
230 | def storm():
231 | try:
232 | import lightning
233 | except ImportError as e:
234 | pass
235 | ```
236 | 1. ```python
237 | def storm():
238 | try:
239 | import lightning
240 | except ImportError:
241 | print(e)
242 | ```
243 | 1. ```python
244 | def storm():
245 | try:
246 | import lightning
247 | except ImportError as e:
248 | print("Something's gone wrong...")
249 | ```
250 |
251 | 1. ```python
252 | def storm():
253 | try:
254 | import lightning
255 | except:
256 | print("Something's gone wrong...")
257 | ```
258 | 1. ```python
259 | def storm():
260 | try:
261 | import lightning
262 | except ImportError as e:
263 | print(e)
264 | ```
265 |
266 | \
267 |
268 | *🗝️ Ans. v*
269 | \
270 |
271 |
272 | 1. 👉**What is the order of imports recommended by PEP 8?**
273 | 1. Standard library imports -> Related third-party imports -> Local application/library-specific imports.
274 | 1. Local application/library-specific imports -> Standard library imports -> Related third-party imports.
275 | 1. Standard library imports -> Local application/library-specific imports -> Related third-party imports.
276 | 1. PEP 8 does not make any specific recommendations for the order of imports. It's just important to put them at the
277 | beginning of the script.
278 | \
279 |
280 | *🗝️ Ans. i*
281 | \
282 |
283 | 1. 👉**Which of the following snippets are consistent with PEP 8 recommendations for using whitespace in expressions and
284 | statements? (Select two answers)**
285 |
286 | 1. ```python
287 | a = 1
288 | b = a + 3
289 | imag = 4.0
290 | ```
291 | 1. ```python
292 | def my_fun (imag=2.0, real=1.0)
293 | return imag*real
294 | ```
295 | 1. ```python
296 | a = 1
297 | b = a + 3
298 | imag = 4.0
299 | ```
300 | 1. ```python
301 | a=a+1
302 | b=a+1
303 | print(a + b)
304 | ```
305 | 1. ```python
306 | a = a + 1
307 | b = b + 3
308 | c = a*2 - 1
309 | d = (a-b) * (c-b)
310 | ```
311 | 1. ```python
312 | def my_fun (imag, real = 1.0)
313 | return imag * real
314 | ```
315 |
316 | \
317 |
318 | *🗝️ Ans. i, v*
319 | \
320 |
321 |
322 | 1. 👉**Which one of the naming styles is recommended by PEP 8 for constant names?**
323 | 1. The CamelCase style, e.g. `MySampleConstant`
324 | 1. Upper-case letters with words separated by underscores, e.g. `MY_SAMPLE_CONSTANT`
325 | 1. Upper-case letters with words not separated by underscores, e.g. `MYSAMPLECONSTANT`
326 | 1. Lower-case letters with words separated by underscores, e.g. `my_sample_constant`
327 | \
328 |
329 | *🗝️ Ans. ii*
330 | \
331 |
332 | 1. 👉**Select the true statements related to PEP 8 guidelines. (Select the two best answers.)**
333 | 1. Under no circumstances are you allowed to ignore PEP 8 guidelines as these are the foundations of Python code
334 | writing
335 | and should be followed at all times.
336 | 1. PEP 8 is constantly evolving, which means its recommendations are constantly changing; therefore, it's not worth
337 | adopting a code writing standard that is not well-established or solid.
338 | 1. If you are resuming work on a project that has not been following PEP 8 guidelines, it is recommended that you
339 | rewrite the existing code to make it PEP 8 compliant.
340 | 1. You can ignore some specific PEP 8 guidelines if following them will mean that you break backwards compatibility
341 | or
342 | degrade code readability.
343 | 1. It is recommended that you follow PEP 8 guidelines if you are starting a new Python project.
344 | \
345 |
346 | *🗝️ Ans. iv, v*
347 | \
348 |
349 | 1. 👉**Which of the following statements is consistent with the Zen of Python philosophy with regard to namespaces (
350 | Select
351 | the best answer.)**
352 | 1. You should generally avoid using many namespaces in your code as this approach will help you avoid conflicts with
353 | already existing names across different scopes.
354 | 1. The Python namespace mechanism does not let you manage the availability if identifiers across different scopes
355 | and is considered bad practice.
356 | 1. You should use global variables as they help you make your code more sustainable, reusable, and readable.
357 | 1. You should generally avoid using the global keyword to modify a variable inside a function, because it can result
358 | in name collisions in your code.
359 | \
360 |
361 | *🗝️ Ans. iv*
362 | \
363 |
364 | 1. 👉**What is true about imports with regard to PEP 8 recommendations? (Select two answers)**
365 | 1. PEP 8 recommends that your imports be on separate lines.
366 | 1. The following one-line import syntax is not correct in Python 3: from x import a, b
367 | 1. You should avoid using wildcard imports (e.g. from vehicles import * ).
368 | 1. You should avoid using absolute imports (i.e. imports that use absolute paths separated by full stops).
369 | \
370 |
371 | *🗝️ Ans. i, iii*
372 |
--------------------------------------------------------------------------------
/dumps/1. POO.md:
--------------------------------------------------------------------------------
1 | # 1. Questions PCPP1 - POO
2 |
3 | 1. 👉**Which sentence describing an abstract class is true?**
4 |
5 | 1) it provides a means for API
6 | 1) it is a contract between two classes
7 | 1) it is a class decorated with the `@abc.abstractclass` decorator
8 | 1) it is a class inheriting from the `Abstractclass` class
9 | \
10 |
11 | *🗝️ Ans. i*
12 | \
13 |
14 | 1. 👉**Take a look at the snippet and choose one of the following statements which is true:**
15 |
16 | ```python
17 | import abc
18 |
19 |
20 | @abc.abstractclass
21 | class BluePrint(abc.ABC):
22 |
23 | @abc.abstractmethod
24 | def hello(self):
25 | pass
26 |
27 |
28 | class WhitePool(BluePrint):
29 |
30 | def hello(self):
31 | print('Welcome to the White Pool!')
32 |
33 |
34 | wp = WhitePool()
35 | ```
36 |
37 | 1) it is erroneous as there is a typo in the abstract method decorator.
38 | 1) it defines one abstract class with one abstract method.
39 | 1) it prints “Welcome to the White Pool”
40 | 1) it is erroneous as there is no abc `abstractclass` decorator
41 | \
42 |
43 | *🗝️ Ans. iv*
44 | \
45 |
46 | 1. 👉 **Select the correct answer.**
47 | **The chaining concept introduces the following attribute on exception instances:**
48 |
49 | 1) `__traceback__` , which is inherent only for implicitly chained exceptions
50 | 1) `__context__` , which is inherent for implicitly chained exceptions
51 | 1) `__traceback__` , which is inherent only for explicitly chained exceptions
52 | 1) `__cause__` , which is inherent for implicitly chained exceptions
53 | \
54 |
55 | *🗝️ Ans. ii*
56 | \
57 |
58 | 1. 👉**The following snippet is an example of what kind of exception chaining?**
59 |
60 | **Select the best answer:**
61 |
62 | ```python
63 | class OwnMath(Exception):
64 | pass
65 |
66 |
67 | def calculatevalue(numerator, denominator):
68 | try:
69 | value = numerator / denominator
70 |
71 | except ZeroDivisionError as e:
72 |
73 | raise OwnMath from e
74 |
75 | return value
76 |
77 |
78 | calculatevalue(4, 0)
79 | ```
80 | 1) explicitly chained exceptions
81 | 1) implicitly chained exceptions
82 | 1) the code is erroneous.
83 | 1) the code is fine, and the script execution is not interrupted by any exception.
84 | \
85 |
86 | *🗝️ Ans. i*
87 | \
88 |
89 | 1. 👉 **@property is used to decorate:**
90 |
91 | 1) a 'getter' type method
92 | 1) any proxying method.
93 | 1) a 'delete type method.
94 | 1) a 'setter' type method
95 | 1) an 'access controller' type method
96 | \
97 |
98 | *🗝️ Ans. ii*
99 | \
100 |
101 | 1. 👉**What should he the order of decorators, placed in your code, controlling access to one specific attribute?**
102 |
103 | 1) first is @property then @attribute.getter or @attribute.setter
104 | 1) first is @property then @attribute.setter or @attribute.deleter
105 | 1) first is @attribute.getter, then @property or @attribute.setter
106 | 1) first is @attribute.setter, then @property or @attribute.deleter
107 | \
108 |
109 | *🗝️ Ans. ii*
110 | \
111 |
112 | 1. 👉**Look at the following code and name its elements.**
113 |
114 | ```python
115 | class A:
116 |
117 | def __init__(self):
118 | self.name = None
119 |
120 | def function(self, value):
121 | self.b = value
122 |
123 |
124 | a = A()
125 | ```
126 | 1) A is a class, function is a method, a is a method.
127 | 1) A is a class, function is a method, a is an object.
128 | 1) A is an attribute, function is a method, a is a method.
129 | 1) A is a method, b is a method, a is a method.
130 | \
131 |
132 | *🗝️ Ans. ii*
133 | \
134 |
135 | 1. 👉**What is the difference between inheritance and composition? Choose the best answer.**
136 |
137 | 1) both terms describe the same concept
138 | 1) inheritance models an 'is a' relation whereas composition models a 'has a' relation.
139 | 1) you cannot implement a multiple inheritance while multiple composition is possible.
140 | 1) composition models an 'is a' relation whereas inheritance models a 'has a' relation.
141 | \
142 |
143 | *🗝️ Ans. ii*
144 | \
145 |
146 | 1. 👉**The function `id()` returns:**
147 |
148 | 1) the identity of the object, a unique value amongst other objects
149 | 1) the absolute memory address occupied by the object.
150 | 1) a sequential number of the object created from the moment a Python script was started.
151 | 1) the identity of the object representing the object type
152 | \
153 |
154 | *🗝️ Ans. i*
155 | \
156 |
157 | 1. 👉**Select the true statement about class methods:**
158 |
159 | 1) class methods are methods that work on the class itself and require class object instances.
160 | 1) class methods are methods that work on the class itself.
161 | 1) class methods are methods that work on the class objects that are instantiated.
162 | 1) class methods cannot change class variables' values as there is no reference for the class.
163 | \
164 |
165 | *🗝️ Ans. ii*
166 | \
167 |
168 | 1. 👉**What are class methods?**
169 |
170 | 1) class methods are classes that expect two parameters: one indicating the class object and other indicating the
171 | class
172 | itself.
173 | 1) class methods are tool methods available to all class instances.
174 | 1) class methods are classes that are bound to class instances.
175 | 1) class methods are decorated with the @method trait.
176 | \
177 |
178 | *🗝️ Ans. ii*
179 | \
180 |
181 | 1. 👉**Select the true sentence.**
182 |
183 | 1) *args refers to a tuple of all not explicitly expected arguments; **kwargs refers to a dictionary of all not
184 | explicitly expected keyword arguments
185 | 1) *args refers to a list of all not explicitly expected arguments; **kwargs refers to a dictionary of all not
186 | explicitly expected keyword arguments
187 | 1) **args refers to a tuple of all not explicitly expected arguments; *kwargs refers to a dictionary of all not
188 | explicitly expected keyword arguments
189 | 1) *args collects all matched positional arguments; **kwargs collects all matched keyword arguments
190 | \
191 |
192 | *🗝️ Ans. i*
193 | \
194 |
195 | 1. 👉**What is a decorator? Select the best answer.**
196 |
197 | 1) it can be only a function that wraps another function to perform additional steps.
198 | 1) it is an only way to make your function safe by enforcing security checks for arguments values.
199 | 1) it can be a function or class that only accelerates another function execution.
200 | 1) it can be a function that returns a function that can be called later.
201 | \
202 |
203 | *🗝️ Ans. iv*
204 | \
205 |
206 | 1. 👉**Which function can be used to get a list of methods inherent to an object?**
207 |
208 | 1) `__dict__()`
209 | 1) `__help__()`
210 | 1) `help()`
211 | 1) `dict()`
212 | \
213 |
214 | *🗝️ Ans. iii*
215 | \
216 |
217 | 1. 👉**What is the following special method responsible for?**
218 |
219 | > __instancecheck__(self, object)
220 |
221 | 1) it is responsible for handling the `issubclass()` function calls.
222 | 1) it is responsible for handling the `instancecheck()` function calls
223 | 1) it is responsible for handling the is `instance()` function calls.
224 | 1) there is no such special method.
225 | \
226 |
227 | *🗝️ Ans. iii*
228 | \
229 |
230 | 1. 👉**What is inheritance?**
231 |
232 | 1) it is a concept of placing attributes inside objects and protecting then with dedicated methods.
233 | 1) it is a concept of building new classes, based on superclasses. New subclasses extend or modify inherited traits
234 | 1) it is another name for the 'has a' relation between two classes.
235 | 1) it is a synonym for polymorphism.
236 | \
237 |
238 | *🗝️ Ans. ii*
239 | \
240 |
241 | 1. 👉**What is polymorphism?**
242 |
243 | 1) it is the possibility to abstract methods from specific types to treat those types in a dedicated way.
244 | 1) it is a synonym for multiple inheritance.
245 | 1) it is the provision of a single interface to objects of different types.
246 | 1) it is a synonym for single inheritance.
247 | \
248 |
249 | *🗝️ Ans. iii*
250 | \
251 |
252 | 1. 👉**What is metaprogramming?**
253 |
254 | 1) it is a programming technique in which computer programs create metadata describing complex data structures like
255 | dictionaries.
256 | 1) it is a polymorphic code that has the ability to decrypt itself in order to protect itself against antiviruses.
257 | 1) it is a programming technique in which computer programs have the ability to modify their own code.
258 | 1) it is a synonym for polymorphism.
259 | \
260 |
261 | *🗝️ Ans. iii*
262 | \
263 |
264 | 1. 👉**Which of the following cannot be "pickled"?**
265 |
266 | 1) function definitions
267 | 1) large objects (LOB) whose size exceeds 64KB.
268 | 1) objects having references to other objects.
269 | 1) objects already pickled.
270 | \
271 |
272 | *🗝️ Ans. i*
273 | \
274 |
275 | 1. 👉**What is the dict property?**
276 |
277 | 1) it is a property that shows the content of every variable.
278 | 1) it is a property that acts like a dictionary and combines all attributes available in your code.
279 | 1) it is a built-in property owned by every Python keyword, object and instruction.
280 | 1) it is a built-in special method that is responsible for supporting any operations expressed with the square
281 | brackets.
282 | \
283 |
284 | *🗝️ Ans. ii*
285 | \
286 |
287 | 1. 👉**In the following snippet, the flag parameter has been assigned a value equal to 'n' What can you say about this
288 | specific value? Select the best answer.**
289 | ```python
290 | import shelve
291 |
292 | my_shelve = shelve.open('first_shelve.shlv', flag='n')
293 | ```
294 | 1) `'n'` stands for `'neutral'` - shelve will accept all data types for keys, but it will be slower in use.
295 | 1) `'n'` stands for `'new'` - a new, empty database will be created.
296 | 1) it is incorrect.
297 | 1) `'n'` stands for `'next'` - new records will be appended to the existing ones.
298 | \
299 |
300 | *🗝️ Ans. ii*
301 | \
302 |
303 | 1. 👉**Look at the following snippet. What is the expected output?**
304 |
305 | ```python
306 | class OwnList(list):
307 |
308 | def __setitem__(self, index, value):
309 | list.append(self, value)
310 |
311 | def append(self, value):
312 | list.__setitem__(self, value)
313 |
314 |
315 | own_list = OwnList()
316 | own_list.append(3)
317 | own_list.append(2)
318 |
319 | print(own_list)
320 | ```
321 | 1) [3, 3]
322 | 1) [2, 3]
323 | 1) [2, 2]
324 | 1) the code is erroneous.
325 | 1) [3, 2]
326 | \
327 |
328 | *🗝️ Ans. iii*
329 | \
330 |
331 | 1. 👉**What is duck typing?**
332 |
333 | 1) it is one of the pillars of OOP, which assumes that all classes provide a consistent interface.
334 | 1) it is a built-in protection against calling unknown methods. All exceptions raised by duck-typing are handled in
335 | a
336 | standard way.
337 | 1) it is a fancy term for the assumption that class objects own methods that are called.
338 | 1) it is a concept of attribute encapsulation. It is similar to the concept of eggs protected by their shells.
339 | \
340 |
341 | *🗝️ Ans. iii*
342 | \
343 |
344 | 1. 👉**The reason for implementing abstract classes is that:**
345 |
346 | 1) abstract classes set requirements regarding methods that must be implemented by their subclasses.
347 | 1) abstract classes decrease the code execution time.
348 | 1) abstract classes help you keep your code clean, short, and self-documenting.
349 | 1) abstract classes are deeper magic than 99% of users should ever worry about
350 | \
351 |
352 | *🗝️ Ans. i*
353 | \
354 |
355 | 1. 👉**Select the best statement related to a decorator.**
356 |
357 | 1) it is an example of 'syntactic overload' that is reserved only to closures.
358 | 1) it can be a function that decorates another function with characters carrying additional meaning such as '@'
359 | or '#'
360 | or '%'
361 | 1) it can be a function or a class that gains access to arguments of the function being decorated.
362 | 1) it can be a function or a class that optimizes another callable object execution by limiting its functionalities.
363 | \
364 |
365 | *🗝️ Ans. iii*
366 | \
367 |
368 | 1. 👉**What is serialization? Select the best answer.**
369 |
370 | 1) a process of assigning unique identifiers to every newly created Python object
371 | 1) a process of creating Python objects based on byte sequences.
372 | 1) a process of converting an object structure into a stream of bytes
373 | 1) another name for the process of data transmission
374 | \
375 |
376 | *🗝️ Ans. iii*
377 | \
378 |
379 | 1. 👉**Which of the following statements related to Python objects is false?**
380 |
381 | 1) an object is an instance of a class.
382 | 1) an object is a synonym for a class.
383 | 1) every object has its type.
384 | 1) an object is a synonym for an instance.
385 | \
386 |
387 | *🗝️ Ans. ii*
388 | \
389 |
390 | 1. 👉**Encapsulation allows for:**
391 |
392 | 1) controlling the access to selected attributes
393 | 1) exposing the __init__ method to consumers
394 | 1) changing the type of encapsulated data; it works like a converting method.
395 | 1) controlling the access to selected methods and attributes
396 | \
397 |
398 | *🗝️ Ans. i*
399 | \
400 |
401 | 1. 👉**Which statement about the 'shelve' module is false?**
402 |
403 | 1) the 'shelve' module is built on top of the 'pickle' module, but you do not have to abide by the order of all the
404 | elements placed into the shelve object.
405 | 1) the 'shelve' module is built on top of the 'pickle' module, so you must abide by the order of all the elements
406 | placed
407 | into the shelve object.
408 | 1) the 'shelve' module is used for object serialization and deserialization.
409 | 1) the 'shelve' module does not require importing the 'pickle' module by the programmer.
410 | \
411 |
412 | *🗝️ Ans. ii*
413 | \
414 |
415 | 1. 👉**What is an instance variable?**
416 |
417 | 1) any kind of variable as everything in Python is an object.
418 | 1) a variable that can be created only during object initialization.
419 | 1) a kind of variable that exists inside an object.
420 | 1) a variable that by default holds the None value as a result of variable initialization.
421 | \
422 |
423 | *🗝️ Ans. iii*
424 | \
425 |
426 | 1. 👉**Exception chaining is:**
427 |
428 | 1) a way to compact exception information.
429 | 1) a decorative statement for better exception handling.
430 | 1) a way to persist details of an exception when translating it to another type of exception.
431 | 1) an exception which occurs during recursion that exhausts all system resources.
432 | \
433 |
434 | *🗝️ Ans. iii*
435 | \
436 |
437 | 1. 👉**Exception chain is:**
438 |
439 | 1) a term that describes how exception details are traveling the exception tree, upwards to the BaseException.
440 | 1) a chain of trust between the subsequent exception handling methods
441 | 1) a structure containing exception attributes: context and cause.
442 | 1) a concept of handling exceptions raised by other exception handling code.
443 | \
444 |
445 | *🗝️ Ans. iii*
446 | \
447 |
448 | 1. 👉**What is the meaning of asterisks that are present in a function definition?**
449 |
450 | 1) they denote complex math operators.
451 | 1) they denote parameters that should be unpacked before use.
452 | 1) they denote pointers as in the C or C++ languages because CPython is written in C++.
453 | 1) they denote parameters of constant type and length.
454 | \
455 |
456 | *🗝️ Ans. ii*
457 | \
458 |
459 | 1. 👉**When you access data stored in a shelve object, you must use the keys of specific type. What type is it?**
460 |
461 | 1) tuple
462 | 1) integer
463 | 1) string
464 | 1) any mutable type
465 | \
466 |
467 | *🗝️ Ans. iii*
468 | \
469 |
470 | 1. 👉**Which statement is false?**
471 |
472 | 1) every list could be copied using slicing [:], which results in getting an independent list object.
473 | 1) deep copy might cause problems when there are cyclic references.
474 | 1) compound objects should be copied using the deep copy method.
475 | 1) it takes more time to make a deep copy than a shallow copy of an object.
476 | \
477 |
478 | *🗝️ Ans. i*
479 | \
480 |
481 | 1. 👉**“We're all consenting adults here” was said by:**
482 |
483 | 1) Guido van Rossum, the author of Python
484 | 1) John Marwood Cleese, a co-founder of 'Monty Python'
485 | 1) Tim Peters, the author of 'Zen of Python'
486 | 1) Uncle Bob, the developer of several software design principles
487 | \
488 |
489 | *🗝️ Ans. i*
490 | \
491 |
492 | 1. 👉**Answer the following question: What is the main reason for subclassing a built-in class?**
493 |
494 | 1) making the code execution faster
495 | 1) avoiding any intelectual rights issues
496 | 1) overriding all the parent's methods
497 | 1) getting a new class that can enrich the parent's methods.
498 | \
499 |
500 | *🗝️ Ans. iv*
501 | \
502 |
503 | 1. 👉**What is a metaclass?**
504 |
505 | 1) It a description of a complex data structure such as dictionary
506 | 1) a synonym for any abstract class which sets the guidelines regarding the methods required in subclasses.
507 | 1) a term describing a file which contains many classes that are in the 'is-a' relation between each other.
508 | 1) a class whose instances are classes.
509 | \
510 |
511 | *🗝️ Ans. iv*
512 | \
513 |
514 | 1. 👉**Is a 'pickle' file format constant amongst different Python releases?**
515 |
516 | 1) yes, that's how the power of Python manifests itself.
517 | 1) it depends on the operating system used.
518 | 1) no, nobody's expected wide compatibility.
519 | 1) yes, as long as the CPU architecture (32 or 64 bits) is retained.
520 | \
521 |
522 | *🗝️ Ans. iii*
523 | \
524 |
525 | 1. 👉**Select the best answer to complete the following sentence:**
526 |
527 | **When constructing a subclass that overrides methods from its superclass:**
528 |
529 | 1) you are not allowed to override all methods.
530 | 1) you still have access to the superclass methods.
531 | 1) you no longer have access to any of the superclass methods.
532 | 1) you should leave at least one method untouched for backwards compatibility.
533 | \
534 |
535 | *🗝️ Ans. ii*
536 | \
537 |
538 | 1. 👉**In the following snippet, the flag parameter has been assigned a value equal to 'c' What can you say about this
539 | specific value? Select the best answer.**
540 |
541 | ```python
542 | import shelve
543 |
544 | my_shelve = shelve.open('first_shelve.shlv', flag='c')
545 | ```
546 |
547 | 1) 'c' stands for 'create' - a database will be created if it does not exist.
548 | 1) 'c' stands for 'critical' - a limited number of data types will be used to increase the database performance.
549 | 1) it is incorrect.
550 | 1) 'c' stands for 'character' - only characters (strings) can be used for shelve keys.
551 | \
552 |
553 | *🗝️ Ans. i*
554 | \
555 |
556 | 1. 👉**Is it possible to instantiate an abstract class? Choose the correct answer.**
557 |
558 | 1) yes, every class can be instantiated.
559 | 1) no, because this is not the role of abstract classes; those are blueprints that must be implemented by
560 | subclasses.
561 | 1) no, because it has no method implementations at all.
562 | 1) no, because it is part of a contract between the class designer and the developer.
563 | \
564 |
565 | *🗝️ Ans. ii*
566 | \
567 |
568 | 1. 👉**Select the best answer to complete the following sentence:**
569 |
570 | **The *args and **kwargs parameters:**
571 |
572 | 1) are responsible for supporting an arbitrary number of positional arguments and keyword.
573 | 1) arguments, but their names cannot be changed.
574 | 1) can be placed in any order in a function definition.
575 | 1) are responsible for handling any number of additional arguments, placed right after the expected arguments,
576 | passed to
577 | a function called.
578 | 1) are deprecated names of any function parameters, originating from Python 2.x.
579 | \
580 |
581 | *🗝️ Ans. i*
582 | \
583 |
584 | 1. 👉**What is an abstract class? Select the best answer.**
585 |
586 | 1) it is another name for the 'has a' relation between two abstract methods
587 | 1) it is a blueprint for other classes; it cannot contain fully defined methods
588 | 1) it is a blueprint for other classes; it must contain at least one abstract method
589 | 1) it is a class that overloads methods derived from its superclass
590 | 1) it is a class decorated with the @abstract decorator
591 | \
592 |
593 | *🗝️ Ans. iii*
594 | \
595 |
596 | 1. 👉**Look at the following snippet. What is the expected output?**
597 |
598 | ```python
599 | class OwnDict(dict):
600 |
601 | def __setitem__(self, _key, _val):
602 | super().__setitem__(_key, _val)
603 |
604 | def update(self, *args, **kwargs):
605 | for _key, _val in dict(*args, **kwargs).items():
606 | self.__setitem__(_key, _val)
607 |
608 |
609 | own_dict = OwnDict()
610 | own_dict[4] = 1
611 | own_dict[2] = 0.5
612 |
613 | print(own_dict)
614 | ```
615 |
616 | 1) the code is erroneous.
617 | 1) {4: 4, 2: 2}
618 | 1) {4: 1, 2: 0.5}
619 | 1) {1: 4, 0.5: 2}
620 | \
621 |
622 | *🗝️ Ans. iii*
623 | \
624 |
625 | 1. 👉**What is an implicit exception chaining?**
626 |
627 | 1) it is a way to fade an exception by replacing it with another exception to limit the memory consumed by exception
628 | details.
629 | 1) it is the only way to promote exception details upwards the call stack.
630 | 1) it is a situation when an exception is raised during other exception handling, so the __context__ attribute is
631 | filled with exception details.
632 | 1) it is a situation when an exception is raised intentionally during other exception handling, so the __cause__
633 | attribute is filled with exception details.
634 | \
635 |
636 | *🗝️ Ans. iii*
637 | \
638 |
639 | 1. 👉**What is a class? Select the best answer.**
640 |
641 | 1) it is another name for the Python module file.
642 | 1) it expresses an idea representing a real-life entity or problem.
643 | 1) it is an independent instance of any variable such as string, float, or dictionary.
644 | 1) it is a synonym for an attribute.
645 | \
646 |
647 | *🗝️ Ans. ii*
648 | \
649 |
650 | 1. 👉**Select the true statement about the 'self' named parameter.**
651 |
652 | 1) it is used as a reference to the class instance.
653 | 1) it is an inherited object variable.
654 | 1) it can be used before an instance is created when to access a class variable.
655 | 1) this keyword is reserved for instance references and other names cannot be used for that.
656 | \
657 |
658 | *🗝️ Ans. i*
659 | \
660 |
661 | 1. 👉**What is inheritance? Choose the right answer.**
662 |
663 | 1) a concept that allows for modeling a tight relation between two subclasses.
664 | 1) a concept of encapsulating inherited data to protect them against modifications.
665 | 1) a concept that allows for modeling a tight relation between a superclass and subclasses.
666 | 1) a concept that allows for building classes from uncoupled elements.
667 | \
668 |
669 | *🗝️ Ans. iii*
670 | \
671 |
672 | 1. 👉**What is a Python magic method?**
673 |
674 | 1) it is a special-purpose method that can accept any number of parameters when called.
675 | 1) it is a special-purpose method that must be delivered by a developer, based on abstract blueprints.
676 | 1) it is a method whose name starts and ends with a dunder.
677 | 1) it is a method whose name starts and ends with a single underscore.
678 | \
679 |
680 | *🗝️ Ans. iii*
681 |
--------------------------------------------------------------------------------