WorksheetsPython Programming Worksheet
Total questions: 86
Worksheet time: 43mins
Which of the following variable names is invalid in Python?
def
1st_number
_count
color text
!data
When refactoring the "spaghetti code" into a modular structure, which actions are MANDATORY?
Defining clear interfaces (which functions and with which parameters the module exports).
Ensuring weak connectivity between the created modules.
Separation of logically related functions into separate modules (.py files).
Rename all variables according to the same standard.
Which of the following cases violates the DRY principle?
The discount calculation code is repeated in three places of the program
One function calculates the discount, the other applies the tax
Three different functions for working with different types of products
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.
How many times will the print(count) instruction be executed?
2
4
бесконечное
5
1
What result will be displayed in the console?
Mistake
Even and less than or equal to 10
Even and greater than 10
Odd
What code should I insert instead of ???
symmetric_difference
union
differenc
intersection
Which version of the Python code sets the condition block correctly?
if x > 0: print("positive")
if x > 0 { print("positive") }
if x > 0 print("positive")
if (x > 0) then print("positive")
What will be displayed in the console?
0
3
5
7
15
Which of these properties is NOT a typical problem of spaghetti code?
Excessive modularity
Unmaintainability
Unreusability
Unintelligibility
Testing difficulty
What do Python code blocks mean (instead of curly braces)?
Indentation (intervals/tabs)
With special characters #BEGIN/#END
In quotation marks
Two dots at the beginning of the block without indentation
What are the advantages of a modular project structure?
A mistake in one module won't break the whole project.
Reuse of modules in other projects
Different people can work on different modules.
The code becomes definitely shorter.
Renaming of all functions can be used.
Advantages of using functions in Python
The functions contribute to compliance with the SRP principle.
Functions allow you to use input parameters and return values.
The functions help to reduce code duplication by following the DRY principle.
Functions always speed up program execution by compiling.
Functions allow you to split the code into named, self-contained fragments.
Which operations with tuples are CORRECT?
a, b, *rest = (1, 2, 3, 4, 5)
coordinates = (lat, lon) = (43.22, 76.85)
x, y = (10, 20)
new_tuple = old_tuple + (6, 7)
my_tuple[0] = 100
What will be displayed in the console?
Unknown team
Uploading user_data
Execution error
Which operations with Counter are CORRECT?
c1 + c2
c1 | c2
c1 - c2
c1 & c2
c1 / c2
What happens when executing this code?
(1, [2, 3, 5], 4)
(1, [2, 3], 4)
(1, [2, 3], 4, 5)
Mistake
Which statements about hash functions are CORRECT?
In Python, hash((1, 2)) == hash((1, 2))
A small change in the input data should cause a significant change in the hash
The hash function should be calculated quickly
The hash function ensures that there are no collisions
MOST LIKELY cause of the error
Incorrect import syntax. To import correctly from a subfolder, use from student_system.student_management import add_student
The SRP principle is violated
There is no add_student function
The DRY principle has not been applied
Specify ALL the advantages of the SRP principle
A function has one responsibility
The code is easier to test
Debugging is simplified
The program execution speed is reduced
No comments needed in the code
What is NOT the purpose of modularity?
Complete exclusion of errors from the program
Code reuse
Error localization
Simplify development by splitting it into parts
Which are advantages of modularity in software development?
Reuse of module code in other projects
Simplify development (different teams can work on different modules)
Information hiding (Encapsulation)
Localization of errors
Improving the execution speed of the entire application
Which statement about the result is INCORRECT?
Key 2 contains the list [2, 4] (the order is guaranteed)
The setdefault() function creates a new list if there is no key.
Key 1 contains the list [1]
Key 3 contains the list [3]
What will be the result of executing the following code? a = 0 for i in range(3): a += 1 if i == 1: break print(a)
Error (syntax error)
(правильного варианта среди чисел нет)
In the try-except-finally block, which block is guaranteed to be executed?
finally
except
None of them
Only try
What function in Python should be used to determine the data type of a variable?
type()
typeof()
datatype()
get_type()
Which of the following cases violates the DRY principle?
The discount calculation code is repeated in three places of the program
Three different functions for working with different types of products
One function calculates the discount, the other applies the tax
Which version of the Python code sets the condition block correctly?
if x > 0: print("positive")
if x > 0 print("positive")
if (x > 0) then print("positive")
if x > 0 { print("positive") }
What will the expression return? re.findall(r'[bA-Za-z]+', 'Hello, hello 123 world!')
['Hello', 'hello', 'world']
['Hello', 'world']
['hello', 'world']
['Hello', 'hello', 'world', '']
Which variable names are invalid in Python?
1st_number
color text
def
my_variable
!data
What do Python code blocks mean (instead of curly braces)?
Indentation (intervals/tabs)
In quotation marks
With special characters #BEGIN/#END
Two dots at the beginning of the block
What command is used to create a new virtual environment named venv?
python -m venv venv
new-env venv
create venv
make-virtual-env venv
Which of the above is true about variables in Python?
Python uses dynamic typing, and the type of a variable is determined at runtime
Variable names are case insensitive
They require an explicit type declaration
They can start with a number
Why does this code cause an error? coordinates = {(1, 2): "Point A", [3, 4]: "Point B"}
The list [3, 4] cannot be a dictionary key because it is mutable and not hashable
You can't mix different types of keys
The tuple (1, 2) cannot be a key
Incorrect dictionary syntax
Which tool is most often used to install third-party Python libraries?
pip
gem
apt-get
npm
Which statement about the result is INCORRECT?
Key 2 contains the list [2, 4] (the order is guaranteed)
The setdefault() function creates a new list if there is no key
Key 1 contains the list [1]
Key 3 contains the list [3]
Advantages of modularity in software development
Localization of errors
Improving the execution speed of the entire application
Simplify development (different teams can work on different modules)
Reuse of module code in other projects
Information hiding (Encapsulation)
Which of the following operations with Counter are CORRECT?
c1 & c2 — intersection (minima)
c1 - c2 — counter subtraction (positive results only)
c1 + c2 — adding counters
c1 | c2 — union (maxima)
c1 / c2 — division of counters
Which of the following operations with tuples are CORRECT?
a, b, *rest = (1, 2, 3, 4, 5)
x, y = (10, 20)
new_tuple = old_tuple + (6, 7)
coordinates = (lat, lon) = (43.22, 76.85)
my_tuple[0] = 100
Which of the statements about hash functions are CORRECT?
In Python, hash((1, 2)) will be equal to hash((1, 2))
A small change in the input data should cause a significant change in the hash
The hash function should be calculated quickly
The hash function ensures that there are no collisions
Какие утверждения описывают преимущества использования функций в Python?
Functions allow you to use input parameters and return values
Functions allow you to split the code into named, self-contained fragments
The functions help to reduce code duplication by following the DRY principle
The functions contribute to compliance with the SRP principle
Functions always speed up program execution
What will be displayed in the console?
Unknown team
Uploading user_data
Execution error
Which situations indicate that code requires refactoring and modularity?
Adding a new feature causes unexpected errors in another module
The function takes up several screens of code
Fixing one error requires changes in multiple files
The same logic is repeated in several functions
The code has been working fine for 2 years
What does a decorator function return?
A new function (wrapper) that calls the original one with additional logic
A list of arguments
The number of calls
A TypeError
A string with the function name
Why check the uniqueness of identifiers in data?
To detect duplicate records or errors in identifier assignment
To speed up sorting
To reduce file size
To convert data to JSON
To add database indexes
What does a property setter do?
Allows controlling and validating values when assigning to an attribute
Creates a copy of the object
Replaces the constructor
Makes the attribute read-only
Deletes the attribute
What is meant by a “large ecosystem of libraries” in Python?
A set of third-party packages for different fields available via package managers
Only built-in libraries
Only scientific and AI packages
A small number of standard modules
What is RAPIDS?
A set of GPU libraries (cuDF, cuML) — analogs of Pandas and Scikit-learn
A logging system
A database connector
A CPU optimization extension
A web framework
Which regex pattern is commonly used to match email addresses?
[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}
[a-z]+@[a-z]{1,}[a-z]
\w+@\w+
email:\s*\S+@\S+
Which regex method removes HTML tags?
re.sub(r'<[^>]+>', '', text)
text.strip()
BeautifulSoup.get_text()
text.replace('<', '')
re.findall()
When is it better to use Composition instead of Inheritance?
When an object has another functionality but is not it (Car has an Engine)
When using multiple inheritance
When a class is a specialization of another
When polymorphism is required
When forcing method override
Which construct is used to check Method Resolution Order (MRO)?
D.mro()
D.__mro__
dir(D)
print(D.resolution_order)
Which statement best describes the difference between a class and an object?
A class describes structure and behavior, an object is a concrete instance with data
A class is only for built-in types
A class exists only at runtime
A class and an object are the same
An object describes structure, and a class stores data
What does the broadcasting mechanism do in NumPy?
Creates random matrices from scratch
Converts data from Pandas to NumPy
Removes duplicate elements in an array
Copies arrays to another memory space
Why are the attributes __username and __password made private?
To protect data and control access through methods
To make them inaccessible inside the class
To prevent instances from being created
To make the class abstract
So that Python automatically encrypts the strings
What happens when creating an instance of an abstract class Shape(ABC)?
A TypeError occurs because an instance of an abstract class cannot be created
__init__ from object is called
The pass implementation is used
Python creates implementations automatically
area() is called by default
What is the purpose of the self parameter?
It is a reference to the current instance of the class inside the method
A global variable
A list of all objects
A reserved word denoting the module
Always contains the class name as a string
How to access Dog.species from object my_dog?
my_dog.species
getattr("my_dog", "species")
species.my_dog
my_dog["species"]
Dog(my_dog).species
When is the __init__ method called?
When creating a new object of the class
When the program finishes
When importing the module
When any method is called
When the object is deleted
What is __str__ most often used for?
To define a clear string representation of an object when calling print(obj)
Save object to JSON
Compare objects
Create a copy
Calculate length
What is a fixture in testing?
Prepared data or objects that are passed into tests
Debugging tool
Test report
Decorator for skipping tests
pytest configuration file
How to group data in Pandas and calculate the mean?
df.groupby('group').mean()
pd.mean(df['group'])
df.sort('group').avg()
df.group('group').avg()
df.aggregate('group', 'mean')
What is the time module used for in decorators?
To measure the execution time of a function
To schedule tasks
To work with time zones
To format dates
To synchronize threads
What does the @pytest.fixture decorator do?
Creates reusable test data or objects for tests
Disables error output
Runs tests in parallel
Measures execution time
Skips tests
Which library is designed for lemmatizing Russian words?
pymorphy2
BeautifulSoup
requests
re
nltk
How is a private attribute conventionally denoted in Python?
UPPERCASE
In quotes
One underscore
Ends with _private
Which code creates a pie chart in Matplotlib?
plt.piechart(...)
plt.circle(...)
plt.plotpie(...)
plt.bar(...)
What is object-oriented programming (OOP)?
A paradigm where programs are built around objects combining data and behavior
CPU optimization method
Programming language
Standard libraries
Only functions without data
Which pytest flag enables verbose output?
-v
-k
-x
-q
-s
What does plt.plot([1,2,3,4], [1,4,2,3]) do?
Plots a line chart
Displays a histogram
Creates a bar chart
Plots a heatmap
Forms a pie chart
What is a library in Python?
A collection of pre-written code (functions, classes, objects) for specific tasks
Variable storage
Interpreter module
GUI
Installation folder
Which library is the foundation of numerical computing in Python?
NumPy
Pandas
TensorFlow
Requests
Matplotlib
Which method reads the entire file into one string?
f.read()
f.tell()
f.readlines()
f.readline()
f.seek(0)
What is the general message from the lecture: “Using GPU is not magic”?
It is an outdated technology
GPU is only suitable for gaming
It is a marketing slogan
It is an experimental approach
What is the main goal of encapsulation in OOP?
Hiding internal implementation and protecting data
Providing a simple interface
Using attributes with a single underscore
Creating a class hierarchy
Ensuring polymorphic behavior
Which class name corresponds to Python conventions (PEP 8)?
UserProfil
user-Profile
userprofile
USER_PROFILE
user_profile
What are object methods?
Functions defined inside a class that describe the behavior of an object
Any functions in a module
Only built-in functions
OS constructors
Special variables
Which OOP property allows working with objects of different classes through a unified interface?
Polymorphism
Encapsulation
Composition
Abstraction
Inheritance
What is an object (instance of a class)?
A specific instance created from a class
A class description
Only an integer or string
Any Python module
Program file name
What does inheritance do in class Dog(Animal):?
Dog receives all methods and attributes of Animal
Dog cannot add its own methods
Dog deletes Animal’s methods
Dog turns Animal into an abstract class
Dog is no longer an object
What is the pytest module used for?
Writing and running automated tests
Web applications
Data visualization
Asynchronous programming
Databases
Which import is the correct alias for NumPy?
import numpy as np
import numpy.all
import numpy as num
import np as numpy
from numpy import base
What is the main purpose of virtual environments in Python?
Isolation of libraries for different projects
Automatic code formatting
Project file management
Speeding up execution
What will be displayed in the console?
Operation successful Completion.
Division by zero!
Only "Completion."
What does checking the range of values in data mean?
That values fall within acceptable limits (e.g., age from 18 to 120)
Data is sorted
File size is limited
All values are the same
Column contains only text
What does data validation for missing values check?
That there are no empty values (NaN, None) in specified columns
That data is encrypted
That the file is CSV
That strings are sorted
That all numbers are positive
