Тест по Python
1. Что из предложенных вариантов используется для однострочного комментирования ?
2. Как правильно объявить переменную ?
-
int x = 10
-
x = 10
-
var x = 10
-
x := 10
3. Какой результат выполнения следующего кода: print(2 + 3 * 4)?
4. Какой тип данных используется для хранения текстовых значений ?
5. Что вернет выражение len("Hello, World!")?
-
11
-
12
-
13
-
14
-
Hello, World!
6. Какое ключевое слово используется для определения функции ?
7. Какой оператор используется для проверки равенства ?
8. Какой из следующих вариантов правильно использует условную конструкцию if ?
-
if (x == 5) then:
-
if x = 5:
-
if x == 5:
-
if (x == 5):
9. Какой блок кода выполнится, если условие в конструкции if истинно?
-
Код, следующий сразу за if
-
Код, выделенный отступом после if
-
Код, заключенный в скобки после if
-
Код, записанный в следующей строке после if
10. Какой оператор используется для добавления альтернативного условия в конструкции if?
-
else if
-
elif
-
elseif
-
else: if
11. Какой результат выполнения следующего кода?
x = 10
if x > 5:
print("Больше пяти")
else:
print("Не больше пяти")
-
Больше пяти
-
Не больше пяти
-
Ошибка
-
Ничего
12. Что выведет следующий код?
x = 10
if x > 5:
print("Больше пяти")
if x < 15:
print("Меньше пятнадцати")
-
Больше пяти
-
Меньше пятнадцати
-
Больше пяти и меньше пятнадцати
-
Иван, не списывай!
13. Ключевое слово для анонимной функции?
-
anonymous
-
lambda
-
function
-
def
14. Как правильно объявить анонимную функцию, которая принимает один аргумент x и возвращает x + 1?
-
lambda x: x + 1
-
lambda x => x + 1
-
def lambda x: x + 1
-
lambda (x) { return x + 1; }
15. Какой оператор используется для создания цикла с известным количеством итераций ?
16. Какой результат выполнения следующего кода?
for i in range(5):
print(i)
-
0 1 2 3 4
-
1 2 3 4 5
-
0 1 2 3 4 5
-
1 2 3 4
17. Какой оператор используется для создания цикла с неизвестным количеством итераций, выполняющегося до тех пор, пока условие истинно?
18. Какой результат выполнения следующего кода?
x = 0
while x < 3:
print(x)
x += 1
19. Какой оператор используется для завершения текущей итерации цикла и перехода к следующей итерации?
20. Какой оператор используется для немедленного выхода из цикла?
21. Какой результат выполнения следующего кода?
for i in range(5):
if i == 3:
break
print(i)
-
0 1 2 3 4
-
0 1 2
-
1 2 3 4
-
0 1 2 3
22. Что произойдет, если в цикле while условие никогда не станет ложным?
-
Цикл выполнится один раз
-
Цикл завершится с ошибкой
-
Цикл будет выполняться бесконечно
-
Цикл выполнится, затем завершится
23. Какой оператор используется для возврата значения из функции ?
24. Какой результат выполнения следующего кода?
def add(a, b):
return a + b
result = add(3, 4)
print(result)
25. Можно ли использовать оператор return для выхода из функции без возврата значения?
26. Какой результат выполнения следующего кода?
def say_hello():
print("Hello")
return
print("World")
say_hello()
27. Какой результат выполнения следующего кода?
def multiply(a, b):
return a * b
return a + b
result = multiply(2, 3)
print(result)
28. Какой результат выполнения следующего кода?
def check_even(x):
if x % 2 == 0:
return True
else:
return False
result = check_even(4)
print(result)
29. Какое ключевое слово используется для создания класса ?
30. Что такое объект в ООП?
-
Функция внутри класса
-
Переменная внутри класса
-
Экземпляр класса
-
Метод внутри класса
31. Что такое метод в классе?
-
Переменная, определенная в классе
-
Функция, определенная в классе
-
Ключевое слово для создания класса
-
Параметр, передаваемый в функцию
32. Какой результат выполнения следующего кода?
class Diana:
def __init__(self, name):
self.name = name
def fly(self):
return f"{self.name}, не списывай! "
diana1 = Diana("Диана")
print(diana1.fly())
-
, не списывай!
-
Диана, !
-
Иван, не списывай!
-
Диана, не списывай!
33. Для чего используется __init__ ?
-
Метод, который вызывается для удаления объекта
-
Метод, который вызывается при создании экземпляра класса
-
Метод, который вызывается для преобразования объекта в строку
-
Метод, который вызывается для сравнения двух объектов
34. Что такое инкапсуляция в объектно-ориентированном программировании?
-
Создание объекта класса
-
Сокрытие данных внутри класса и предоставление доступа к ним через методы
-
Наследование методов и атрибутов от другого класса
-
Создание нового экземпляра класса
35. Как обозначаются приватные атрибуты класса ?
-
С помощью префикса _ (один подчеркивания)
-
С помощью префикса __ (два подчеркивания)
-
С помощью префикса priv_
-
С помощью префикса private_
36. Какой результат выполнения следующего кода?
class Test:
def __init__(self):
self.__hidden = 42
test = Test()
print(test.__hidden)
37. Что такое свойство (property) ?
-
Функция, которая возвращает атрибут объекта
-
Переменная, доступная только внутри класса
-
Специальный метод, который позволяет управлять доступом к атрибутам
-
Класс, который содержит другие классы
38. Что такое наследование в ООП?
-
Механизм создания экземпляра класса
-
Механизм получения доступа к приватным атрибутам
-
Механизм создания нового класса на основе существующего
-
Механизм удаления объекта
39. Какой ключевое слово используется для указания наследования ?
-
inherits
-
extends
-
derives
-
class
40. Какой результат выполнения следующего кода?
class Animal:
def speak(self):
return "Animal speaks"
class Dog(Animal):
pass
dog = Dog()
print(dog.speak())
-
Ошибка
-
Animal speaks
-
none
41. Как вызвать метод суперкласса из подкласса?
-
superclass.method()
-
self.method()
-
super().method()
-
baseclass.method()
42. Можно ли создать класс, который наследует от нескольких классов ?
43. Какая функция позволяет вызывать метод базового класса из метода дочернего класса?
44. Какое утверждение верно для кортежей?
-
Кортежи могут быть изменены после создания.
-
Кортежи являются неупорядоченными коллекциями элементов.
-
Кортежи являются упорядоченными коллекциями элементов, которые не могут быть изменены после создания.
45. Как создать кортеж из одного элемента?
-
new_tuple = (1)
-
new_tuple = [1]
-
new_tuple = (1,)
46. Какие операции можно выполнять с кортежами ?
-
Изменять элементы кортежа
-
Объединять кортежи
-
Удалять элементы из кортежа
47. Как получить индекс определенного элемента в кортеже?
-
tuple_name.index(element)
-
index(tuple_name, element)
-
element.index(tuple_name)
48. Что делает конструкция try...except...finally?
-
Пытается выполнить блок кода внутри try, если возникает исключение, выполняет блок кода внутри except, а затем блок кода внутри finally.
-
Пытается выполнить блок кода внутри try, если возникает исключение, сразу переходит к блоку finally, а затем except.
-
Пытается выполнить блок кода внутри try, если возникает исключение, сразу переходит к блоку except, а затем finally.
49. Какой из блоков (try, except, finally) является необязательным в конструкции try...except...finally?
50. Как добавить элемент в словарь?
-
dict.add(1, 2)
-
dict[1] = 2
-
dict.append(1, 2)