Font size
WorksheetsPython Programming Quiz
Total questions: 120
Worksheet time: 3600secs
Which built-in Python module provides support for regular expressions?
search
regexp
pattern
regex
re
What does the command plt.plot([1, 2, 3, 4], [1, 4, 2, 3]) do in Matplotlib?
Forms a pie chart
Plots a heatmap
Plots a line chart
Displays a histogram
Creates a bar chart
What does inheritance do in the example 'class Dog(Animal):'?
Dog receives all methods and attributes of Animal
Dog turns Animal into an abstract class
Dog is no longer an object
Dog deletes Animal's methods
Dog cannot add its own methods
Which Python string method removes whitespace from both ends of a string?
replace()
split()
join()
strip()
lower()
What is the general message from the lecture: "Using GPU is not magic"?
It is an experimental approach not recommended for use
It is an outdated technology
It is a natural step in data analysis evolution when data volumes become too large for CPU processing
It is a marketing slogan with no practical value
GPU is only suitable for gaming, not for analytics
Which command creates a 3×3 identity matrix in NumPy?
np.identity()
np.matrix(3)
np.ones(3,3)
np.zeros(3,3)
np.eye(3)
How to correctly create an object of the Dog class with the name "Bobby" and age 5?
Dog.dog("Bobby", 5)
Dog["Bobby", 5]
dog = Dog.name("Bobby", 5)
dog = Dog("Bobby", 5)
new Dog("Bobby", 5)
What is a decorator in Python?
A function that takes another function and extends its behavior without modifying the original code
A tool for compiling Python into machine code
A method for sorting lists
A class for creating graphical interfaces
A way to declare global variables
What are Series and DataFrame objects used for in Pandas?
Series --- analogous to Python lists, DataFrame --- analogous to tuples
Series --- one-dimensional data with indices, DataFrame --- two-dimensional tables with column and row names
Both are used exclusively for visualization
Series --- a service data type for NumPy
Series --- only for string data, DataFrame --- only for numeric data
What is object-oriented programming (OOP)?
A programming language alternative to Python
A set of standard libraries for working with files
A way to write programs using only functions without data
A method for optimizing code execution speed on the processor
A paradigm where the program is built around objects that combine data and behavior
Which pytest flag enables verbose output of test results?
-k (keyword filter)
-s (capture off)
-v (verbose)
-x (exit on first failure)
-q (quiet)
Which class name corresponds to Python conventions (PEP 8)?
UserProfile
userprofile
USER_PROFILE
user_profile
user-Profile
What is an object (instance of a class)?
A description of a class without creating it
A specific instance created from a class
The name of the program file
Any Python module
Only an integer or string
Which Python library is primarily used to fetch (download) HTML pages from web servers?
json
requests
nltk
pymorphy2
BeautifulSoup
Which library is the foundation of numerical computing in Python?
NumPy
Requests
Matplotlib
TensorFlow
Pandas
What does MRO (Method Resolution Order) determine in Python?
The priority between abstract and concrete methods
The order of calling constructors in composition
The order in which Python searches for methods in the class hierarchy during inheritance
The priority when calling 'super()' in single inheritance
The sequence in which modules are imported
Which library is responsible for plotting density plots?
Seaborn (sns.kdeplot(data))
Tkinter
NumPy
Plotly
Pandas
When is the @pytest.mark.xfail marker used?
When a test requires an internet connection
When a test uses deprecated functions
When a test needs to be executed first
When a test works only on Windows
When a test is expected to fail due to a known bug
How to access the class attribute Dog.species from the object my_dog?
my_dog["species"]
my_dog.species
species.my_dog
getattr("my_dog", "species") without passing the object itself
Dog[my_dog].species
In the example 'class Duck(Flyer, Swimmer):', what methods will be available to a 'duck' object?
Only 'quack()' and methods from Flyer
Only methods that were called via 'super()'
Only methods from the first parent (Flyer)
Only methods that were overridden in 'Duck'
fly(), swim(), and Duck's own methods (e.g., quack())
Besides using parent's methods, what else can a child class do?
Add new methods and attributes, and override existing methods
Force the use of only the parent's implementation
Change the parent's MRO (Method Resolution Order)
Use only composition
Completely ignore the parent's init
What is a fixture in the context of testing?
A decorator for skipping tests
A pytest configuration file
Prepared data or objects that are passed into tests
A code debugging tool
A report on test results
How does a class attribute differ from an instance attribute?
A class attribute exists only at runtime, an instance attribute only at compile time
A class attribute can be modified, while an instance attribute can only be read
A class attribute is common to all objects of that class, an instance attribute is unique to each object
A class attribute is stored in a file, while an instance attribute is only in memory
There is no difference; these are two names for the same thing
Which statement best describes the difference between a class and an object?
A class is used only for built-in types, an object only for custom types
An object describes structure, and a class stores data
A class describes structure and behavior, an object is a specific representative with that behavior and data
A class exists only at runtime, and an object only at compile time
A class and an object are the same thing
Which Matplotlib backend is most commonly used for the Tkinter graphical interface?
GTK3Agg
Agg
Qt5Agg
WXAgg
TkAgg
How is a private attribute conventionally denoted in Python?
The name starts with one underscore: _balance
The name is written in UPPERCASE: BALANCE
The name is placed in quotes: "balance"
The name ends with the word private: balance_private
The name starts with two underscores: __balance
Which code creates a pie chart in Matplotlib?
plt.piechart([20, 30, 50])
plt.bar([20, 30, 50])
plt.pie([20, 30, 50], labels=['A', 'B', 'C'], autopct='%1.1f%%')
plt.circle([20, 30, 50])
plt.plot(['A', 'B', 'C'], [20, 30, 50])
Why are the attributes '__username' and '__password' made private in the 'UserAccount' class?
To prevent instances from being created
To protect data and control access through methods
So that Python automatically encrypts the strings
To make them inaccessible inside the class
To make the class abstract
How does the list [Firewall(), Antivirus(), IDS()] demonstrate polymorphism if each object has a 'protect()' method?
Each object implements 'protect()' in its own way, and the loop calls them uniformly
The loop works only with descendants of Firewall
The loop forbids different implementations
The loop changes the class of objects on the fly
The loop calls methods by variable name
Which NLTK function tokenizes text into individual words?
tokenize()
split()
word_tokenize()
sent_tokenize()
words()
What is the main drawback of GPU computing, as mentioned in the lecture?
GPU does not support NumPy libraries
Conda cannot be used for GPU
The need to reinstall Python
Transferring data between CPU and GPU creates a bottleneck and requires more time
GPU does not work with large files
Which library is the GPU analog of the Pandas DataFrame?
cuDF
torchdata
CuPy
numba
cuML
Why check the uniqueness of identifiers in data?
To add indexes to the database
To detect duplicate records or errors in identifier assignment
To speed up data sorting
To reduce file size
To convert data to JSON
What does checking the range of values in data mean?
That the data is sorted in ascending order
That the file does not exceed a certain size
That values fall within acceptable limits (e.g., age from 18 to 120)
That all values are the same
That a column contains only text
What is the @property decorator used for?
So that the method is executed only once in the entire program
So that the method becomes a top-level function
So that the method becomes private and inaccessible from outside
So that a method can be accessed like an attribute (without parentheses)
So that the method automatically saves data to a file
What does data validation for missing values check?
That the data is encrypted
That strings are sorted alphabetically
That all numbers are positive
That the file has a .csv extension
That there are no empty values (NaN, None) in the specified columns
What is the main goal of automated data testing?
To speed up loading data into memory
To detect errors and anomalies in data before using it in analysis
To create data visualization
To convert data into another format
To reduce the dataset size
Which construct is used to check the Method Resolution Order (MRO) for a class D?
dir(D)
type(D).mro
D.mro()
print(D.resolution_order)
D.mro
Which regular expression pattern is commonly used to match email addresses?
[a-zA-Z0-9_.−]+@[a-zA-Z0-9.−]+.[a-z]{2}
\w+@\w+
email:\d+$+@\S+
[a-z]+@[a-z]+.[a-z]{2,}
A[a-z]+@[a-z]+$
Which regex method removes HTML tags by replacing them with empty strings?
text.strip()
re.sub(r'<[^>]+>', '', text)
text.replace('<', '')
re.findall('?>', text)
BeautifulSoup.get_text()
What is the main purpose of using virtual environments in Python?
Project File Management
Speeding up code execution
Automatic code formatting
Isolation of libraries for different projects
How many times will the print(count) instruction be executed?
5
4
0
1
3
What is the difference between for and while loops in Python?
for can be interrupted using break, but while cannot
while is always executed at least once, and for may not be executed even once
for requires explicit counter indication, while does not
for is always used to iterate through the sequence, and while is used to execute code while the condition is true
Which tool is most often used to install third-party Python libraries?
pip
gem
npm
apt-get
What result will be displayed in the console (check_number(5))?
Odd
Mistake
Even and less than or equal to 10
Even and greater than 10
What do Python code blocks mean (instead of curly braces)?
Two dots at the beginning of the block without indentation
In quotation marks
Indentation (intervals/tabs)
With special characters #BEGIN/#END
What will be the result of executing the code with a = 0 and for loop?
0
1
2
3
In the try-except-finally block, which block of code is guaranteed to be executed?
finally
Only except (if an error has occurred)
Only try
None of them
When refactoring code into a modular structure, which actions are MANDATORY?
Rename all variables according to the same standard
Ensuring weak connectivity between the created modules
Separation of logically related functions into separate modules (.py files)
Defining clear interfaces (which functions and with which parameters the module exports)
What will be displayed in the console (10 / 2 with try-except-finally)?
Division by zero!
The operation was successful
Operation successful
Completion
Which situations are valid indicators that the code requires refactoring?
The calculate_total function is very large
To correct an error, changes are needed in three different files
The same input verification is repeated in five functions
Adding a new feature causes unexpected errors in other modules
The code has been working fine for 2 years
Specify ALL the advantages of the SRP principle:
A function has one responsibility
No comments needed in the code
The code is easier to test
Debugging is simplified
The program execution speed is reduced
What happens when executing: my_tuple = (1, [2, 3], 4); my_tuple.append(5)?
Mistake: 'tuple' object does not support item assignment
(1, [2, 3], 4)
(1, [2, 3, 5], 4)
What is NOT the purpose of modularity?
Error localization
Code reuse
Complete exclusion of errors from the program
Simplify development by splitting it into parts
Which are the advantages of modularity in software development?
Reuse of module code
Information hiding (Encapsulation)
Localization of errors
Automatic correction of all errors
Simplify development
Which statement about the result is INCORRECT?
Key 1 contains the list
Key 3 contains the list
The setdefault() function creates a new list if there is no key
Key 2 contains the list [2, 4] (the order is guaranteed)
What is the Pandas library used for?
For working with structured data: tables, time series, statistics
For working with binary files
For solving differential equations
For creating low-level plots
For managing system processes
What does the json.load() function do?
Saves JSON data to a file
Reads a CSV file
Loads JSON data from a file object
Extracts text from HTML
Converts a string to JSON
What is a class in Python?
A template (blueprint) for creating objects
A string variable describing an object
A separate function not related to data
A special type of comment in the source code
A specific object in memory
What is tokenization in text processing?
Finding patterns using regular expressions
Cleaning text from HTML tags
Converting words to their base forms
Splitting text into individual meaningful units (tokens)
Removing stop words from text
Which file on a website specifies rules for web crawlers about which pages can be accessed?
config.json
robots.txt
terms.txt
sitemap.xml
index.html
Which OOP property allows working with objects of different classes through a unified interface?
Inheritance
Encapsulation
Abstraction
Composition
Polymorphism
What is a library in Python?
A collection of pre-written code (functions, classes, objects) designed to solve specific tasks.
A graphical interface for data visualization.
A storage location for all variables in a project.
A special interpreter module that stores calculation results.
A folder with Python installation files.
What does the @pytest.mark.skip marker mean?
The test will be executed twice
The test will be skipped and not executed
The test will run with higher priority
The test will save the result to a file
The test will run only in debug mode
What are object methods?
Functions defined inside a class that describe the behavior of an object
Any functions declared in a module
Only built-in Python functions (print, len, etc.)
Special variables storing project settings
Operating system constructors
When is the init method called?
When the object is deleted by the garbage collector
When the program finishes
Every time any method of the object is called
When creating a new object of the class
Only when importing the module where the class is declared
What advantage of OOP is illustrated by the example with 10,000 characters in a city simulator?
Speeding up the program 10 times without changing algorithms
Reducing duplicate code by using one Person class instead of thousands of similar variables and functions
Automatic creation of a graphical interface
Ability to run the program only on a server
Complete absence of runtime errors
In BeautifulSoup, which method finds ALL elements with a specified tag?
find()
find_all()
get_text()
select_one()
extract()
What happens when trying to create an instance of the abstract class 'Shape(ABC)'?
A 'TypeError' occurs because an instance of an abstract class cannot be created.
The 'pass' implementation is used.
The 'init' from 'object' is called.
The 'area()' method is called by default.
Python automatically creates an implementation for all abstract methods.
Which relationship describes Composition ('Has-a'), as opposed to Inheritance ('Is-a')?
An object of one class is another class.
Both relationships are identical in nature.
An object of one class replaces another class.
An object of one class contains an instance of another class.
An object of one class calls a method of another class.
Why is the 'Cipher' class declared as abstract with 'abstractmethod encrypt/decrypt'?
To be able to create instances of 'Cipher()'.
To force child classes to implement both methods.
To hide the methods from the interpreter.
To automatically log operations.
To prohibit inheritance.
What is the primary function of calling 'super().method_name()' in a child class method?
To disable encapsulation for that method.
To force a call to 'init' from the 'object' class.
To call the corresponding method from the nearest parent class according to MRO.
To define a new abstract method.
How to group data in Pandas by the 'group' column and calculate the mean?
df.group('group').avg()
pd.mean(df['group'])
df.sort('group').avg()
df.aggregate('group', 'mean')
df.groupby('group').mean()
In a typical text processing pipeline, which stage usually follows tokenization?
Text vectorization
Removing stop words
Parsing from web sources
Sentiment analysis
Normalization (stemming/lemmatization)
Why is 'super().init(...,...)' called in 'Ransomware.init(...)'?
To bypass type checking.
To hide the parent's attributes.
To create a new 'Malware' object.
To initialize fields of the parent class 'Malware', such as 'name'.
To override the 'attack' method.
Which Python library is specifically designed for lemmatizing Russian words?
nltk
pymorphy2
requests
re
BeautifulSoup
Why is referential integrity data validation needed?
To encrypt data
To ensure that related records exist in the corresponding tables
To remove all duplicates
To convert data types
To create a backup
In which case is it better to use Composition instead of Inheritance?
When polymorphism through a common hierarchy is required.
When it is necessary to forcefully override a method.
When a class is a specialization of another class (e.g., 'Ransomware' is 'Malware').
When using multiple inheritance.
When an object has another functionality but is not (e.g., a Car has an Engine).
What are object attributes?
Files where the class source code is saved
Comments describing the code
Data (state) stored inside an object
Only methods that the object can execute
Imported modules used by the program
What is the pytest module used for?
For data visualization
For asynchronous programming
For writing and running automated tests
For working with databases
For creating web applications
Which regular expression pattern is commonly used to match email addresses? (Alternative version)
email:\s*\S+@\S+
\w+@\w+
A[a-z]+@[a-z]+
[a-zA-Z0-9._%+−]+@[a-zA-Z0-9.−]+.[a-zA-Z]{2,}
[a-z]+@[a-z]+
Which regex method removes HTML tags by replacing them with empty strings? (Alternative version)
re.sub(r'<[^>]+>', '', text) or re.sub(r'<.*?>', '', text)
BeautifulSoup.get_text()
text.strip()
re.findall(r'<.?>', text)
text.replace('<', '')
What is the main difference between for and while loops in Python?
for requires explicit counter indication, while does not.
for can be interrupted using break, but while cannot.
while is always executed at least once, and for may not be executed even once.
for is always used to iterate through the sequence, and while is used to execute code while the condition is true.
What function in Python should be used to determine the data type of a variable?
get_type()
type()
typeof()
datatype()
How many times will the print(count) instruction be executed in the following code?
3
4
infinite
5
What will be displayed in the console?
5
15
3
10
0
What code should I insert instead of ??? to find the symmetric difference of the sets?
union
symmetric_difference
differenc
intersection
What are the advantages of a modular project structure (choose ALL the right ones)?
Renaming of all functions can be used.
A mistake in one module won't break the whole project.
Different people can work on different modules.
The code becomes definitely shorter.
Reuse of modules in other projects.
Which of these properties is not a typical problem of the 'spaghetti code'?
Excessive modularity
Unreusability
Testing difficulty
Unintelligibility
Unmaintainability
Which of the statements about hash functions are CORRECT?
The hash function should be calculated quickly.
The hash function ensures that there are no collisions for any data.
A small change in the input data should cause a significant change in the hash.
In Python, hash((1, 2)) will be equal to hash([1, 2]).
Which of the following variable names is invalid in Python?
1st_number
totalSum
def
!data
_count
Which version of the Python code sets the condition block correctly?
if (x > 0) then print('positive')
if x > 0 { print('positive') }
if x > 0 print('positive')
if x > 0: print('positive') # in one line
What will be the result of executing the following code?
2
1
0
3
When refactoring the 'spaghetti code' into a modular structure, which of the listed actions are MANDATORY? Select all the correct ones.
Defining clear interfaces (which functions and with which parameters the module exports).
Separation of logically related functions into separate modules (.py files).
Ensuring weak connectivity between the created modules.
Rename all variables according to the same naming convention.
What is the main purpose of using virtual environments in Python?
Isolation of libraries for different projects
Speeding up code execution
Automatic code formatting
Project File Management
What command is used to create a new virtual environment named venv?
new-env venv
python -m venv venv
make-virtual-env venv
create venv
Why is this code causing an error?
Incorrect syntax for creating a dictionary
The tuple (1, 2) cannot be a dictionary key
You can't mix different types of data in dictionary keys.
The list [3, 4] cannot be a dictionary key, as it is mutable and non-hashed.
Which of the following cases violates the DRY principle?
The calculate_total function has become so large that it takes up 4 screens to scroll.
Adding a new feature (for example, sending SMS) causes unexpected errors in the report generation module.
The code has been working fine and requires no changes for 2 years now.
The same sequence of actions for verifying user input is repeated in five different functions in main.py.
What is NOT the purpose of modularity?
Error localization
Code reuse
Simplify development by splitting it into parts
Complete exclusion of errors from the program
Which tool is most often used to install third-party Python libraries?
npm
apt-get
gem
pip
What happens when executing this code?
An empty Counter will be created for 'user3' and 0 will be returned for the 'view' key.
None will return
The KeyError error is because there is no 'user3' key.
What result will the expression return, provided that the string is passed in the original case?
['hello']
['Привет', 'hello', '123', 'мир']
[]
['Hello', 'hello', 'world']
Which of the following operations with Counter are CORRECT?
c1 / c2 - division of counters
c1 | c2 - union (maxima)
c1 & c2 - intersection (minima)
c1 - c2 - counter subtraction (positive results only)
c1 + c2 - adding counters
What is meant by a 'large ecosystem of libraries' in the context of Python?
Only built-in libraries from Python developers
Availability of packages for scientific computing and AI development
A set of third-party packages for different fields (web, science, AI, automation) available through package managers
A small number of standard modules in the distribution
Specify ALL the advantages of the SRP principle:
Debugging is simplified
The program execution speed is reduced
No comments needed in the code
A function has one responsibility
Which of these situations are valid indicators that the code requires refactoring and applying modularity principles?
Adding a new feature (for example, sending SMS) causes unexpected errors in the report generation module
The code has been working fine and requires no changes for 2 years now.
To correct an error in the discount calculation algorithm, you have to make changes in the code of three different modules.
The calculate_total function has become so large that it takes up 4 screens to scroll.
Specify ALL the advantages of the SRP (Single Responsibility Principle):
No comments needed in the code
The program execution speed is reduced
Debugging is simplified
A function has one responsibility
The code is easier to test
Which of the following statements describe the advantages of using functions in Python? (Select all appropriate options)
Functions allow you to split the code into named, self-contained fragments.
Functions allow you to use input parameters and return values.
The functions contribute to compliance with the principle of single responsibility (SRP).
Functions make debugging more difficult because the code is broken into parts.
The functions help to reduce code duplication by following the DRY principle.
What happens when executing this code?
(1, [2, 3], 4, 5)
(1, [2, 3, 5], 4)
Mistake: 'tuple' object does not support item assignment
(1, [2, 3], 4)
When starting main.py error occurs: ModuleNotFoundError: No module named 'student_management'. What is the MOST LIKELY cause of the error?
In the file student_management.py there is no add_student function.
Incorrect import syntax. To import correctly from a subfolder, use from student_system.student_management import add_student.
The DRY principle has not been applied.
The SRP principle is violated in the student_management module.
Which of the following operations with tuples are CORRECT?
a, b, 'test' = (1, 2, 3, 4, 5)
x, y = (10, 20)
new_tuple = old_tuple + (6, 7)
my_tuple = 100 (changing a tuple element)
coordinates = (lat, lon) = (43.22, 76.85)
Which of the following operations with Counter are CORRECT?
c1 - c2 → counter subtraction (positive results only)
c1 / c2 → division of counters
c1 + c2 → adding counters
c1 & c2 → intersection (minima)
c1 | c2 → union (maxima)
The code is given. Which of the statements about the result is INCORRECT?
The setdefault() function creates a new list if there is no key
Key 1 contains the list
Key 3 contains the list
Key 2 contains the list [2, 4] (the order is guaranteed)
Which of the above are the advantages of modularity in software development? (Select all the appropriate options)
Information hiding (Encapsulation)
Simplify development (the ability for different teams to work on different modules)
Improving the execution speed of the entire application
Localization of errors (an error in one module is less likely to break the entire system)
Reuse of module code in other projects
What do Python code blocks mean (instead of curly braces)?
Two dots at the beginning of the block without indentation
In quotation marks
Indentation (intervals/tabs)
With special characters #BEGIN/#END
Which of the following cases violates the DRY (Don't Repeat Yourself) principle?
One function calculates the discount, the other applies the tax
Three different functions for working with different types of products
The discount calculation code is repeated in three places of the program
Which of the following are the advantages of modularity in software development? (Select all appropriate options)
Simplify development (the ability for different teams to work on different modules)
Automatic correction of all errors in the project
Information hiding (Encapsulation)
Localization of errors (an error in one module is less likely to break the entire system)
Reuse of module code in other projects
Which of the following operations with tuples are CORRECT?
my_tuple = 100 (changing a tuple element)
coordinates = (lat, lon) = (43.22, 76.85)
*a, b, rest = (1, 2, 3, 4, 5)
new_tuple = old_tuple + (6, 7)
x, y = (10, 20)
Which of the following statements describe the advantages of using functions in Python? (Select all appropriate options)
The functions contribute to compliance with the principle of single responsibility (SRP)
Functions always speed up program execution by compiling.
The functions help to reduce code duplication by following the DRY principle.
Functions make debugging more difficult because the code is broken into parts.
Functions allow you to use input parameters and return values.
When starting main.py error occurs. The project structure looks like this. Error in the import line in main.py: from student_management import add_student. What is the MOST LIKELY cause of the error?
In the file student_management.py there is no add_student function.
Incorrect import syntax. To import correctly from a subfolder, use from student_system.student_management import add_student.
The DRY principle has not been applied.
The SRP principle is violated in the student_management module.
