Python

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

Which of the following is a protected attribute?

- _sara_ - _sara

Explain how can you make a Python Script executable on Unix?

Script file must begin with #!/usr/bin/env python

What is __init__ method in python?

The __init__ method is the constructor. The method is run as soon as an object is instantiated. It is useful for initializing any attributes or default behaviour of the object at the time of instantiation.

Write a Program to combine two different dictionaries. While combining, if you find the same keys, you can add the values of these same keys. Output the new dictionary.

We can use the Counter method from the collections module. $ from collections import Counter $ d1 = {'key1': 50, 'key2': 100, 'key3':200} $ d2 = {'key1': 200, 'key2': 100, 'key4':300} $ new_dict = Counter(d1) + Counter(d2) $ print(new_dict)

Is it possible to call parent class without its instance creation?

Yes, it is possible if the base class is instantiated by other child classes or if the base class is a static method.

пример кастомных типов данных

datetime, __str__

What are iterators in Python?

- An iterator is an object. - It remembers its state i.e., where it is during iteration - __iter__() method initializes an iterator. - It has a __next__() method which returns the next item in iteration and points to the next element. Upon reaching the end of iterable object __next__() must return StopIteration exception. - It is also self-iterable. - Iterators are objects with which we can iterate over iterable objects like lists, strings, etc. 1) accumulate(iter, func): This iterator takes two arguments, iterable target and the function which would be followed at each iteration of value in target. If no function is passed, addition takes place by default. If the input iterable is empty, the output iterable will also be empty. arr5 = list(itertools.accumulate(arr4,operator.mul)) 2) chain(iter1, iter2..): This function is used to print all the values in iterable targets one after another mentioned in its arguments. arr4 = list(itertools.chain(arr1,arr2,arr3)) 3) tee(iterator, count):- This iterator splits the container into a number of iterators mentioned in the argument. iti = iter(arr) it = itertools.tee(iti, 3)

What is break, continue in Python?

- Break. The break statement terminates the loop immediately and the control flows to the statement after the body of the loop. - Continue. The continue statement terminates the current iteration of the statement, skips the rest of the code in the current iteration and the control flows to the next iteration of the loop.

CI (continuous integration) and CD (continuous delivery) are ...

- Continuous Integration (CI) is a software development practice where developers frequently integrate their code changes into a shared repository, which is then verified by an automated build and testing process. The goal of CI is to catch integration problems early in the development cycle, thereby reducing the time and effort required to identify and fix bugs. - Continuous Delivery (CD) is an extension of CI that ensures that changes to the codebase can be automatically built, tested, and deployed to production. The ultimate goal of CD is to enable teams to release software quickly, reliably, and frequently, by automating the entire software delivery process. In essence, CI is a practice that focuses on building quality into the development process by detecting issues early, while CD focuses on ensuring that those changes can be safely and rapidly deployed to production. Together, these two practices can help teams to deliver software faster and more efficiently, with fewer errors and greater confidence.

In Django what is caching?

- Django caching is a technique used to temporarily store frequently accessed data or computation results in memory or disk, in order to speed up the response time of web applications. When a user makes a request for a page, Django checks whether the requested data is already in the cache. If it is, Django retrieves the data from the cache instead of computing it again, which significantly reduces the processing time. There are different types of caching in Django, including: - Database caching: Data is stored in the database instead of in memory or disk. This can be useful for applications with a lot of data that cannot fit into memory. - Memory caching: Data is stored in the memory of the web server. This is the fastest caching method, but the data is lost when the server is restarted. - File caching: Data is stored in files on disk. This method is slower than memory caching, but the data persists even after the server is restarted. - Cache Frameworks: Django provides a cache framework that allows developers to use different types of cache backends such as Memcached, Redis, or local memory. CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } -------------------------------------------- $ from django.core.cache import cache $ def my_view(request): result = cache.get('my_key') if not result: result = expensive_computation() cache.set('my_key', result, timeout=60) return render(request, 'my_template.html', {'result': result}) Template fragment caching. $ from django.shortcuts import render $ from django.views.decorators.cache import cache_page $ @cache_page(60 * 15) # cache for 15 minutes $ def my_view(request): data = get_data_from_database() return render(request, 'my_template.html', {'data': data}) Template tag. {% load cache %} {% cache 300 my_cache_key %} <p>This is some expensive computation:</p> {% expensive_computation %} {% endcache %} Overall, caching is a powerful technique that can significantly improve the performance of Django applications, especially for frequently accessed data or computation results. By using the caching framework and template fragment caching, you can easily add caching to your Django application and make it more efficient. Finally, it's important to note that caching can have some drawbacks, especially if you cache data for too long or use it improperly. Cached data may become stale or outdated, which can lead to incorrect or inconsistent results. Additionally, caching can consume a significant amount of memory or disk space, depending on the size of the data being cached. Therefore, it's important to use caching judiciously and to monitor its impact on your application's performance and resource usage.

Что такое HTTP, идемпотентные и не идемпотентные методы

- Idempotent: An HTTP method is idempotent if the intended effect on the server of making a single request is the same as the effect of making several identical requests. This does not necessarily mean that the request does not have any unique side effects: for example, the server may log every request with the time it was received. Idempotency only applies to effects intended by the client: for example, a POST request intends to send data to the server, or a DELETE request intends to delete a resource on the server. All safe methods are idempotent, as well as PUT and DELETE. The POST method is NOT-idempotent. To be idempotent, only the state of the server is considered. The response returned by each request may differ: for example, the first call of a DELETE will likely return a 200, while successive ones will likely return a 404. Another implication of DELETE being idempotent is that developers should not implement RESTful APIs with a delete last entry functionality using the DELETE method. Note that the idempotence of a method is not guaranteed by the server and some applications may incorrectly break the idempotence constraint. GET /pageX HTTP/1.1 is idempotent, because it is a safe (read-only) method. Successive calls may return different data to the client, if the data on the server was updated in the meantime. POST /add_row HTTP/1.1 is not idempotent; if it is called several times, it adds several rows: POST /add_row HTTP/1.1 POST /add_row HTTP/1.1 -> Adds a 2nd row POST /add_row HTTP/1.1 -> Adds a 3rd row DELETE /idX/delete HTTP/1.1 is idempotent, even if the returned status code may change between requests: DELETE /idX/delete HTTP/1.1 -> Returns 200 if idX exists DELETE /idX/delete HTTP/1.1 -> Returns 404 as it just got deleted DELETE /idX/delete HTTP/1.1 -> Returns 404

What are Python namespaces? Why are they used?

- In Python, a namespace is a mapping from the names of variables to their corresponding objects. When you create a variable in Python, it is stored in a namespace along with other variables and objects. - Namespaces are used to avoid naming conflicts and to provide a way to organize variables, functions, and classes in a program. In Python, namespaces are implemented as dictionaries, where the keys are the names of the variables, and the values are the corresponding objects. - When you create a variable in Python, it is automatically placed in the current namespace, which depends on where the variable is defined. For example, if you define a variable inside a function, it will be placed in the function's namespace. If you define a variable at the top level of a module, it will be placed in the module's namespace. - You can access variables from other namespaces by either using the fully qualified name (i.e., namespace.variable) or by importing the variable into your current namespace. Overall, namespaces provide a way to organize and manage variables, functions, and classes in a program, which makes it easier to write and maintain Python code.

How are arguments passed by value or by reference in python?

- Pass by value: Copy of the actual object is passed. Changing the value of the copy of the object will not change the value of the original object. - Pass by reference: Reference to the actual object is passed. Changing the value of the new object will change the value of the original object. In Python, arguments are passed by reference, i.e., reference to the actual object is passed.

How Python is interpreted?

- Python as a language is not interpreted or compiled. Interpreted or compiled is the property of the implementation. Python is a bytecode(set of interpreter readable instructions) interpreted generally. - Source code is a file with .py extension. - Python compiles the source code to a set of instructions for a virtual machine. The Python interpreter is an implementation of that virtual machine. This intermediate format is called "bytecode". - .py source code is first compiled to give .pyc which is bytecode. This bytecode can be then interpreted by the official CPython or JIT(Just in Time compiler) compiled by PyPy.

What are unit tests in Python?

- Unit test is a unit testing framework of Python. - Unit testing means testing different components of software separately. Can you think about why unit testing is important? Imagine a scenario, you are building software that uses three components namely A, B, and C. Now, suppose your software breaks at a point time. How will you find which component was responsible for breaking the software? Maybe it was component A that failed, which in turn failed component B, and this actually failed the software. There can be many such combinations. - This is why it is necessary to test each and every component properly so that we know which component might be highly responsible for the failure of the software.

What is the use of help() and dir() functions?

- help() function in Python is used to display the documentation of modules, classes, functions, keywords, etc. If no parameter is passed to the help() function, then an interactive help utility is launched on the console. - dir() function tries to return a valid list of attributes and methods of the object it is called upon. It behaves differently with different objects, as it aims to produce the most relevant data, rather than the complete information: - For Modules/Library objects, it returns a list of all attributes, contained in that module. - For Class Objects, it returns a list of all valid attributes and base attributes. - With no arguments passed, it returns a list of attributes in the current scope.

Можете коротко объяснить, как используются модули sqlite3, ctypes, pickle, traceback и itertools.

- sqlite3 помогает обрабатывать базы данных, например SQLite; - ctypes позволяет создавать в питоне типы данных из Си и обрабатывать их; - pickle позволяет переносить любые структуры данных во внешние файлы; - traceback позволяет извлекать, форматировать и выводить на печать трассы вызовов (stack traces); - itertools помогает работать с перестановками (permutations), комбинациями (combinations) и другими итерируемыми объектами (iterables).

Как вы тестируете код? Что такое mock? Что такое Pytest?

- unittest.mock is a library for testing in Python. It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used. unittest.mock provides a core Mock class removing the need to create a host of stubs throughout your test suite. - A mock object substitutes and imitates a real object within a testing environment. It is a versatile and powerful tool for improving the quality of your tests. One reason to use Python mock objects is to control your code's behavior during testing. For example, if your code makes HTTP requests to external services, then your tests execute predictably only so far as the services are behaving as you expected. Sometimes, a temporary change in the behavior of these external services can cause intermittent failures within your test suite. Because of this, it would be better for you to test your code in a controlled environment. Replacing the actual request with a mock object would allow you to simulate external service outages and successful responses in a predictable way.

Генератор и Итератор?

- Итератор является более общей концепцией, чем генератор, и представляет собой любой объект, класс которого имеет методы __next__ и __iter__. - Генератор - это итератор, который обычно создается путем вызова функции, содержащей не менее одного оператора yield. Это ключевое слово действует аналогично return, но возвращает объект-генератор. Между ними существуют тонкие различия: - Для генератора мы пишем функцию, а для итератора можно использовать встроенные функции iter() и next(). - Для генератора используется ключевое слово yield для выдачи по одному объекту за раз. - В генераторе может быть сколько угодно операторов yield. - Генератор сохраняет текущее состояние локальных переменных (local variables) каждый раз, когда yield приостанавливает цикл (loop). Итератор не использует локальные переменные, он работает только с итерируемым объектом (iterable). - Итератор можно использовать с помощью класса, а генератор — нет. - Генераторы работают быстро, компактно и проще. - Итераторы экономнее потребляют память.

Что такое функция?

- Функция в Python — это объект, принимающий аргументы и возвращающий значение. - Функции позволяют определять и повторно использовать определенную функциональность в компактной форме. - Вызвать функцию — значит передать ей входные данные, необходимые для выполнения и возвращения результата. Когда вы передаете функции входные данные, это называется передача параметра функции. - Ключевое слово def сообщает Python, что вы определяете функцию. После def вы указываете имя функции; оно должно отвечать тем же правилам, что и имена переменных. Согласно конвенции, в имени функции нельзя использовать заглавные буквы, а слова должны быть разделены подчеркиванием. Как только вы присвоили своей функции имя, укажите после него круглые скобки. Внутри скобок должен содержаться один или несколько параметров. После скобок ставится двоеточие, а новая строка начинается с отступа в четыре пробела. Любой код с отступом в четыре пробела после двоеточия является телом функции. - Ключевое слово return используется для определения значения, которое функция возвращает при вызове. - Чтобы вызвать функцию в Python, мы используем синтаксис: имя_функции(параметры, через, запятую).

What are global, protected and private attributes in Python?

1) Global variables are public variables that are defined in the global scope. To use the variable in the global scope inside a function, we use the global keyword. 2) Protected attributes are attributes defined with an underscore prefixed to their identifier eg. _sara. They can still be accessed and modified from outside the class they are defined in but a responsible developer should refrain from doing so. 3) Private attributes are attributes with double underscore prefixed to their identifier eg. __sara. They cannot be accessed or modified from the outside directly and will result in an AttributeError if such an attempt is made. Every member with a double underscore will be changed to _object._class__variable. So, it can still be accessed from outside the class, but the practice should be refrained.

Генератор (yield и tuple comprehension)

1) In Python, there's no tuple comprehension. However, you can mimic the tuple comprehensions by running a generator expression inside tuple() function call. $ numbers = [1, 2, 3, 4, 5] $ squares = tuple(x**2 for x in numbers) $ print(squares) -># Output: (1, 4, 9, 16, 25) 2) In Python, a generator expression is a concise way to create a generator object. It is similar to list comprehension, but instead of creating a list, it creates a generator. A generator is an iterator that generates values on the fly, rather than storing them in memory. This makes it more efficient, especially when working with large collections of data. $ squares = (x**2 for x in range(1, 11)) Squares will be calculated on the fly rather than storing them in memory. Because of this, you could use a generator to generate squares all the way to infinity without running into memory problems. 3) how the 'tuple comprehension' works: $ squares = tuple(x**2 for x in numbers) $ print(squares) -># Output: (1, 4, 9, 16, 25)

Типы данных

1) None (неопределенное значение переменной). 2) Логические переменные (Boolean Type). 3) Числа (Numeric Type): - int - целое число, - float - число с плавающей точкой, - complex - комплексное число. 4) Списки (Sequence Type): - list - список, - tuple - кортеж, - range - диапазон. 5) Строки (Text Sequence Type): - str 6) Бинарные списки (Binary Sequence Types): - bytes - байты, - bytearray - массивы байт, - memoryview - специальные объекты для доступа к внутренним данным объекта через protocol buffer. 7) Множества (Set Types): - set - множество, -- frozenset - неизменяемое множество. 8) Словари (Mapping Types): - dict - словарь. Эти типы данных можно, в свою очередь, классифицировать по нескольким признакам: - изменяемые (списки, словари и множества), - неизменяемые (числа, строки и кортежи), - упорядоченные (списки, кортежи, строки и словари), - неупорядоченные (множества).

How do you create a class in Python?

1) To create a class in python, we use the keyword "class": $ class InterviewbitEmployee: def __init__(self, emp_name): self.emp_name = emp_name 2) To instantiate or create an object from the class created above, we do the following: $ emp_1 = InterviewbitEmployee("Mr. Employee") 3) To access the name attribute, we just call the attribute using the dot operator as shown below: $ print(emp_1.emp_name) -> Mr. Employee 4) To create methods inside the class, we include the methods under the scope: $ def introduce(self): print("Hello I am " + self.emp_name) 5) The "self" parameter in the init and introduce functions represent the reference to the current class instance which is used for accessing attributes and methods of that class. The "self" parameter has to be the first parameter of any method defined inside the class. The method of the class InterviewbitEmployee can be accessed: $ emp_1.introduce()

Explain split() and join() functions in Python?

1) split() function to split a string based on a delimiter to a list of strings. 2) join() function to join a list of strings based on a delimiter to give a single string. $ string = "This is a string." $ string_list = string.split(' ') #delimiter is 'space' character or ' ' $ print(string_list) ->#output: ['This', 'is', 'a', 'string.'] $ print(' '.join(string_list)) ->#output: This is a string.

Ошибки, типы ошибок, raise, try.

1) Выражение try-except. Чтобы охватить всю программу целиком или только отдельные фрагменты кода для обнаружения и определения ошибок могут использоваться выражения try-except. Если в выражении try возникнет ошибка, будет создано исключение, и код будет выполнен в соответствии с выражением except. Использование выражения except является наиболее простой формой обработки ошибок. Выражение try содержит необязательное условие finally, которое можно использовать для задач, которые должны выполняться всегда, независимо от того, возникает исключение или нет. 2) Выражение raise. В некоторых случаях может потребоваться создать пользовательские исключения. Для этой цели может использоваться выражение raise. 3) Основные исключения. Список основных встроенных исключений: - Exception - то, на чем фактически строятся все остальные ошибки; - AttributeError - возникает, когда ссылка атрибута или присвоение не могут быть выполнены; - IOError - возникает в том случае, когда операция I/O (такая как оператор вывода, встроенная функция open() или метод объекта-файла) не может быть выполнена, по связанной с I/O причине: «файл не найден», или «диск заполнен», иными словами. - ImportError - возникает, когда оператор import не может найти определение модуля, или когда оператор не может найти имя файла, который должен быть импортирован; - IndexError - возникает, когда индекс последовательности находится вне допустимого диапазона; - KeyError - возникает, когда ключ сопоставления (dictionary key) не найден в наборе существующих ключей; - KeyboardInterrupt - возникает, когда пользователь нажимает клавишу прерывания(обычно Delete или Ctrl+C); - NameError - возникает, когда локальное или глобальное имя не найдено; - OSError - возникает, когда функция получает связанную с системой ошибку; - SyntaxError — возникает, когда синтаксическая ошибка встречается синтаксическим анализатором; - TypeError - возникает, когда операция или функция применяется к объекту несоответствующего типа. - ValueError - возникает, когда встроенная операция или функция получают аргумент, тип которого правильный, но неправильно значение, и ситуация не может описано более точно, как при возникновении IndexError; - ZeroDivisionError - возникает, когда второй аргумент операции division или modulo равен нулю.

Oператор вхождения (in / not in).

1) Оператор in возвращает True если в некотором наборе значений есть определенное значение: $ message = "hello world!" $ hello = "hello" $ print(hello in message) -># True 2) Если нам надо наоборот проверить, нет ли в наборе значений какого-либо значения, то мы може использовать модификацию оператора - not in. Она возвращает True, если в наборе значений НЕТ определенного значения.

виды связей между таблицами - один к одному, многие к одному, один ко многим, многие ко многим, реализация в django ORM.

1) Связи создаются с помощью внешних ключей (foreign key). Внешний ключ — это атрибут, который ссылается на primary key другой таблицы. Другими словами, это что-то вроде указателя на строку другой таблицы. 2) Виды связей: - Многие ко многим, MTM; (Для реализации связи многие ко многим нам нужен некий посредник между двумя рассматриваемыми таблицами. Он должен хранить два внешних ключа, первый из которых ссылается на первую таблицу, а второй — на вторую.) - Один ко многим, OTM; (Эта самая распространенная связь между базами данных. Таблица-посредник тут не нужна.) - Один к одному, OTO. (Можно сказать, что отношение один к одному — это разделение одной и той же таблицы на две.) Django ORM (Object Relational Mapping) является одной из самых мощных особенностей Django. Это позволяет нам взаимодействовать с базой данных, используя код Python, а не SQL. In Django, select_related and prefetch_related are designed to stop the deluge of database queries that are caused by accessing related objects. - select_related() "follows" foreign-key relationships, selecting additional related-object data when it executes its query. One uses select_related when the object that you're going to be selecting is a single object, so OneToOneField or a ForeignKey. - prefetch_related() does a separate lookup for each relationship and does the "joining" in Python. You use prefetch_related when you're going to get a "set" of things, so ManyToManyFields as you stated or reverse ForeignKeys.

Преобразование списка строк в список целых чисел в Python

1. Использование map(). Он применяет указанную функцию к каждому элементу списка, получая результаты. Поскольку он возвращает итератор, преобразуйте результат в список. $ strings = ["1", "2", "3", "4", "5"] $ nums = list(map(int, strings)) $ print(nums) -># [1, 2, 3, 4, 5] Приведенный выше код создает новый список. Вы можете изменить существующий список на месте присвоив срезу [:]: $ nums[:] = list(map(int, nums)) 2. Использование List Comprehension $ nums = [int(s) for s in strings]

SOLID: 4) The Interface Segregation Principle (ISP)

4) The Interface Segregation Principle (ISP) "Many client-specific interfaces are better than one general-purpose interface". In the contest of classes, an interface is considered, all the methods and properties "exposed", thus, everything that a user can interact with that belongs to that class. In this sense, the IS principles tell us that a class should only have the interface needed (SRP) and avoid methods that won't work or that have no reason to be part of that class. This problem arises, primarily, when, a subclass inherits methods from a base class that it does not need. Every sub-class inherits only what it needs, avoiding invoking an out-of-context (wrong) sub-method. That might create an error hard to catch. This principle is closely connected with the other ones and specifically, it tells us to keep the content of a subclass clean from elements of no use to that subclass. This has the final aim to keep our classes clean and minimise mistakes. Принцип разделения интерфейсов гласит, что «Ни один клиент не должен зависеть от методов, которые он не использует». Принцип разделения интерфейсов предполагает создание небольших интерфейсов, известных как «ролевые интерфейсы», вместо большого интерфейса, состоящего из нескольких методов. Разделяя методы по ролям на более мелкие интерфейсы, клиенты будут зависеть только от методов, которые имеют к ним отношение.

Write python function which takes a variable number of arguments.

A function that takes variable arguments is called a function prototype. Syntax: def function_name(*arg_list). For example: $ def func(*var): for i in var: print(i) $ func(1) $ func(20, 1, 6) The * in the function argument represents variable arguments in the function.

In Django what is CSRF-token?

CSRF (Cross-Site Request Forgery) is a type of security vulnerability that can occur when a user is tricked into performing an action on a website without their knowledge or consent. Django provides a built-in protection against CSRF attacks through the use of CSRF tokens. A CSRF token is a unique, randomly generated value that is included in the HTML form of a Django application. This token is then checked when the form is submitted, to ensure that the form submission is legitimate and not the result of a CSRF attack. In your Django view, you can use the csrf_protect decorator to ensure that the CSRF token is checked: $ from django.views.decorators.csrf import csrf_protect $ @csrf_protect $ def my_view(request): if request.method == 'POST': # Process form data here... With these steps, your Django application will be protected against CSRF attacks.

Что такое словарь (dictionary)?

Dictionary in Python is a collection of keys values, used to store data values like a map, which, unlike other data types which hold only a single value as an element. Dictionary methods: - dic.clear() - Remove all the elements from the dictionary; - dict.copy() - Returns a copy of the dictionary; - dict.get(key, default = "None") - Returns the value of specified key; used to get the value specified for the passed key. - dict.items() - Returns a list containing a tuple for each key value pair; - dict.keys() - Returns a list containing dictionary's keys; - dict.update(dict2) - Updates dictionary with specified key-value pairs; - dict.values() - Returns a list of all the values of dictionary; - pop() - Remove the element with specified key; - popItem() - Removes the last inserted key-value pair; - dict.setdefault(key, default= "None") - set the key to the default value if the key is not specified in the dictionary; - dict.has_key(key) - returns true if the dictionary contains the specified key.

In Django what is django admin?

Django admin is a built-in application of the Django web framework that provides a user-friendly interface for managing the content of a Django project. It allows developers to perform CRUD (Create, Retrieve, Update, Delete) operations on the data in the database without writing any code. The Django admin site is automatically generated based on the models defined in the project. The site includes a login page, a dashboard, and the ability to add, edit, and delete instances of each model. It also provides search, filtering, and sorting capabilities, as well as the ability to export data in various formats like CSV, JSON, and XML. - Create a superuser account: To access the admin site, a user must be authenticated. Django provides a command-line utility to create a superuser account, which has access to all the features of the admin site. $ ./manage.py createsuperuser - Register a model: To make a model editable in the admin site, it must be registered with the admin site. This is done by creating an admin.py file in the app directory and registering the model using the admin.site.register() function: $ from django.contrib import admin $ from .models import Post $ admin.site.register(Post) - Customize the admin site: Django admin provides many ways to customize the look and feel of the admin site. For example, you can customize the list of fields displayed for each instance of a model, add custom actions to perform on multiple instances at once, and override the default templates. $ list_display = ('title', 'author', 'pub_date') - Add inline editing: In Django admin, it is possible to edit related models inline, without having to navigate to a separate page. This is done using the InlineModelAdmin class, which is a subclass of ModelAdmin. $ class CommentInline(admin.TabularInline): model = Comment $ classPostAdmin(admin.ModelAdmin): inlines = [CommentInline] - Use third-party packages: Django admin is highly extensible and can be customized using third-party packages. For example, the django-import-export package provides a way to import and export data from the admin site in various formats, including Excel, CSV, and JSON. To use this package, you can install it using pip and add it to the INSTALLED_APPS setting in settings.py. Then, you can define an ImportExportModelAdmin class for the model you want to import and export, and include it in the ModelAdmin subclass. - Create custom views: In addition to the automatically generated views, it is possible to create custom views in Django admin. This can be useful for performing complex operations that cannot be accomplished using the built-in views. To create a custom view, you can define a method in the ModelAdmin subclass and decorate it with the @admin.action decorator. For example, suppose you have a Book model and you want to mark selected books as "out of stock" in the admin site. - Limit access to the admin site: By default, the admin site is accessible to all authenticated users. However, it is possible to restrict access to specific users or groups using Django's built-in authentication system. To limit access to the admin site, you can define a custom ModelAdmin subclass and override the has_view_permission() method. - Customize the look and feel: Django admin's default templates and styles can be customized to match the look and feel of your site. This can be done by creating custom templates and static files and registering them with Django's template and static files finders.

как реализована работа с базой данных

Django может работать с множеством БД. Открываем файл настроек, settings.py находящийся в каталоге проекта находим там такие строчки и модифицируем их до: $ DATABASE_ENGINE = 'postgresql_psycopg2' #'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_NAME = myDBName DATABASE_USER = myUserDB DATABASE_PASSWORD = myUserDBPasswor Модель БД в django — описание таблиц на языке python. Для создания модели приложения необходимо отредактировать models.py. В модели описывается много классов, каждый из которых будет описывать одну таблицу БД, а свойство класса — это один столбец таблицы. Класс должен быть унаследован от models.Model описанного в пакете django.db.models. Свойства класса должны иметь типы описанные в пакете django.db.models: - models.DateTimeField() — поле содержащее в себе Дату и Время - models.CharField(max_length= xx) — Текстовое поле ограниченной длины. Длина строки до 255 символов - models.BooleanField() — Trure / False - models.ForeignKey() — ссылка на внешнюю таблицу - models.PositiveIntegerField() — положительное целое значение - models.URLField(max_length=хх) — ссылка на web страницу длина ссылки ограничена xx символами - models.DateField() — поле содержащие Дату и т.д. Мы создали наши модели, теперь нам нужно применить эти миграции: $ python3 manage.py makemigrations $ python3 manage.py migrate

python django система аутентификации

Django предоставляет систему аутентификации и авторизации ("permission") пользователя, реализованную на основе фреймворка работы с сессиями. Система аутентификации и авторизации позволяет вам проверять учётные данные пользователей и определять какие действия какой пользователь может выполнять. Данный фреймворк включает в себя встроенные модели для Пользователей и Групп (основной способ применения прав доступа для более чем одного пользователя), непосредственно саму систему прав доступа (permissions)/флаги, которые определяют может ли пользователь выполнить задачу, с какой формой и отображением для авторизованных пользователей, а так же получить доступ к контенту с ограниченным доступом. Примечание: В соответствии с идеологией Django система аутентификации является очень общей и, таким образом, не предоставляет некоторые возможности, которые присутствуют в других системах веб-аутентификации. Решениями некоторых общих задач занимаются пакеты сторонних разработчиков, например, защита от подбора пароля (через стороннюю библиотеку OAuth). Соответствующие настройки сделаны в параметрах INSTALLED_APPS и MIDDLEWARE файла проекта: $ INSTALLED_APPS = [ ... 'django.contrib.auth', 'django.contrib.contenttypes', $ MIDDLEWARE = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware' ########### Django provides a built-in authentication system, which is designed to help developers handle user authentication and authorization in their web applications. The authentication system is customizable and can be used to implement various types of authentication, including basic, session-based, token-based, and social authentication. - Basic authentication is the simplest type of authentication, where users provide their credentials (username and password) to access a protected resource. In Django, you can implement basic authentication using the built-in django.contrib.auth module. - Session-Based Authentication: Session-based authentication is a more advanced type of authentication, where a session ID is used to keep track of the user's authentication status. In Django, session-based authentication is enabled by default, and you can use the @login_required decorator to protect your views. - Token-Based Authentication: Token-based authentication is a type of authentication where a token is used to authenticate the user instead of a username and password. This type of authentication is often used for APIs and mobile applications. In Django, you can implement token-based authentication using the django-rest-framework package. - Social Authentication: Social authentication allows users to log in to your application using their social media accounts, such as Facebook, Twitter, or Google. In Django, you can use the django-allauth package to implement social authentication. Overall, Django's authentication system provides developers with a powerful and flexible tool for handling user authentication and authorization in their web applications. Depending on your application's needs, you can use one or more of the authentication methods described above to provide a secure and user-friendly authentication experience for your users.

docker, docker-compose

Docker is a software platform that allows you to build, deploy, and run applications in containers. Containers are lightweight, standalone packages that contain everything needed to run an application, including the code, runtime, system tools, libraries, and settings. Docker provides an easy way to package and distribute applications, making it easier to move applications between environments, such as development, testing, and production. Docker Compose is a tool for defining and running multi-container Docker applications. It allows you to define a set of services, each of which can be run in its own container, and configure how these containers should interact with each other. With Docker Compose, you can define complex applications that consist of multiple services, and then start and stop them all with a single command. This makes it easier to manage and deploy complex applications that consist of multiple components.

Define GIL.

GIL stands for Global Interpreter Lock. This is a mutex used for limiting access to python objects and aids in effective thread synchronization by avoiding deadlocks. GIL helps in achieving multitasking (and not parallel computing). For example, there are three threads. First Thread acquires the GIL first and starts the I/O execution. When the I/O operations are done, thread 1 releases the acquired GIL which is then taken up by the second thread. The process repeats and the GIL are used by different threads alternatively until the threads have completed their execution. The threads not having the GIL lock goes into the waiting state and resumes execution only when it acquires the lock.

Git flow is?

Git Flow is a branching model for Git created by Vincent Driessen. It is designed to help developers manage their Git branches and releases in a structured and organized way. Git Flow provides a set of guidelines for how to use Git to manage development and release cycles. It defines a specific branching model, with clear rules and procedures for creating, merging, and tagging branches. Git Flow is based on two main branches: master and develop. The master branch represents the stable production code, while the develop branch is used for ongoing development work. Developers create feature branches off the develop branch to work on new features, and then merge those branches back into develop when the feature is complete. When the code in develop is stable and ready for release, it is merged into the master branch and tagged with a release number. Git Flow also provides for the creation of hotfix branches off of master in case an urgent bug fix is needed. Once the hotfix is complete, it is merged back into both master and develop. Overall, Git Flow provides a clear and organized way for managing Git branches and releases, and has become a popular branching model among developers.

Git (VCS) is ...

Git is a distributed Version Control System (VCS) designed to handle everything from small to very large projects with speed and efficiency. It was created by Linus Torvalds in 2005 and has since become one of the most widely used VCS in the world. Git allows multiple developers to collaborate on a project simultaneously, making it easier to manage changes and keep track of revisions. With Git, each developer has their own copy of the project, and changes made by one developer can be merged with changes made by another developer without losing any data. Additionally, Git allows developers to work offline, making it possible to make changes to a project without an internet connection. Git is free and open source software, and it is available for Windows, Linux, and Mac operating systems. It has become an essential tool in modern software development and is widely used in many fields, including web development, game development, and scientific research.

GitHub, GitLab, and Bitbucket are ...

GitHub, GitLab, and Bitbucket are all web-based Git repository hosting services that allow users to store, manage, and share their Git repositories. - GitHub is the most popular and widely used of the three services, and it is owned by Microsoft. It offers a range of features including issue tracking, code review, project management, and integration with other tools. - GitLab is another popular repository hosting service that offers similar features to GitHub, but also includes some additional functionality such as continuous integration and deployment, monitoring, and security scanning. GitLab is an open source project, and there is both a self-hosted and a cloud-hosted version available. - Bitbucket is a repository hosting service owned by Atlassian, and it is primarily used by teams that use other Atlassian products such as Jira and Confluence. It offers features similar to GitHub and GitLab, such as code review and pull requests, but also includes features for collaboration, such as inline comments and mentions. Overall, the choice between GitHub, GitLab, and Bitbucket will depend on your specific needs and preferences, as each platform offers different features and capabilities.

Differences Between HTTP vs HTTPS.

HTTP и HTTPS (Hypertext Transfer Protocol vs Hypertext Transfer Protocol Secure). The most significant difference between the two protocols is that: - HTTPS is encrypted and secured using digital certificates, while HTML is not. When you visit a website using HTTPS, your connection to that site is encrypted. Any information you send or receive on that site is also encrypted. - another difference between the protocols is that HTTPS uses port 443, while HTML uses port 80. Port 443 is the standard port for secured Hypertext Transfer Protocol (HTTPS). Port 80 is the default port for unsecured Hypertext Transfer Protocol (or "protocol").

In Django what is Meta in Model?

In Django, Meta is a class used to define metadata options for a model. It is an inner class that is defined inside a model class and is used to provide additional information about the model. The Meta class can be used to set various options for the model, such as the name of the database table to use for the model, the ordering of the model's records in the database, whether the model is abstract or not, etc. By default, if you don't specify a Meta class for a model, Django will use default options for the model. Some of the other options that can be set in the Meta class of a Django model include: - db_table: specifies the name of the database table to use for the model. By default, Django will use the name of the model in lowercase as the table name. - verbose_name: specifies a human-readable name for the model. By default, Django will use the name of the model in sentence case as the verbose name. - verbose_name_plural: specifies the plural form of the verbose name. By default, Django will add an "s" to the end of the verbose name to create the plural form. - abstract: specifies whether the model is abstract or not. An abstract model is a model that is not intended to be instantiated on its own, but rather serves as a base class for other models to inherit from. - unique_together: specifies a list of fields that, when taken together, must be unique in the database. For example, if you have a User model with first_name and last_name fields, you might want to specify unique_together = ('first_name', 'last_name') to ensure that no two users can have the same first and last name. Overall, the Meta class is a powerful tool in Django that allows you to customize the behavior of your models in a wide variety of ways.

In Django what are queryset and manager, with examples?

In Django, a QuerySet is a collection of database records returned as a result of a query. It allows you to filter, order, and slice the data in a flexible and powerful way. On the other hand, a Manager is the interface through which Django models interact with the database. Managers are used to create, retrieve, update, and delete objects from the database. Here is an example of how QuerySets and Managers work: Suppose you have a model called Book that represents a book in a library. The model has fields such as title, author, and publication_date. You can create a Manager for this model as follows: $ class BookManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(is_published=True) In this Manager, we have overridden the get_queryset method to only return books that are published. These queries will only return the books that have is_published set to True, thanks to the custom Manager we created.

In Django what is field in Model?

In Django, a field in a model refers to a specific attribute or data column that is defined in a Django model class. A model is a Python class that represents a database table, and each field in the model corresponds to a column in the database table. Fields can be defined using various data types, such as CharField, IntegerField, DateField, BooleanField, and many others, which determine the type of data that can be stored in that field. In addition to defining the data type for a field, there are several other options that can be specified in the field definition. Some common options include: - null: Specifies whether the field can be set to null (i.e., no value). By default, this is set to False, which means the field cannot be null. - blank: Specifies whether the field is required to have a value. By default, this is set to False, which means the field is required. - default: Specifies a default value to use if no value is provided for the field. - unique: Specifies whether the field's value must be unique across all rows in the table. - verbose_name: Specifies a human-readable name for the field, which is used in forms and other user-facing interfaces. Fields in Django models can also have relationships with other models, such as ForeignKey, OneToOneField, and ManyToManyField. These relationship fields allow you to create more complex data models that can represent more complex relationships between different types of data. In summary, fields in Django models represent attributes or data columns in a database table. They are defined using various data types and options that determine how the data is stored and validated. Once the fields are defined in the model, Django uses them to create a corresponding database table automatically, along with the appropriate data types for each column. This table is created using Django's built-in Object-Relational Mapping (ORM) framework, which maps Python objects to database tables and provides a simple and intuitive way to interact with the database. Overall, fields in Django models are a key part of creating and interacting with database tables using Django's ORM framework. It's important to note that when defining fields in a Django model, you should follow the principle of Don't Repeat Yourself (DRY). This means that you should avoid duplicating code or logic in your model definitions, and instead use inheritance or reusable components to minimize redundancy. For example, if you have several models that all share a common set of fields (such as created_at and updated_at timestamps), you can define these fields once in a base model and then inherit from that base model in your other models. In summary, fields in Django models are used to define the attributes or data columns of a database table. They are defined using various data types and options, and can have relationships with other models. By following the principle of DRY and using inheritance and reusable components, you can create flexible and maintainable data models for your Django application.

In Django what is Model?

In Django, a model is a Python class that represents a database table. It is a blueprint for creating and interacting with database tables in your Django application. A model defines the fields (i.e., attributes or columns) of a table, as well as any additional methods or metadata. Each attribute of the model corresponds to a column in the database table, and each instance of the model represents a row in the table. Models in Django use an Object-Relational Mapping (ORM) system to communicate with the database, which means you can interact with the database using Python objects and methods, rather than writing raw SQL queries. The Django ORM provides a convenient and powerful way to CRUD (create, read, update, and delete) data from the database. To define a model in Django, you create a subclass of the `django.db.models.Model` class and define the attributes (i.e., fields) of the model as class attributes. Once you have defined a model, you can use Django's database API to interact with the database (to create and save instance to the database). You can also query the database to retrieve instances of a model that match certain criteria, using the `objects` attribute of the model class. Django model is a Python class that represents a database table, and provides a convenient way to interact with the database using Python objects and methods. In addition to defining the fields of the table, a model can also include various methods and metadata, such as: - `__str__()` method: This method is used to define a string representation of the model instance. It is useful for debugging and displaying data in the Django admin interface. - `Meta` class: This class is used to define metadata about the model, such as the ordering of query results, the name of the database table to use, and any unique constraints or indexes. - Custom methods: You can define custom methods on the model class to perform operations on the model data, such as calculating a value based on the fields, or updating related objects. Overall, models are a powerful feature of Django that allow you to define the structure and behavior of your database tables using Python code, and interact with the database in a convenient and efficient way. One important aspect of Django models is that they are database-agnostic, meaning that you can use the same Python code to define and manipulate your models, regardless of the underlying database management system (DBMS) you are using. Django provides a database abstraction layer that allows you to write database-independent queries and model definitions, and it supports several popular DBMSs out of the box, including PostgreSQL, MySQL, SQLite, and Oracle. In addition to the built-in field types provided by Django, you can also define custom field types if you need to represent more complex or specialized data types in your models. You can also define relationships between models, such as one-to-one, one-to-many, and many-to-many relationships, using the various `ForeignKey`, `OneToOneField`, and `ManyToManyField` field types provided by Django. In addition to model inheritance, Django also provides a powerful queryset API that allows you to perform complex queries on your models, using a Pythonic syntax that is similar to SQL. You can filter, annotate, aggregate, and group your queryset results, and chain multiple operations together to create complex queries.

In Django what is django template render?

In Django, a template is a text file that defines the structure of the output that will be displayed to the user. The template can contain placeholders for dynamic content, which are replaced with actual values when the template is rendered. The render() function is a built-in Django function that is used to render a template with a context. The context is a dictionary that contains the variables and their corresponding values, which are used to populate the placeholders in the template. $ return render(request, 'my_template.html', context) Overall, the render() function in Django is used to combine a template and a context to generate an HTML response that can be returned to the user.

In Django what are annotation and aggregation?

In Django, annotation and aggregation are two powerful features of the Object-Relational Mapping (ORM) system that allow developers to perform advanced queries and data manipulations. - Annotation refers to the process of adding extra data to each object in a queryset, typically by performing a calculation or aggregation. This can be done using the annotate() method of a queryset. An example of an annotation would be adding a field to a queryset that calculates the total number of comments on each blog post: $ from django.db.models import Count $ from myapp.models import BlogPost, Comment $ blog_posts = BlogPost.objects.annotate(num_comments=Count('comments')) We're using the Count aggregation function to count the number of related Comment objects for each post. - Aggregation, on the other hand, refers to the process of summarizing data across multiple objects in a queryset, typically by performing a calculation or grouping operation. This can also be done using the aggregate() method of a queryset. An example of an aggregation would be calculating the total number of comments across all blog posts: $ from django.db.models import Sum $ from myapp.models import BlogPost, Comment $ num_comments = Comment.objects.aggregate(total_comments=Sum('post__num_comments'))

In Django what are forms and model.Form?

In Django, forms are a way to display and handle HTML forms in a user-friendly way. Django provides two main ways of creating forms: - Using Django forms module, - Using Model forms. 1) Django Forms. Django forms allow you to define a form in Python and then render it in HTML: $ from django import forms $ class ContactForm(forms.Form): name = forms.CharField(max_length=100) email = forms.EmailField() In this example, we define a form called ContactForm with fields: name, email. The CharField and EmailField are pre-defined form fields in Django. Now that we have defined the form, we can render it in HTML using the as_p method. <form method="post"> {% csrf_token %} {{ form.as_p }} <buttontype="submit">Submit</button> </form> In this HTML code, we use the as_p method to render the form fields as paragraphs. The {% csrf_token %} tag is a security measure to prevent Cross-Site Request Forgery (CSRF) attacks. 2) Model Forms. Model forms in Django are a convenient way to create forms based on models. They automatically generate form fields based on the fields in the model. $ from django import forms $ from .models import Contact $ class ContactForm(forms.ModelForm): class Meta: model = Contact fields = ['name', 'email'] In this example, we create a form called ContactForm based on the Contact model. We specify the fields we want to include in the form using the fields attribute of the Meta class. Now we can render the form in HTML using the same as_p method. This will render a form with fields: name, email, based on the corresponding fields in the Contact model. In addition to the basic form fields such as CharField and EmailField, Django provides many other built-in form fields, including BooleanField, DateField, DateTimeField, ChoiceField, ModelChoiceField, IntegerField, DecimalField, FileField, and ImageField. Furthermore, you can create custom form fields that can validate and clean the user input before it's saved.

What Git origin is?

In Git, "origin" is a shorthand name for the remote repository that a local repository was originally cloned from. When you clone a repository, Git automatically creates an "origin" remote that points to the original repository. You can see a list of your remotes by running the command git remote -v in the terminal. The "origin" remote is typically used to keep your local repository in sync with changes made to the original repository. You can fetch changes from the origin remote using the command git fetch origin, and you can push changes from your local repository to the origin remote using the command git push origin. It's worth noting that you can rename the "origin" remote to something else if you prefer. The name "origin" is just a convention and doesn't have any special meaning to Git.

What Git master is?

In Git, the term "master" refers to the default and primary branch in a Git repository. When a new Git repository is created, it typically has one initial branch named "master". Developers use this branch to develop new features, fix bugs, and make changes to the codebase. The "master" branch is often considered the main branch of a Git repository and is used as a base for creating other branches. It's common practice to create new branches from the "master" branch and make changes there, then merge those changes back into the "master" branch when they're ready. Note that some projects, especially those related to diversity and inclusion in technology, have changed the name of the default branch from "master" to something else, such as "main" or "trunk".

How do you copy an object in Python?

In Python, the assignment statement (= operator) does not copy objects. Instead, it creates a binding between the existing object and the target variable name. To create copies of an object in Python, we need to use the copy module. Moreover, there are two ways of creating copies for the given object using the copymodule: - Shallow Copy is a bit-wise copy of an object. The copied object created has an exact copy of the values in the original object. If either of the values is a reference to other objects, just the reference addresses for the same are copied. - Deep Copy copies all values recursively from source to target object, i.e. it even duplicates the objects referenced by the source object.

Python List Comprehension

List comprehension is an elegant way to define and create lists based on existing lists. It can identify when it receives a string or a tuple and work on it like a list. $ letters = [ letter for letter in 'human' ] -> ['h', 'u', 'm', 'a', 'n'] List comprehensions can utilize conditional statement to modify existing list (or other tuples). $ number_list = [ x for x in range(20) if x % 2 == 0] $ print(number_list) -> [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] Key Points to Remember. - List comprehension is an elegant way to define and create lists based on existing lists. - List comprehension is generally more compact and faster than normal functions and loops for creating list. However, we should avoid writing very long list comprehensions in one line to ensure that code is user-friendly. - Remember, every list comprehension can be rewritten in for loop, but every for loop can't be rewritten in the form of list comprehension.

What are lists and tuples? What is the key difference between the two?

Lists and Tuples are both sequence data types that can store a collection of objects in Python. The objects stored in both sequences can have different data types. Lists are represented with square brackets ['sara', 6, 0.19], while tuples are represented with parantheses ('ansh', 5, 0.97). But what is the real difference between the two? The key difference between the two is that while lists are mutable, tuples on the other hand are immutable objects. This means that lists can be modified, appended or sliced on the go but tuples remain constant and cannot be modified in any manner. You can run the following example on Python IDLE to confirm the difference: my_tuple = ('sara', 6, 5, 0.97) my_list = ['sara', 6, 5, 0.97] print(my_tuple[0]) # output => 'sara' print(my_list[0]) # output => 'sara' my_tuple[0] = 'a' # modifying tuple => throws an error my_list[0] = 'a' # modifying list => list modified print(my_tuple[0]) # output => 'sara' print(my_list[0]) # output => 'a'

What is PEP 8 and why is it important?

PEP stands for Python Enhancement Proposal. A PEP is an official design document providing information to the Python community, or describing a new feature for Python or its processes. PEP 8 is especially important since it documents the style guidelines for Python Code. Apparently contributing to the Python open-source community requires you to follow these style guidelines sincerely and strictly.

What is PYTHONPATH in Python?

PYTHONPATH is an environment variable which you can set to add additional directories where Python will look for modules and packages. This is especially useful in maintaining Python libraries that you do not wish to install in the global default location. PYTHONPATH — эта переменная сообщает интерпретатору путь до файлов модуля, импортированных в программу. Поэтому она должна включать в себя директорию с библиотекой-источником питона и директории с исходным кодом питона. Переменную PYTHONPATH можно назначить самостоятельно, однако обычно ее предустанавливает установщик питона.

Можете назвать 10 встроенных функций питона?

Python Built-in Functions: 1) print( ) function; 2) type( ) function; 3) input( ) function, читает ввод и возвращает строку; 4) abs( ) function; 5) pow( ) function; 6) dir( ) function; 7) sorted( ) function; 8) max( ) function; 9) Функция complex() создает комплексное число; 10) Функция filter() отфильтровывает элементы, для которых заданное условие верно; 11) Функция format() помогает задать формат строки; 12) Функция hash() возвращает хэш-значение объекта; 13) Функция hex() преобразовывает число в шестнадцатеричное число; 14) Функция len() возвращает число, показывающее длину строки; 15) Функция open() открывает файл.

Python Dictionary Methods

Python Dictionary Methods: - clear() - Removes all items from the dictionary - copy() - Returns a shallow copy of the dictionary - fromkeys() - Creates a dictionary from the given sequence - get() - Returns the value for the given key - items() - Return the list with all dictionary keys with values - keys() - Returns a view object that displays a list of all the keys in the dictionary in order of insertion - pop(key) - Returns and removes the element with the given key - popitem() - Returns and removes the random key-value pair from the dictionary - setdefault() - Returns the value of a key if the key is in the dictionary else inserts the key with a value to the dictionary - update() - Updates the dictionary with the elements from another dictionary - values() - Returns a list of all the values available in a given dictionary

What are Dict and List comprehensions?

Python comprehensions, like decorators, are syntactic sugar constructs that help build altered and filtered lists, dictionaries, or sets from a given list, dictionary, or set. Using comprehensions saves a lot of time and code that might be considerably more verbose (containing more lines of code). - Performing mathematical operations on the entire list: my_list = [2, 3, 5, 7, 11] squared_list = [x**2 for x in my_list] # list comprehension # output => [4 , 9 , 25 , 49 , 121] -Performing conditional filtering operations on the entire list. - Combining multiple lists into one. Comprehensions allow for multiple iterators and hence, can be used to combine multiple lists into one. - Flattening a multi-dimensional list. A similar approach of nested iterators can be applied to flatten a multi-dimensional list or work upon its inner elements.

Are access specifiers used in python?

Python does not make use of access specifiers specifically like private, public, protected, etc. However, it does not derive this from any variables. It has the concept of imitating the behaviour of variables by making use of a single (protected) or double underscore (private) as prefixed to the variable names. By default, the variables without prefixed underscores are public.

What are modules and packages in Python?

Python packages and Python modules are two mechanisms that allow for modular programming in Python. Modularizing has several advantages - Simplicity: Working on a single module helps you focus on a relatively small portion of the problem at hand. This makes development easier and less error-prone. Maintainability: Modules are designed to enforce logical boundaries between different problem domains. If they are written in a manner that reduces interdependency, it is less likely that modifications in a module might impact other parts of the program. Reusability: Functions defined in a module can be easily reused by other parts of the application. Scoping: Modules typically define a separate namespace, which helps avoid confusion between identifiers from other parts of the program. Modules, in general, are simply Python files with a .py extension and can have a set of functions, classes, or variables defined and implemented. They can be imported and initialized once using the import statement. If partial functionality is needed, import the requisite classes or functions using "from foo import bar". Packages allow for hierarchial structuring of the module namespace using dot notation. As, modules help avoid clashes between global variable names, in a similar manner, packages help avoid clashes between module names. Creating a package is easy since it makes use of the system's inherent file structure. So just stuff the modules into a folder and there you have it, the folder name as the package name. Importing a module or its contents from this package requires the package name as prefix to the module name joined by a dot.

Introduction to Python

Python was developed by Guido van Rossum and was released first on February 20, 1991. It is one of the most widely-used and loved programming languages and is interpreted in nature thereby providing flexibility of incorporating dynamic semantics. It is also a free and open-source language with very simple and clean syntax. This makes it easy for developers to learn python. Python also supports object-oriented programming and is most commonly used to perform general-purpose programming. Due to its simplistic nature and the ability to achieve multiple functionalities in fewer lines of code, python's popularity is growing tremendously. Python is also used in Machine Learning, Artificial Intelligence, Web Development, Web Scraping, and various other domains due to its ability to support powerful computations using powerful libraries.

Что такое REST (а есть ещё SOAP и XML-RPC)?

REST stands for REpresentational State Transfer and is a software architecture style that defines a pattern for client and server communications over a network. REST provides a set of constraints for software architecture to promote performance, scalability, simplicity, and reliability in the system. REST defines the following architectural constraints: - Stateless: The server won't maintain any state between requests from the client. - Client-server: The client and server must be decoupled from each other, allowing each to develop independently. - Cacheable: The data retrieved from the server should be cacheable either by the client or by the server. - Uniform interface: The server will provide a uniform interface for accessing resources without defining their representation. - Layered system: The client may access the resources on the server indirectly through other layers such as a proxy or load balancer. - Code on demand (optional): The server may transfer code to the client that it can run, such as JavaScript for a single-page application. Note, REST is not a specification but a set of guidelines on how to architect a network-connected software system. REST (REpresentational state transfer) - это стиль архитектуры программного обеспечения для распределенных систем, таких как World Wide Web, который, как правило, используется для построения веб-служб. Термин REST был введен в 2000 году Роем Филдингом, одним из авторов HTTP-протокола. Системы, поддерживающие REST, называются RESTful-системами. В общем случае REST является очень простым интерфейсом управления информацией без использования каких-то дополнительных внутренних прослоек. Каждая единица информации однозначно определяется глобальным идентификатором, таким как URL. Каждая URL в свою очередь имеет строго заданный формат.

What SDLC is?

SDLC stands for Software Development Life Cycle. It is a process used by software development teams to design, develop, test, and maintain high-quality software products. The SDLC model is a framework that outlines the different stages of software development, from the initial concept and planning through to deployment and maintenance. The typical stages of SDLC include requirements gathering, design, coding, testing, deployment, and maintenance. The process involves collaboration between different stakeholders, including developers, testers, project managers, and business analysts, to ensure that the software meets the requirements of the end-users and the organization. By following a structured SDLC approach, software development teams can reduce errors, ensure consistency, and deliver high-quality software products on time and within budget.

SQLite, PostgreSQL, and MySQL are ...

SQLite, PostgreSQL, and MySQL are all database management systems (DBMS) that can be used to store and manage data. - SQLite is a lightweight DBMS that is often used in embedded systems and mobile applications. It is a self-contained, server-less database that does not require a separate server process. SQLite supports SQL and is easy to set up and use. - PostgreSQL, on the other hand, is a powerful open-source DBMS that is known for its robustness, scalability, and reliability. It supports advanced features such as ACID compliance, full-text search, and JSON data types. PostgreSQL also has a large and active community that provides support and contributes to its development. - MySQL is another popular open-source DBMS that is widely used for web applications. It is known for its speed and scalability, and has a simple and easy-to-use interface. MySQL supports SQL, and is often used with the LAMP (Linux, Apache, MySQL, PHP) stack for web development. Overall, the choice between these three DBMS will depend on the specific needs of your project, such as scalability, reliability, features, and ease of use.

What is Scope Resolution in Python?

Sometimes objects within the same scope have the same name but function differently. In such cases, scope resolution comes into play in Python automatically. A few examples of such behavior are: Python modules namely 'math' and 'cmath' have a lot of functions that are common to both of them - log10(), acos(), exp() etc. To resolve this ambiguity, it is necessary to prefix them with their respective module, like math.exp() and cmath.exp(). Consider the code below, an object temp has been initialized to 10 globally and then to 20 on function call. However, the function call didn't change the value of the temp globally. Here, we can observe that Python draws a clear line between global and local variables, treating their namespaces as separate identities. temp = 10 # global-scope variable def func(): temp = 20 # local-scope variable This behavior can be overridden using the global keyword inside the function, as shown in the following example: temp = 10 # global-scope variable def func(): global temp temp = 20 # local-scope variable

Table of Python Set Methods

Table of Python Set Methods: - add(value) - Adds a given element to a set - clear() - Removes all elements from the set - copy() - Returns a shallow copy of the set - difference() - Returns a set that is the difference between two sets - difference_update() - Updates the existing caller set with the difference between two sets - discard(value) - Removes the element from the set (does not throw any error if no element) - frozenset() - Return an immutable frozenset object - intersection() - Returns a set that has the intersection of all sets - intersection_update() - Updates the existing caller set with the intersection of sets - isdisjoint() - Checks whether the sets are disjoint or not - issubset() - Returns True if all elements of a set A are present in another set B - issuperset() - Returns True if all elements of a set A occupies set B - pop() - Returns and removes a random element from the set - remove(value) - Removes the arbitrary element from the set - symmetric_difference() - Returns a set which is the symmetric difference between the two sets - symmetric_difference_update() - Updates the existing caller set with the symmetric difference of sets - union() - Returns a set that has the union of all sets - update(*args) - Adds elements to the set

Types of tests (unit-tests, integration-tests, acceptance-tests etc.).

Tests are used in software development to verify that the code works as expected and to catch any errors or bugs. There are several types of tests that can be used in software development, including: 1) Unit Tests: These are tests that verify the behavior of individual units or components of code in isolation. They are typically automated tests that run quickly and frequently during the development process. Unit tests are focused on testing small, discrete pieces of code and are used to catch errors early in the development process. 2) Integration Tests: These are tests that verify that the individual components of a system work together as expected. Integration tests are used to identify problems that may arise when different parts of a system are combined. They are typically performed after unit tests have been run and are used to validate that the system as a whole is working as expected. 3) Acceptance Tests: These are tests that verify that the software meets the requirements of the stakeholders. Acceptance tests are typically performed by the end-users or business representatives, and are used to ensure that the software meets their expectations and works as intended in the real world. 4) Regression Tests: These are tests that are run after changes have been made to the software to ensure that existing functionality has not been affected. Regression tests are used to catch any unintended consequences of changes to the software. 5) Performance Tests: These are tests that verify that the software performs as expected under various load conditions. Performance tests are used to identify any bottlenecks or scalability issues in the software. 6) Security Tests: These are tests that verify that the software is secure and protected against potential attacks or vulnerabilities. Security tests are used to ensure that the software is safe to use and that sensitive information is protected.

Что такое SOLID.

The SOLID principles are: 1) The Single-Responsibility Principle (SRP) "A class should have one, and only one, reason to change" 2) The Open-Closed Principle (OCP) "Software entities ... should be open for extension but closed for modification" 3) The Liskov Substitution Principle (LSP) "Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it" 4) The Interface Segregation Principle (ISP) "Many client-specific interfaces are better than one general-purpose interface" 5) The Dependency inversion Principle (DIP) "Abstractions should not depend on details. Details should depend on abstraction. High-level modules should not depend on low-level modules. Both should depend on abstractions" These five principles are not a specific ordered list (do this, then that, etc) but a collection of best practices, developed through the decades. They are gathered into an acronym, as a mnemonic vehicle to be remembered, similar to others in computer science, e.g.: DRY: Don't Repeat Yourself; KISS: Keep It Small and Simple; as pieces of accumulated wisdom. A little side note, the acronym was created years after these five principles were set together. Самыми известными и важными считаются принципы проектирования, предложенные Робертом К. Мартином (также известным как Дядя Боб). Дядя Боб представил много разных принципов проектирования, однако самых популярных всего 5, сокращенно их называют SOLID-принципами. В основном они сфокусированы вокруг объектно-ориентированной парадигмы проектирования ПО. Если учитывать эти рекомендации при разработке объектно-ориентированного ПО, код станет не таким сложным, снизится риск поломок, улучшится взаимодействие между различными объектами и код станет более гибким, читаемым и управляемым.

What is pass in Python?

The pass keyword represents a null operation in Python. It is generally used for the purpose of filling up empty blocks of code which may execute during runtime but has yet to be written. Without the pass statement in the following code, we may run into some errors during code execution.

JSON, XML, CSV.

There are three major data formats being used to transmit data from a web server to a client: CSV, XML, and JSON. - CSV stands for "comma separated values". As the name implies, this data format is basically a list of elements separated by commas. Pros - This format is the most compact of all three formats. Generally speaking, CSV formats are about half the size of XML and JSON formats. This is the major advantage of CSV because it can help reduce bandwidth. Cons - This format is the least versatile of all three formats. - XML stands for "eXtensible Markup Language". XML was designed in 1996. It was created to better represent data formats with a hierarchical structure. Pros - This data format fully supports hierarchical data structures and is very appropriate when receiving complex data as a response. It is also very human readable. Most browsers have built in XML readers that allow you to inspect XML files. Since XML was the first standard hierarchical data format, most APIs have built in functionality to automatically convert XML data streams into native data structures like objects. Cons - This data format is about three times as large as CSV. This is because each data element has an associated open and close parameter tag. - JSON stands for (JavaScript Object Notation). It was invented in 2001 and became popularized by Yahoo and Google in 2005 and 2006. It was created as an alternative to XML. Like XML, however, it represents hierarchical data with the use of commas, curly braces and brackets. Pros - This data format supports hierarchical data while being smaller in size than XML. As its name implies, it was also created to more easily parse data into native Javascript objects, making it very useful for web applications. JSON is the best of both worlds with respect to CSV and XML. It's simple and compact like CSV, but supports hierarchical data like XML. Unlike XML, JSON formats are only about twice as large as CSV formats. Cons - This data format has a little bit less support than XML. Since JSON is relatively newer than XML, fewer APIs exist to automatically convert JSON to native data structures. However, this is rapidly changing because newer APIs and plugins are supporting both XML and JSON. JSON has no concept of comments, XML allows you to add comments within a document. YAML was designed for readability and thus allows comments. XML supports complex data types such as charts, images, and other non-primitive data types. JSON supports only strings, numbers, arrays, Boolean, and objects. YAML, on the other hand, supports complex data types such as date and time stamps, sequences, nested and recursive values, and primitive data types. XML is used for data interchange (that is, when a user wants to exchange data between two applications). JSON is better as a serialization format and is used for serving data to application programming interfaces (APIs). YAML is best suited for configuration.

Can you easily check if all characters in the given string is alphanumeric?

This can be easily done by making use of the isalnum() method that returns true in case the string has only alphanumeric characters. $ "abdc1321".isalnum() ->#Output: True $ "xyz@123$".isalnum() ->#Output: False Another way is to use match() method from the re (regex) module: $ import re $ print(bool(re.match('[A-Za-z0-9]+$', 'abdc1321'))) ->#Output: True $ print(bool(re.match('[A-Za-z0-9]+$', 'xyz@123$'))) -># Output: False

How will you check if a class is a child of another class?

This is done by using a method called "issubclass()" provided by python. The method tells us if any class is a child of another class by returning true or false accordingly. For example: $ print(issubclass(Child, Parent)) # True $ print(issubclass(Parent, Child)) # False

Explain how to delete a file in Python?

Use command os.remove(file_name): $ import os $ os.remove("ChangedFile.csv") $ print("File Removed!")

In Django how does view work?

Views are a fundamental concept in Django and provide a flexible way to handle HTTP requests and generate responses. Views are Python functions or classes that receive an HTTP request and return an HTTP response. When a user makes an HTTP request to a Django web application, Django's URL resolver will map the URL to a view. The view function or class will then be called with the request object as its argument, and it will return an HTTP response object that contains the content to be sent back to the user's web browser. $ from django.http import HttpResponse $ def hello(request): return HttpResponse("Hello, world!") In more complex applications, views will often interact with models and templates to generate the content of the HTTP response. Django's template system is often used to generate HTML content based on data from the application's models. Views can also perform other tasks, such as handling form submissions, setting cookies, or redirecting the user to a different URL. The specifics of how a view works will depend on the requirements of the application. Django supports several ways to define views, including function-based views and class-based views. Function-based views are simple Python functions that take a request object as input and return an HTTP response object. Class-based views are Python classes that define methods for handling different HTTP methods (e.g. GET, POST) and can be more flexible and reusable. Once you have defined a view, you need to map it to a URL so that Django knows which view to use for a given request. This is done in the urls.py file of your Django application using the URL dispatcher: $ urlpatterns = [ path('hello/', views.hello, name='hello'), ] Views in Django can also handle form submissions, which is a common use case for web applications. When a user submits a form, the data is sent as an HTTP POST request to the server. In Django, you can define a view that handles the form submission and returns a response. If the form is valid, the function processes the data and redirects the user to a success page. If the form is not valid, the function re-renders the form template with error messages. To handle the form submission, the view uses a Django form class called MyForm. This form class defines the fields of the form and any validation rules that should be applied to the data. Another useful feature of Django views is middleware, which is code that runs before or after a view is executed. Middleware can be used for tasks such as authentication, caching, or logging. Django provides a number of built-in middleware classes, and you can also write your own middleware to customize the behavior of your application. You can also use Django's built-in generic views, which are pre-built views that handle common tasks such as displaying a list of objects or creating a new object. You can also use Django's REST framework to build web APIs that return data in formats such as JSON or XML.

Let list_1 = ['s', 'r', 'a', 's'] and list_2 = ['a', 'a', 'n', 'h'], what is the output of ["".join([i, j]) for i, j in zip(list_1, list_2)]?

['sa', 'ra', 'an', 'sh']

Which function is responsible for pickling?

pickle.dump()

как работает роутинг

view-functions (в файле views.py) в файле urls.py проекта сопоставляются с адресами URL с помощью функции path(), которая располагается в пакете django.urls и которая принимает четыре параметра: $ path(route, view, kwargs=None, name=None) 1. route: представляет шаблон адреса URL, которому должен соответствовать запрос 2. view: функция-представление, которое обрабатывает запрос 3. kwargs: дополнительные аргументы, которые передаются в функцию-представление 4. name: название маршрута re_path. Хотя мы можем успешно применять функцию path() для определения маршрутов, она довольно ограничена по своему действию. Запрошенный путь должен в точности соответствовать указанному в маршруте адресу URL. Например, стоит нам указать слеш в конце: "about/" и django уже не сможет сопоставить путь с запросом. В качестве альтернативы для определения маршрутов мы можем использовать функцию re_path(), которая также располагается в пакете django.urls и имеет тот же набор параметров: $ re_path(route, view, kwargs=None, name=None) Ее преимущесто состоит в том, что она позволяет задать адреса URL с помощью регулярных выражений. Очередность маршрутов Когда запрос приходит к приложению, то система проверяет соответствие запроса маршрутам по мере их определения: вначале сравнивается первый маршрут, если он не подходит, то сравнивается второй и так далее. Поэтому более общие маршруты должны определяться в последнюю очередь, а более конкретные маршруты должны идти в начале.

что такое байткод

Байт-код (байтко́д; англ. bytecode, также иногда p-код, p-code от portable code) — стандартное промежуточное представление, в которое может быть переведена компьютерная программаавтоматическими средствами. По сравнению с исходным кодом, удобным для создания и чтения человеком, байт-код — это компактное представление программы, уже прошедшей синтаксический и семантический анализ. В нём в явном виде закодированы типы, области видимости и другие конструкции. С технической точки зрения байт-код представляет собой машинно-независимый код низкого уровня, генерируемый транслятором из исходного кода. Многие современные языки программирования, особенно интерпретируемые, используют байт-код для облегчения и ускорения работы интерпретатора. Трансляция в байт-код является методом, промежуточным по эффективности между прямой интерпретацией и компиляцией в машинный код. По форме байт-код похож на машинный код, но предназначен для исполнения не реальным процессором, а виртуальной машиной. В качестве виртуальной машины обычно выступает интерпретатор соответствующего языка программирования. Байт-код называется так, потому что длина каждого кода операции традиционно составляет один байт.

Aргументы функции (формат записи).

В Python можно передать переменное количество аргументов двумя способами: - *args для неименованных аргументов; - **kwargs для именованных аргументов. Мы используем *args и **kwargs в качестве аргумента, когда заранее не известно, сколько значений мы хотим передать функции. 1) *args: Если поставить * перед именем, это имя будет принимать не один аргумент, а несколько. Аргументы передаются как кортеж и доступны внутри функции под тем же именем, что и имя параметра, только без *. 2) **kwargs: если поставить ** перед именем, это имя будет принимать любое количество именованных аргументов. Кортеж/словарь из нескольких переданных аргументов будет доступен под этим именем.

Объясните, как в Python осуществляется управление памятью.

В Python объекты и структуры данных (data structures) находятся в закрытой динамически выделяемой области (private heap), которая управляется менеджером памяти Python. Он делегирует часть работы программам распределения ресурсов (allocators), закрепленным за конкретными объектами, и одновременно с этим следит, чтобы они не выходили за пределы динамически выделяемой области. По факту данной областью управляет интерпретатор (interpreter). Пользователь никак не контролирует данный процесс, даже когда манипулирует ссылками объектов на блоки памяти внутри динамической области. Менеджер памяти Python распределяет пространство динамической области среди объектов и другие внутренние буферы по требованию.

что такое MVC

В ПО принято разделять: 1) программную логику, 2) код, который относится к данным, 3) настройки и шаблоны. Таким образом, код становится более структурированным, и его легче развивать, а также сопровождать в дальнейшем. MVC (Model-View-Controller: модель-вид-контроллер) — шаблон архитектуры ПО, который подразумевает разделение программы на 3 слабосвязанных компонента, каждый из которых отвечает за свою сферу деятельности. Django — это фреймворк, использующий шаблон проектирования MVC (Model — доступ к хранилищу данных; View — это интерфейс, с которым взаимодействует пользователь; Controller — некий связывающий объект между model и view.). Но раз как такового слоя Controller в Django нет, то можно использовать в контексте Django аббревиатуру MTV (Model, Template, and View), где для простоты можно считать view контроллером. Выделим в Django приложениях несколько слоев, которые есть в каждом туториале и почти в каждом проекте: 1) front-end/templates 2) serializers/forms 3) views 4) models.

Что такое AsyncIO? Когда его имеет смысл использовать?

В отличие от потоков, в AsyncIO переключение между сопрограммами происходит лишь тогда, когда сопрограмма ожидает завершения внешней операции. AsyncIO подойдет, если приложение большую часть времени тратит на чтение/запись данных, а не их обработку, то есть, например, для работы с веб-сокетами.

Предельно допустимая длина идентификатора в питоне?

В питоне идентификатор может быть любой длины. Помимо этого есть несколько правил для присвоения имен: - первым символом может быть нижнее подчеркивание (_), символы A-Z или a-z; - остальная часть имени может состоять из символов A-Z/a-z/_/0-9; - не забываем, что питон чувствителен к регистру; - в качестве имени нельзя использовать ключевые слова (keywords): and, def, False, import, not, True, as, del, finally, in, or, try, assert, elif, for, is, pass, while, break, else, from, lambda, print, with, class, except, global, None, raise, yield, continue, exec, if, nonlocal, return.

Расскажите, какой в питоне механизм передачи параметров.

В питоне используется передача параметров по ссылке. Если изменить параметр внутри функции, то это отразится на выводе функции. Однако, если использовать в качестве параметров литералы (строки, числа, кортежы), то они передаются по значению (потому что они не изменяемые).

Если мы не поставим двоеточие в конце строки для цикла "do-while", он все равно сработает?

В питоне такой цикл не реализован. (Это вопрос из тех, которые с подвохом, когда упоминают элементы других языков.)

garbage collector

Вам не нужно беспокоиться о сборщике мусора и работе с памятью когда вы пишете код на Python. Как только объекты больше не нужны, Python автоматически освобождает память из под них. Стандартный интерпретатор питона (CPython) использует сразу два алгоритма, подсчет ссылок и generational garbage collector (далее GC), более известный как стандартный модуль gc из Python. Основной процесс сборки мусора выполняется алгоритмом подсчета ссылок, который очень простой и не имеет настроек. Дополнительный алгоритм используется только для поиска и удаления объектов с циклическими ссылками.Не стоит заниматься преждевременной оптимизацией кода под сборщик мусора, на практике серьёзне проблемы со сборкой мусора встречаются довольно редко.

какой путь проходит request и response в django

Веб-приложение или веб-сайт вращаются вокруг цикла запрос-ответ, и приложения Django не являются исключением. Но это не просто двухэтапный процесс. Приложения Django должны пройти различные стадии, чтобы вернуть конечному пользователю результат. 1) WSGI. Веб-сервер - это программа, которая использует HTTP (протокол передачи гипертекста) для предоставления пользователям данных, формирующих веб-страницы, в ответ на их запросы, которые пересылаются HTTP-клиентами их компьютеров. WSGI — это инструмент, созданный для решения основной проблемы: подключения веб-сервера к веб-среде. WSGI имеет две стороны: «серверная» и «прикладная». Для обработки ответа WSGI сервер выполняет приложение и предоставляет функцию обратного вызова на стороне приложения. Приложение обрабатывает запрос и возвращает ответ на сервер, используя предоставленный обратный вызов. По сути, обработчик WSGI действует как привратник-посредник между вашим веб-сервером (Apache, NGINX) и вашим проектом на Django. Между сервером и приложением лежат промежуточные программы (middleware -- промежуточное программном обеспечение) -- серия двунаправленных фильтров: они могут изменять (или замыкать) данные, передаваемые назад и вперед между сетью и вашим приложением Django. Слои приложения Джанго. 1) Request Middlewares - Запрос промежуточного программного обеспечения 2) URL Router (URL Dispatcher) - Маршрутизация URL 3) Views - Отображения 4) Context Processors - Контекстные процессоры 5) Template Renderers - Рендер шаблонов 6) Response Middlewares - Промежуточное программное обеспечение ответа.

Что делает функция zip()?

Возвращает итератор с кортежами. В данном случае она совмещает элементы двух списков и создает из них кортежи. Работает не только со списками.

- Что такое контекстные менеджеры? - Где они применяются? - Как создать свой контекстный менеджер? - Что такое with в питоне?

Данная инструкция обеспечивает исполнение кода очистки после исполнения программы: - для открытия файла: совершить с ним какие-то действия и автоматически закрыть файл после завершения работы; - открывать соединение с DB и автоматически его закрывать. Код очистки исполняется даже в случае, когда появляется исключение (exception). Контекстные менеджеры - это конструкции, которые упрощают работу с тем или иным интерфейсом. Например, работу с файлами или базами данных. Создаются они с помощью оператора with. Для создания собственного класса контекстного менеджера используется библиотека contextlib.

Что такое битовые операторы?

Данные операторы выполняют операции в битовом формате. % ^ >>

Операторы сравнения в питоне.

Данные операторы сравнивают значения между собой. - Оператор "меньше" (<): если значение с левой стороны от оператора меньше, он возвращает True; - Оператор "больше" (>): если значение с левой стороны от оператора больше, он возвращает True; - Оператор "меньше или равно" (<=): если значение с левой стороны от оператора меньше значения с правой стороны или равно ему, он возвращает True; - Оператор "больше или равно" (>=): если значение с левой стороны от оператора больше значения с правой стороны или равно ему, он возвращает True; - Оператор равенства (==): если значения равны, он возвращает True; - Оператор неравенства (!=): если значения не равны, он возвращает True.

Что такое дескриптор?

Дескриптор - атрибут объекта, чье поведение при доступе переопределяется методами __get__, __set__ и __delete__. Если определен хотя бы один из этих методов, объект становится дескриптором. Descriptors are a low-level mechanism that lets you hook into an object's attributes being accessed. Properties are a high-level application of this; that is, @properties are implemented using descriptors. Or, better yet, properties are descriptors that are already provided for you in the standard library. If you need a simple way to return a computed value from an attribute read, or to call a function on an attribute write, use the @property decorator. The descriptor API is more flexible, but less convenient, and arguably "overkill" and non-idiomatic in this situation. It's useful for more advanced use cases, like implementing bound methods, or static and class methods; when you need to know, for example, if the attribute was accessed through the type object, or an instance of the type.

как подключить приложение (app) к проекту (installed_apps)

Для создания нового приложения необходимо в командной строке прописать команды: $ django-admin startproject locallibrary . $ python3 manage.py startapp catalog Оно будет добавлено в ваш проект, после чего вы сможете связать его с вашим сайтом. Для связи приложений используйте файл settings.py. В нем в списке INSTALLED_APPS добавьте новый элемент, который должен иметь одинаковое название с вашим приложением. Теперь веб-сайт знает о существовании этого приложения, но мы до сих пор нигде не вызываем приложение. Поэтому, зайдите в файл urls.py и в нём пропишите новую ссылку, по которой мы будем подключать приложение при переходе по ссылке.

Что нужно сделать, чтобы функция возвращала значение?

Для этого используется ключевое слово return.

Как можно преобразовать целое число (integer) в символ Unicode? И наоборот?

Для этого просто нужна встроенная функция chr(x): $ print(chr(97)) -> 'a' Python ord() function takes string argument of a single Unicode character and return its integer Unicode code point value. $ x = ord('A') -> 65

Лямбда или анонимная функция?Расскажите про выражения лямбда (lambda expressions). Где они могут пригодиться?

Если нужно написать функцию с одним выражением, то можно обойтись без определения (def) и сделать ее анонимной (noname). Выражение лямбда может принимать входные данные и возвращать значения. Лямбда позволяет обойтись без входных данных. В Python анонимные функции создаются при помощи лямбда-выражений. Такие выражения удобно использовать в местах, где ожидается функция с достаточно ограниченной задачей.

Чем Python отличается от Java? Сравнение Python с другим языком.

Если сравнивать Python и Java: - Java быстрее - Python использует отступы, а Java нужны скобки - в Python динамическая типизация, а в Java — статическая - Python — простой и лаконичный, а Java — многословный язык - Python — интерпретируемый язык - Java не зависит от используемой платформы - в Java есть интерфейс JDBC, который улучшает доступ к базам данных.

Что случится, если не обработать ошибку в блоке except?

Если этого не сделать, программа завершится. Затем она отправит трассу исполнения на sys.stderr.

Минусы python?

Какие в питоне есть ограничения: - интерпретируемая природа питона снижает скорость исполнения программы; - его не выгодно использовать для мобильных устройств и браузеров: - будучи языком с динамической типизацией данных, он использует утиную типизацию; в связи с этим появляются ошибки исполнения (runtime errors) (If it looks like a duck, swims like a duck and quacks like a duck, then it probably is a duck). - в нем слабо развиты возможности доступа к базам данных. Поэтому питон не идеальный вариант для приложений с очень большими базами данных; - низкие требования на входе, то есть свои силы в питоне может попробовать каждый; это иногда снижает качество кода; - у питона индивидуально выраженный стиль.

Разница между __new__ и __init__?

Метод __new__ используется, когда нужно управлять процессом создания нового экземпляра, а __init__ - когда контролируется его инициализация. Поэтому new возвращает новый экземпляр класса, а init - ничего.

Как выйти из бесконечного цикла?

Можно нажать комбинацию клавиш Ctrl+C, которая прерывает исполнение.

Что такое строка документации (docstring)?

Она вносится первой строкой в блок, определяющий содержание функции, класса или метода. Содержит описание их цели и способа исполнения. Обозначается тремя одинарными или двойными кавычками с каждой стороны. __doc__

Что такое временная подмена (Monkey Patching)?

Она модифицирует класс или модуль во время выполнения (at runtime), то есть представляет собой динамическую модификацию (dynamic modification). In Python, the term monkey patch refers to dynamic (or run-time) modifications of a class or module. In Python, we can actually change the behavior of code at run-time.

Расскажите про генераторы списков (list comprehension).

Они позволяют создавать списки с помощью одной строки кода. There are a few different ways you can create lists in Python: - the most common type of loop is the for loop; - map() provides an alternative approach that's based in functional programming; - list comprehensions are a third way of making lists. With this elegant approach, you could rewrite the for loop from the first example in just a single line of code: $ squares = [i * i for i in range(10)] -> [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Oператор тождественности (is / is not)

Операторы тождественности. is и is not — операторы тождественности в Python. Они проверяют, находятся ли два значения (или две переменные) по одному адресу в памяти. То, что две переменные равны еще не значит, что они идентичны.

Булевые операторы сравнения

Операции сравнения Простейшие условные выражения представляют операции сравнения, которые сравнивают два значения. Python поддерживает следующие операции сравнения: == - Возвращает True, если оба операнда равны. Иначе возвращает False. != - Возвращает True, если оба операнда НЕ равны. Иначе возвращает False. > (больше чем) - Возвращает True, если первый операнд больше второго. < (меньше чем) - Возвращает True, если первый операнд меньше второго. >= (больше или равно) - Возвращает True, если первый операнд больше или равен второму. <= (меньше или равно) - Возвращает True, если первый операнд меньше или равен второму.

Битовые операторы.

Перечень битовых операторов языка Python в порядке убывания приоритета следующий: ~ - битовый оператор НЕТ (инверсия, наивысший приоритет); <<, >> - операторы сдвига влево или сдвига вправо на заданное количество бит; & - битовый оператор И (AND); ^ - битовое исключающее ИЛИ (XOR); | - битовый оператор ИЛИ (OR). 1) ~ В битовом операторе (операции) ~ инверсия значение любого бита числа изменяется на противоположное. Значение бита 0 устанавливается в 1, а значение 1 устанавливается в 0. То есть, положительное число становится отрицательным со смещением -1. Также отрицательное число становится положительным со смещением на -1. 2) Операторы сдвига влево << и сдвига вправо >> сдвигают каждый бит на одну или несколько позиций влево или вправо. 3) Битовый оператор И (AND) есть бинарным и выполняет побитовое «И» для каждой пары битов операндов, которые размещаются слева и справа от знака оператора &. Каждый целочисленный операнд рассматривается как набор бит, над любым из которых выполняется побитовая операция «И». 4) Битовый оператор ^ (исключающее ИЛИ, XOR) -- выполняет операцию сложения по модулю 2 для любого бита операндов. 5) Битовый оператор ИЛИ (OR) есть бинарным и обозначается символом |. Оператор реализует побитовое логическое сложение по образцу операторов & и ^.

Какие есть режимы обработки файлов в Python?

Предусмотрены следующие режимы: - только чтение - 'r' - только запись - 'w' - чтение-запись - 'rw' - добавление в конце - 'a'. Можно открыть текстовый файл с опцией 't'. Поэтому, чтобы открыть текстовый файл для чтения, можно использовать режим 'rt'. Точно так же для бинарных файлов используется 'b'.

Методы (methods) и конструкторы (constructors) — это одно и то же или нет?

Разница между ними очень тонкая, но важная: - Название конструктора должно соответствовать названию класса, а метод можно называть как угодно. - Конструктор исполняется при создании объекта, а метод исполняется при его вызове. - Конструктор исполняется один раз для каждого объекта, а метод можно вызывать по одному объекту неограниченно. - Конструкторы используются для определения (define) и инициализации не статических переменных. Методы используются для осуществления операций в рамках бизнес-логики.

Singleton на Python.

Синглтон (одиночка) - это паттерн проектирования, цель которого ограничить возможность создания объектов данного класса одним экземпляром. Он обеспечивает глобальность до одного экземпляра и глобальный доступ к созданному объекту. Класс в вашей программе имеет только один экземпляр, доступный всем клиентам. $ class SingletonClass(object): def __new__(cls): if not hasattr(cls, 'instance'): cls.instance = super(SingletonClass, cls).__new__(cls) return cls.instance

Oценка сложности алгоритмов.

Сложность алгоритмов обычно оценивают по времени выполнения или по используемой памяти. В обоих случаях сложность зависит от размеров входных данных: массив из 100 элементов будет обработан быстрее, чем аналогичный из 1000. При этом точное время мало кого интересует: оно зависит от процессора, типа данных, языка программирования и множества других параметров. Важна лишь асимптотическая сложность, т. е. сложность при стремлении размера входных данных к бесконечности. Сложность - один из вариантов: - O(1), например, для определения значения третьего элемента массива не нужно ни запоминать элементы, ни проходить по ним сколько-то раз. Всегда нужно просто дождаться в потоке входных данных третий элемент и это будет результатом, на вычисление которого для любого количества данных нужно одно и то же время. - O(n) — линейная сложность, такой сложностью обладает, например, алгоритм поиска наибольшего элемента в не отсортированном массиве. Нам придётся пройтись по всем n элементам массива, чтобы понять, какой из них максимальный. - O(log(N)) — логарифмическая сложность. Простейший пример — бинарный поиск. Если массив отсортирован, мы можем проверить, есть ли в нём какое-то конкретное значение, методом деления пополам. Проверим средний элемент, если он больше искомого, то отбросим вторую половину массива — там его точно нет. Если же меньше, то наоборот — отбросим начальную половину. И так будем продолжать делить пополам, в итоге проверим log n элементов. - O(N log(N)) - O(N^2) — квадратичная сложность. Такую сложность имеет, например, алгоритм сортировки вставками. В канонической реализации он представляет из себя два вложенных цикла: один, чтобы проходить по всему массиву, а второй, чтобы находить место очередному элементу в уже отсортированной части. Таким образом, количество операций будет зависеть от размера массива как n * n, т. е. n2. *считая, что 𝑁 - размер входных данных.

Операторы присваивания (=, +=, -=, etc.)

Составной оператор += прибавляет к переменной значение выражения справа от оператора присваивания и записывает получившийся результат в эту переменную. a += 5 эквивалентно a = a + 5. Составные операторы присваивания используются для сокращения записи. Таблица с составными операторами присваивания и их эквивалентами a += b -> a = a + b a -= b -> a = a - b a *= b -> a = a * b a /= b -> a = a / b a %= b -> a = a % b a //= b -> a = a // b a **= b -> a = a ** b

В чем заключается проблема циклических зависимостей? Как ее решить?

Циклические зависимости обычно служат признаком некачественного проектирования системы. Временное решение - перенести импорт во вложенные области видимости. В частности, определения функций.

что такое middleware

Что такое Middleware? - Middleware (программное обеспечение промежуточного слоя, связующее, межплатформенное ПО) — это словно мост, связывающий между собой две части программы или системы. - Django Middleware — это промежуточный слой между запросом и ответом, это легкая, низкоуровневая система "плагинов" для глобального изменения входных или выходных данных. Каждый компонент промежуточного слоя отвечает за выполнение определенной функции. Когда пользователь инициирует запрос из вашего приложения, создается обработчик WSGI, выполняющий следующие действия по порядку: 1) Импорт модуля settings.py из корневой директории проекта. 2) Импорт классов исключений Django. 3) Загрузка всех классов связующего ПО, указанных в кортеже MIDDLEWARE из модуля settings.py. 4) Построение списка методов для обработки представлений, исключений, запросов и ответов. 5) Перебор методов запроса (request) по порядку. 6) Выдача прав доступа к запрошенному ресурсу по URL. 7) Обход каждого из методов обработки представлений (views) по порядку. 8) Вызов функции представления или метода dispatch() для представления-класса. 9) Обработка методов выброса исключений, если такие есть. 10) Обход каждого из методов ответа (response) в обратном порядке от обхода методов запроса. 11) Построение возвращаемого значения и выполнение функции обратного вызова (callback). Специальные методы Django Middleware на основе классов: - process_request: когда Django проходит через метод process_request в каждом из Middleware, то с помощью константы ROOT_URLCONF , указанной в settings.py, создаётся объект запроса. После обхода всех связующих ПО по очереди сверху вниз, Django решает, какое из представлений вызвать непосредственно следом за созданием объекта запроса. - process_view(request, view_func, view_args, view_kwargs): рассмотрим формальные параметры, где request — это объект-экземпляр HttpRequest, а view_func — это функция, которая вызывается непосредственно перед представлением. process_response: данный метод составляет ответ, объект-экземпляр класса HttpResponse — конечный результат, получаемый после выполнения process_responseв каждом из связующих ПО. - process_template_response(request, response): среди формальных параметров request — это объект-экземпляр класса HttpRequest, а response — это объект-экземпляр класса TemplateResponse (или эквивалент), ранее возвращенный представлением Django или другим связующим ПО. - process_exception(request, exception): данный метод вызывается, когда представление выбрасывает исключение; обратите внимание на формальные параметры, где request — это объект-экземпляр класса HttpRequest, а exception — это объект-экземпляр класса Exception, выброшенный функцией или методом представления.

virtualenv - виртуальные окружения

Чтобы запускать каждое приложение со своим набором версий библиотек в изолированных средах. Таким образом, виртуальная среда (virtual environment) в языке Python позволяет управлять проектами изолированно друг от друга, то есть: - у каждого проекта могут быть свои зависимости; - зависимости одного проекта не влияют на зависимости другого проекта. Создавать виртуальное окружение в Python можно при помощи различных утилит (venv и virtualenv).

Для чего используется bytes()?

Это встроенная функция питона, которая возвращает неизменяемый байтовый объект.

Расскажите про try, raise и finally.

Это ключевые слова (keywords) для обработки исключений (exception handling). Потенциально рискованный код помещается в блок try, оператор raise (raise statement) используется для прямого вызова ошибки, а в блоке finally находится код, который исполняется в любом случае.

Что такое рекурсия? Может ли рекурсия создавать сложности? Какие преимущества у рекурсии?

Это когда функция вызывает саму себя. При этом она должна иметь базовое условие, чтобы не создать бесконечный цикл! Разумеется: - Приходится чаще вызывать функцию. - Каждый вызов функции сохраняет переменную состояния в программном стеке, то есть растет потребление памяти, что в итоге может стать причиной переполнения памяти. - Вызовы функции отнимают время. Рекурсия помогает: - экономить усилия на выполнение задачи, - сократить объем кода по сравнению с циклами, - легче воспринимать код.

What is the output of the following statement "Hello World"[ : : -1]?

"dlroW olleH"

Django

An open-source Web framework that makes the creation of complex, database-driven Web sites easier by emphasizing the use of components that can be reused.

What is the use of self in Python?

Self is used to represent the instance of the class. With this keyword, you can access the attributes and methods of the class in python. It binds the attributes with the given arguments. self is used in different places and often thought to be a keyword. But unlike in C++, self is not a keyword in Python.

Простейшие алгоритмы.

The word Algorithm means "A set of rules to be followed in calculations or other problem-solving operations " or " A procedure for solving a mathematical problem in a finite number of steps that frequently by recursive operations ". Types of Algorithms: 1. Brute Force Algorithm: It is the simplest approach for a problem. A brute force algorithm is the first approach that comes to finding when we see a problem. 2. Recursive Algorithm: A recursive algorithm is based on recursion. In this case, a problem is broken into several sub-parts and called the same function again and again. 3. Backtracking Algorithm: The backtracking algorithm basically builds the solution by searching among all possible solutions. Using this algorithm, we keep on building the solution following criteria. Whenever a solution fails we trace back to the failure point and build on the next solution and continue this process till we find the solution or all possible solutions are looked after. 4. Searching Algorithm: Searching algorithms are the ones that are used for searching elements or groups of elements from a particular data structure. They can be of different types based on their approach or the data structure in which the element should be found. 5. Sorting Algorithm: Sorting is arranging a group of data in a particular manner according to the requirement. The algorithms which help in performing this function are called sorting algorithms. Generally sorting algorithms are used to sort groups of data in an increasing or decreasing manner. 6. Hashing Algorithm: Hashing algorithms work similarly to the searching algorithm. But they contain an index with a key ID. In hashing, a key is assigned to specific data. 7. Divide and Conquer Algorithm: This algorithm breaks a problem into sub-problems, solves a single sub-problem and merges the solutions together to get the final solution. It consists of the following three steps: - Divide - Solve - Combine 8. Greedy Algorithm: In this type of algorithm the solution is built part by part. The solution of the next part is built based on the immediate benefit of the next part. The one solution giving the most benefit will be chosen as the solution for the next part. 9. Dynamic Programming Algorithm: This algorithm uses the concept of using the already found solution to avoid repetitive calculation of the same part of the problem. It divides the problem into smaller overlapping subproblems and solves them. 10. Randomized Algorithm: In the randomized algorithm we use a random number so it gives immediate benefit. The random number helps in deciding the expected outcome.

Арифметические операции

Арифметические операции: - — вычитание * — умножение ** — возведение в степень / — деление // — целочисленное деление % — остаток от деления

Pick out negative numbers from the given list.

[num for num in list if num<0]

Что такое декораторы с параметрами?

Декоратор — это просто функция, принимающая аргументом другую (декорируемую) функцию, и возвращающая её же, но уже «исправленную». В качестве декоратора может использоваться любое выражение, значение которого — функция, принимающая функцию и возвращающая функцию. Таким образом возможно создавать «декораторы с параметрами» (фактически, фабрики декораторов). $ def repeat(times): def decorate(fn): @wraps(fn) def wrapper(*args, **kwargs): for _ in range(times): result = fn(*args, **kwargs) return result return wrappe return decorate

Как посчитать длину строки (string)?

Для этого вызываем функцию len()

Как можно сделать скрипт Python, исполняемый в Unix?

Для этого должны выполняться два условия: - Файл скрипта должен быть в исполняемом режиме. - Первая строка должен начинаться с решетки (хэша, hash(#)), например: #!/usr/local/bin/python

Как можно отслеживать разные версии кода?

Для этого используется контроль версий (version control). Одним из возможных инструментов контроля является Git.

Как можно преобразовать строку (string) в нижний регистр (lowercase)?

Для этого используется метод lower(). Для преобразования в верхний регистр (uppercase) используется метод upper(). - методы isupper() (все символы в верхнем регистре) и islower() (все символы в нижнем регистре), которые проверяют регистр всех символов имени. - метод istitle(), который проверяет строку на стиль заголовка (все слова должны начинаться с символа в верхнем регистре) - метод capitalize() -- перевести первый символ строки в верхний регистр.

Как можно получить все значения из словаря?

Для этого используется метод values(). values() is an in-built method in Python programming language that returns a view object. The view object contains the values of the dictionary, as a list. If you use the type() method on the return value, you get "dict_values object". It must be cast to obtain the actual list. $ dictionary = {"geeks": "5", "for": "4", "Geeks": "3"} $ print(dictionary.values()) -> dict_values(['5', '4', '3'])

Как пишутся комментарии в питоне?

Для этого используется символ #. Все, что написано на строке после него, считается комментарием и игнорируется. Комментарии используются для объяснения цели написанного кода. """ -- как многострочный комментарий.

Как в питоне узнать, в какой мы сейчас директории? Как узнать текущую директорию в питоне?

Для этого используется функция os.getcwd(). Она импортируется из модуля os. getcwd() (current working directory)method is used to get the current working directory of a process. Somewhere in your script, you can add this function anytime you wish to know or get the directory of an operation currently being carried out.

Какие методы/функции мы используем для определения типа экземпляра (type of instance) и наследования (inheritance)?

Для этого используются type(), isinstance() и issubclass(). 1. type() используется для определени типа объекта. 2. isinstance() принимает два аргумента: значение (value) и тип (type). Если значение относится к соответствующему типу, то возвращается True. Если нет, то возвращается False. $ numbers = [1, 2, 3, 4, 2, 5] $ result = isinstance(numbers, list) $ print(result) -># Output: True 3. issubclass() принимает два класса в качестве аргументов. $ class Vehicles: pass $ class Car(Vehicles): pass $ print(issubclass(Car, Vehicles)) -> True

Как убрать из списка дубликат элемента?

Для этого можно конвертировать список во множество (set()).

Как конвертировать список в строку?

Для этого подойдет метод join(). - join() is an in-built string function in Python used to join elements of the sequence separated by a string separator. This function joins elements of a sequence and makes it a string. $ list_1 = ['g', 'e', 'e', 'k', 's'] $ print("".join(list_1)) ->Output: geeks

Как можно принять результат ввода на клавиатуре?

Если пользователь что-то вводит с помощью клавиатуры, можно использовать функцию input(). В качестве аргумента можно задать данной функции текст запроса на ввод. Результат ввода всегда является строкой.

Как можно конвертировать строку в число?

Если строка содержит только числовые символы, можно использовать функцию int().

"Celery" and "beat" are ...

"Celery" and "beat" are two components of the Celery distributed task queue system. Celery is a Python library that allows you to distribute tasks across multiple worker nodes in a network. It is often used for background processing, where long-running or resource-intensive tasks are offloaded from the main application to be executed in the background. Beat, on the other hand, is a scheduler for Celery that allows you to schedule periodic tasks to be executed at specified intervals. It acts as a sort of "cron job" for Celery, allowing you to automate the execution of tasks on a regular basis. Together, Celery and Beat provide a powerful framework for building distributed applications that can handle a large number of tasks and scale up or down as needed.

Как работает max и min с разными типами данных (строки, числа и прочее).

$ minimum = min('Ivanov', 'Pet', 'Si') -># min = 'Ivanov' $ maximum = max('abcABC') -># max = 'c' (ord("c")=99)

как поменять местами значения двух переменных

$ x = 1 $ y = 2 $ print("x: ", x, end=" --> ") $ print("y: ", y) x: 1 --> y: 2 $ x, y = y, x $ print("x: ", x, end=" --> ") $ print("y: ", y) x: 2 --> y: 1

What is the difference between .py and .pyc files?

- .py files contain the source code of a program. Whereas, .pyc file contains the bytecode of your program. We get bytecode after compilation of .py file (source code). .pyc files are not created for all the files that you run. It is only created for the files that you import. - Before executing a python program python interpreter checks for the compiled files. If the file is present, the virtual machine executes it. If not found, it checks for .py file. If found, compiles it to .pyc file and then python virtual machine executes it. - Having .pyc file saves you the compilation time.

What is the difference between Python Arrays and lists?

- Arrays in python can only contain elements of same data types i.e., data type of array should be homogeneous. It is a thin wrapper around C language arrays and consumes far less memory than lists. (import array) - Lists in python can contain elements of different data types i.e., data type of lists can be heterogeneous. It has the disadvantage of consuming large memory.

What is slicing in Python?

- As the name suggests, 'slicing' is taking parts of. - Syntax for slicing is [start : stop : step] - start is the starting index from where to slice a list or tuple - stop is the ending index or where to sop. - step is the number of steps to jump. - Default value for start is 0, stop is number of items, step is 1. - Slicing can be done on strings, arrays, lists, and tuples.

What is docstring in Python?

- Documentation string or docstring is a multiline string used to document a specific code segment. - The docstring should describe what the function or method does.

Методы, которые изменяют изначальный объект и методы которые возвращают новый.

- sorted() and sort() in Python. - using .sort() you can irrevocably overwrite data

-- Как получить список всех атрибутов объекта? or -- Что такое dir()?

- В простейшем виде -- с помощью функции dir(). Для объектов, класс которых не определил __dir__(), функция попытается определить атрибуты по данным __dict__. Возвращаемый список может включать не все атрибуты, особенно в случаях с переопределенным __getattr__(). Функция help() показывает строку документации и справку для ее аргумента Функция dir() возвращает список, содержащий пространство имен в объекте.

Какие различия есть между методами для списков append() и extend()?

- метод append() добавляет элемент к концу списка, - метод extend() добавляет к концу списка переданный ему итерируемый объект (iterable).

Что такое приглашение интерпретатора (interpreter prompt)?

Когда мы заходим в интерпретатор питона, то видим следующую строку: >>>

Что такое блок?

Когда мы пишем предложение (statement), нам нужно завершить первую строку двоеточием, а под ним написать блок кода, который исполняется в рамках этого предложения. Каждая строка блока пишется с одинаковым отступом.

как одной строкой присвоить значения группе переменных

1) $ x, y = 1, 2 2) $ n, *a = map(int, "1 2 3 4 5".split()) $ print( n ) -> # 1 $ print( a ) -> # [2, 3, 4, 5]

What does *args and **kwargs mean?

1) *args is a special syntax used in the function definition to pass variable-length arguments. "*" means variable length and "args" is the name used by convention. You can use any other. 2) **kwargs is a special syntax used in the function definition to pass variable-length keyworded arguments. Here, also, "kwargs" is used just by convention. You can use any other name. Keyworded argument means a variable that has a name when passed to a function. It is actually a dictionary of the variable names and its value.

How do you access parent members in the child class?

1) By using Parent class name: You can use the name of the parent class to access the attributes as shown in the example below: $ Parent.name = name 2) By using super(): The parent class members can be accessed in child class using the super keyword. $ super(Child, self).__init__(name)

What are the benefits of using Python?

1) Python is a general-purpose programming language that has a simple, easy-to-learn syntax that emphasizes readability and therefore reduces the cost of program maintenance. Moreover, the language is capable of scripting, is completely open-source, and supports third-party packages encouraging modularity and code reuse. 2) Its high-level data structures, combined with dynamic typing and dynamic binding, attract a huge community of developers for Rapid Application Development and deployment. - это интерпретируемый язык - в нем динамическая типизация данных - это объектно-ориентированный язык - он лаконичный и внешне простой - распространяется бесплатно - у него большое сообщество

SOLID: 1) The Single-responsibility principle (SRP)

1) The Single-responsibility principle (SRP). "A class should have one, and only one, reason to change": every component of your code (in general a class, but also a function) should have one and only one responsibility. As a consequence of that, there should be only a reason to change it. - It is easier to localize errors. Any error in execution will point out to a smaller section of your code, accelerating your debug phase. - Any part of the code is reusable in other section of your code. - It is easier to create testing for each function of your code. Принцип единой ответственности гласит, что у каждого класса должна быть только одна «ответственность» и он не должен брать на себя другие обязанности. Роберт К. Мартин объяснял его так: «У класса должна быть лишь одна причина для изменения».

What is Python?

1) high-level 2) interpreted 3) general-purpose programming language. Being a general-purpose language, it can be used to build almost any type of application with the right tools/libraries. Additionally, python supports objects, modules, threads, exception-handling, and automatic memory management which help in modelling real-world problems and building applications to solve these problems.

1) Какая разница между одинарным (_) и двойным (__) подчеркиванием? Почему игнорируются имена-идентификаторы, которые начинаются с символа подчеркивания? 2) Как в Python воплощены public, private, protected методы?

1) В питоне не реализована концепция скрытой переменной (private variable), поэтому принято декларировать скрытые переменные первым символом в виде нижнего подчеркивания. Одинарным подчеркиванием задаются частные переменные, функции, методы и классы. Двойное подчеркивание применяется для искажения имен атрибутов в классе (вызвать такой метод стандартным образом не получится). 2) Этот вопрос напрямую связан с предыдущим. Все компоненты класса Python по умолчанию являются открытыми (public). Для защищенных (protected) методов по соглашению Python добавляется префикс одиночного подчеркивания, для закрытых (private) методов - префикс двойного подчеркивания.

как 1) создавать, 2) фильтровать, 3) сортировать, 4) выбирать конкретный и 5) обновлять записи в базе

1) Чтобы создать запись, вы можете определить экземпляр модели, а затем вызвать метод save (). $ record = MyModelName(my_field_name="Instance #1") $ record.save() 2) Мы можем получить все записи для модели как объект QuerySet, используя objects.all(). QuerySet - это итерируемый объект, он содержит несколько объектов, которые мы можем перебирать. $ all_books = Book.objects.all() Метод filter() Django позволяет отфильтровать возвращаемый QuerySet для соответствия указанному текстовому или числовому полю по конкретным критериям. Например, чтобы отфильтровать книги, содержащие букву «w» в заголовке, а затем подсчитать их, мы могли бы сделать следующее. $ books = Book.objects.filter(title__contains='w') $ n_books=Book.objects.filter(title__contains='w').count() Есть много других типов Field lookups: - icontains (без учёта регистра), - iexact (точное совпадение без учёта регистра), - exact (точное совпадение с учётом регистра ) - in, - gt (больше), gte, lte, lt - startswith, endswith, iendswith и т. д В некоторых случаях нужно будет фильтровать поле, которое определяет отношение «OTM» к другой модели (например, ForeignKey). В этом случае вы можете «индексировать» поля в связанной модели с дополнительными двойными подчёркиваниями. Так, например, чтобы фильтровать книги с определённым жанром, нужно будет указывать имя в поле жанра, как показано ниже: $ books_containing_genre = Book.objects.filter(genre__name__icontains='fiction') - exclude(): получает набор объектов модели, которые НЕ соответствуют условию. Результат метода - объект QuerySet. 3) order_by() $ id= News.objects.order_by('-date_added')[:4] 4) get(): получает один объект модели $ entry = Entry.objects.get(pk=1) 5) Saving changes to objects. To save changes to an object that's already in the database, use save(). $ b5.name = "New name" $ b5.save() This performs an UPDATE SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save(). - Updating a ForeignKey field works exactly the same way as saving a normal field - assign an object of the right type to the field in question. - Updating a ManyToManyField works a little differently - use the add() method on the field to add a record to the relation. To add multiple records to a ManyToManyField in one go, include multiple arguments in the call to add(): $ john = Author.objects.create(name="John") $ paul = Author.objects.create(name="Paul") $ entry.authors.add(john, paul)

функция zip()

1) как функция zip используется обычно Функция zip объединяет элементы различных итерируемых объектов (таких как списки, кортежи или множества) и возвращает итератор. 2) Zip работает с любым количеством итерируемых объектов. Она имеет дело не с двумя, а с любым количеством итерируемых объектов одновременно. То есть неважно, сколько итерируемых объектов передаётся в функцию zip: она в любом случае работает как надо. Кстати, если аргумента нет, функция zip возвращает пустой итератор. 3) работа с неравными по длине аргументами В реальности данные не всегда чистые и полные: иногда приходится иметь дело с неравными по длине итерируемыми объектами. По умолчанию результат функции zip берётся по длине самого короткого итерируемого объекта. В модуле itertools есть функция zip_longest ( + fillvalue='...'). 4) операция распаковывания. Если в предыдущем примере получить сначала record, то как распаковать его на отдельные итерируемые объекты? К сожалению, в Python нет функции распаковывания. Но если воспользоваться хитрыми приёмами звёздочек, распаковывание превращается в очень простую задачу. $ record = [(1, 'Elon Mask'), (2, 'Tim Cook')] $ id, leaders = zip(*record) $ print(id) -># (1, 2) $ print(leaders) -># ('Elon Mask', 'Tim Cook') С помощью звёздочки здесь выполнена операция распаковки: распакованы все четыре кортежа из списка record. 5) Создание и обновление словарей. С помощью функции zip очень просто создавать или обновлять dict, задействуя отдельные списки. Есть два однострочных решения: - использование dict comprehension и zip; - использование функции dict и zip. $ id = [1, 2, 3, 4] $ leaders = ['Elon Mask', 'Tim Cook'] $ leader_dict = {i: name for i, name in zip(id, leaders)} $ leader_dict_2 = dict(zip(id, leaders)) 6) функция zip вместо циклов for. Существует ещё один вариант применения, в котором функция zipзаменяет цикл for, — это работа с последовательными элементами одной коллекции. Например, имеется список из целых чисел и надо вычислить разницу между соседними числами. $ numbers = [12, 3, 7, 15, 8] $ diff = [a-b for a, b in zip(numbers, numbers[1:])] -> [9, -4, -8, 7] 7) сортировка списков. Кроме того, с помощью zip выполняется сортировка двух связанных друг с другом списков: $ list1 = [3,2,4,1, 1] $ list2 = ['three', 'two', 'four', 'one', 'one2'] $ list1, list2 = zip(*sorted(zip(list1, list2))) -> list1(1, 1, 2, 3, 4) -> list2('one', 'one2', 'two', 'three', 'four') 8) применение функции zip в циклах for Типичный сценарий — когда имеешь дело с несколькими итерируемыми объектами одновременно. Функция zip показывает себя во всей красе, если задействовать её вместе с циклами for. Продемонстрируем это на следующем примере: $ products = ["cherry", "strawberry", "banana"] $ price = [2.5, 3, 5] $ cost = [1, 1.5, 2] $ for prod, p, c in zip(products, price, cost): print(f'The profit of a box of {prod} is £{p-c}!') 9) транспонирование матрицы. $ matrix = [[1, 2, 3], [1, 2, 3]] $ matrix_T = [list(i) for i in zip(*matrix)] $ print(matrix_T) -># [[1, 1], [2, 2], [3, 3]]

Расскажите про наследование (inheritance) в Python.

Когда один класс наследует из другого, его называют дочерним/производным/подклассом (child/derived/subclass), который наследует из родительского/базового/супер класса (parent/base/superclass). Он наследует/получает все атрибуты и методы. Наследование позволяет повторно использовать код и облегчает создание и дальнейшую работу приложений (applications). В Python поддерживаются следующие виды наследования: - Единичное наследование (Single Inheritance) — класс наследует из одного базового класса. - Множественное наследование (Multiple Inheritance) — класс наследует из двух или нескольких базовых классов. - Многоуровневое наследование (Multilevel Inheritance) — класс наследует из базового класса, который, в свою очередь, наследует из другого базового класса. - Иерархическое наследование (Hierarchical Inheritance) — два класса или несколько классов наследуют из одного базового класса (single base class). - Гибридное наследование (Hybrid Inheritance) — сочетание двух или нескольких видов наследования.

Зачем нужен secret_key

Критически важные настройки файла settings.py: DEBUG. При развёртывании сайта должен быть установлен в False (DEBUG = False). Тем самым, прекратится вывод важной отладочной информации. SECRET_KEY. Это большое случайное число, применяемое для защиты от CSRF. Важно, чтобы ключ, используемый в продакшене, не указывался в исходном коде, и/или не запрашивался с другого сервера. Django рекомендует размещать значение ключа либо в переменной окружения, или в файле с доступом только на чтение. # Чтение SECRET_KEY из переменной окружения $ import os SECRET_KEY = os.environ['SECRET_KEY']

Логические операции.

Логические операции. Для создания составных условных выражений применяются логические операции. В Python имеются следующие логические операторы: 1) and (логическое умножение) применяется к двум операндам: x and y Сначала оператор and оценивает выражение x, и если оно равно False, то возвращается его значение. Если оно равно True, то оценивается второй операнд - y и возвращается значение y. 2) or (логическое сложение) также применяется к двум операндам: x or y: Сначала оператор or оценивает выражение x, и если оно равно True, то возвращается его значение. Если оно равно False, то оценивается второй операнд - y и возвращается значение y. 3) not (логическое отрицание) Возвращает True, если выражение равно False age = 22 print(not age > 21) # False print(not 0) # True

В каких областях питон имеет преимущество, лучше всего использовать?

Лучше всего питон использовать в следующих областях: - веб-приложения - графические интерфейсы пользователя для настольных ПК - научные и арифметические приложения - разработка ПО - разработка программ обучения - приложения для бизнеса - сетевые приложения - игры - 3D-графика

Для чего в Python используются слоты?

Магический атрибут __slots__ позволяет задать ограниченный набор атрибутов, которыми будет обладать экземпляр класса. За счет такого ограничения можно повысить скорость работы при доступе к атрибутам и сэкономить место в памяти.

Можно ли сказать, что массив (array) NumPy лучше списка (list)?

Массивы NumPy имеют три преимущества перед списками: - Они быстрее - Они потребляют меньше памяти - С ними удобнее работать

Как можно переключить регистр строки?

Можно использовать метод swapcase(), предусмотренный для класса str

Приведите несколько методов, с помощью которых можно реализовать в питоне функционально ориентированное программирование

Несколько методов могут помочь с итерацией по списку (list): - filter() может отфильтровать несколько значений на основе условия. - map() применяет функцию к каждому элементу итерируемого объекта. - reduce() продолжает уменьшать последовательность (sequence) парами, пока не будет достигнуто единичное значение.

Что делает питон объектно-ориентированным?

ООП. Он следует парадигме объектно-ориентированного программирования, которая построена вокруг классов (classes) и их экземпляров (instances). Это позволяет реализовать следующие функции: - сокрытие внутренней структуры данных - абстракция - наследование - полиморфизм (способность выбирать правильный метод в зависимости от типа данных) - ограничение доступа к данным

Можете объяснить жизненный цикл треда?

Общими словами, цикл выглядит так: - сначала создается класс, который подменяет метод исполнения класса в треде, и создаем экземпляр (instance) для этого класса; - вызываем start(), который готовит тред к исполнению; - переводим тред в состояние исполнения; - можно вызвать разные методы, например sleep() и join(), которые переводят тред в режим ожидания; - когда режим ожидания или исполнения прекращается, другие ожидающие треды подготавливаются к исполнению; - после завершения исполнения тред останавливается.

Что такое оператор контроля последовательности (control flow statement)?

Обычно программа в питоне начинает исполнение с первой строки. После нее программа однократно исполняет каждое предложение. Когда будет исполнено последнее предложение, программа прекращается. Также контроль последовательности помогает усложнить обычный порядок исполнения программы.

Расскажите про операторы тождественности.

Операторы is и is not показывают, являются ли два значения идентичными.

Let func = lambda a, b : (a ** b), what is the output of func(float(10), 20) ?

1e+20

SOLID: 2) The Open-closed principle (OCP).

2) The Open-closed principle (OCP). "Software entities ... should be open for extension but closed for modification": you should not need to modify the code you have already written to accommodate new functionality, but simply add what you now need. The result is a very flexible class, that requires minimum time to be maintained. Принцип открытости/закрытости впервые был сформулирован Бернардом Мейером в 1988 году. Роберт К. Мартин говорил о нем так «Наиболее важный принцип открытости/закрытости гласит «Сущности программы (классы, модули, функции и т.п.) должны быть открыты для расширения, но закрыты для изменений».

Паттерны (или шаблоны) проектирования.

Паттерны (или шаблоны) проектирования описывают типичные способы решения часто встречающихся проблем при проектировании программ. - Singleton - Класс, который может иметь только один экземпляр. - Decorator - Класс, расширяющий функциональность другого класса без использования наследования. - Abstract factory - Класс, который представляет собой интерфейс для создания компонентов системы. Книга Design Patterns — Elements of Reusable Object-Oriented Software (1991). В этой книге описаны 23 шаблона проектирования. Также команда авторов этой книги известна общественности под названием «Банда четырёх» (англ. Gang of Four, часто сокращается до GoF). Именно эта книга стала причиной роста популярности шаблонов проектирования.

Можно ли осуществить динамическую загрузку модуля в Python?

При динамической загрузке модули загружаются только когда они становятся нужны. Такой подход — медленный, но он помогает эффективнее использовать память. В Python для этого можно использовать модуль importlib.

Преобразование одного типа данных в другой.

Процесс преобразования значения одного типа данных (целые числа, строки, числа с плавающей точкой и т. д.) в другой называется преобразованием типа. В Python есть два вида преобразования: - Неявное преобразование типов. - Явное приведение типов. Неявное преобразование типов. При неявном преобразовании типов Python автоматически преобразует один тип данных в другой. Этот процесс не требует участия пользователя. Явное приведение типов. В явном преобразовании программист сам заменяет текущий тип данных объекта на требуемый. Для этого используются встроенные функции, такие как int (), float (), str () и т. д., чтобы выполнить явное преобразование типов. Этот тип преобразования также называется приведением типов, поскольку пользователь приводит (изменяет) тип данных объекта. Что надо запомнить: - Преобразование типов — это преобразование объекта из одного типа данных в другой. - Неявное преобразование типов автоматически выполняется интерпретатором Python. - Python не допускает потери данных при неявном преобразовании типов. - Явное преобразование типов также называется приведением типов. Типы данных преобразуются пользователем с помощью встроенных функций. - В явном приведении типов может произойти потеря данных, поскольку мы принудительно приводим объект к определенному типу.

SOLID: 3) The Liskov substitution principle (LSP)

3) The Liskov substitution principle (LSP) "Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it" / "Derived classes must be substitutable for their base classes". If a subclass redefines a function also present in the parent class, a client-user should not be noticing any difference in behaviour, and it is a substitute for the base class. If in a subclass, you redefine a function that is also present in the base class, the two functions ought to have the same behaviour (the user should expect that the same type of result, given the same input). A consequence of LSP is that: the new redefined function in the sub-class should be valid and be possibly used wherever the same function in the parent class is used. Принцип подстановки Лисков гласит: «Объекты в программе должны быть заменяемы экземплярами их подтипов без ущерба корректности работы программы». Если класс Subclass является подтипом класса Super, тогда в программе объекты типа Super должны легко заменяться объектами типа Subclass без необходимости изменения кода.

SOLID: 5) The Dependency Inversion Principle (DIP)

5) The Dependency Inversion Principle (DIP) "Abstractions should not depend on details. Details should depend on abstraction. High-level modules should not depend on low-level modules. Both should depend on abstractions" This is basically what an API is also, used for. With the DIP in mind, we would start from the end of the project, in which our code is independent of what takes in input and it is not susceptible to changes and out of our direct control. Принцип инверсии зависимостей гласит: Модуль высокого уровня не должен зависеть от модулей низкого уровня. И то, и другое должно зависеть от абстракций. Абстракции не должны зависеть от деталей реализации. Детали реализации должны зависеть от абстракций. Если ваш код уже реализует принципы открытости/закрытости и подстановки Лисков, он уже будет неявно согласован с принципом инверсии зависимостей.

What is Scope in Python?

A scope is the region that a variable is recognized. A variable is only available from inside the region it is created. A global and locally scoped versions of the same variable can be created. Local Scope - Is a variable within a function that can only be accessed from within that function. (Ex.) def display_name(): name = "Appleseed" <---- within a function print(name) Global Scope - Is a regular variable outside a function that can be accessed from anywhere at anytime. (Ex.) name = "Johnny" <---- outside a function (Ex.) name = "Johnny" <---- Global Scope def display_name(): name = "Appleseed" <---- Local Scope print(name) ============================= Every object in Python functions within a scope. A scope is a block of code where an object in Python remains relevant. Namespaces uniquely identify all the objects inside a program. However, these namespaces also have a scope defined for them where you could use their objects without any prefix. A few examples of scope created during code execution in Python are as follows: A local scope refers to the local objects available in the current function. A global scope refers to the objects available throughout the code execution since their inception. A module-level scope refers to the global objects of the current module accessible in the program. An outermost scope refers to all the built-in names callable in the program. The objects in this scope are searched last to find the name referenced. Note: Local scope objects can be synced with global scope objects using keywords such as global.

AJAX

AJAX stands for Asynchronous JavaScript and XML. It is a web development technique that allows web pages to be updated asynchronously by exchanging data with a web server in the background, without requiring a full page reload. This makes web applications more responsive and interactive, and improves the overall user experience. The technique involves using JavaScript to send a request to a server and receive a response, which can be in XML, HTML, JSON, or other formats. The data is then dynamically inserted into the web page, without requiring a page refresh. AJAX is widely used in web development, particularly in single-page applications and other web applications that require frequent updates or real-time data. It is also used in web services and APIs to exchange data between servers and clients. There are many popular JavaScript libraries and frameworks, such as jQuery, AngularJS, and React, that provide built-in support for AJAX, making it easier for developers to implement this technique in their web applications.

Agile\Scrum\Kanban is...

Agile, Scrum, and Kanban are all project management methodologies used in software development and other industries. - Agile is an iterative and flexible approach to project management that focuses on delivering value to the customer through continuous improvement and collaboration. It emphasizes adaptability and responsiveness to changing requirements and customer needs. - Scrum is a framework for implementing the Agile methodology that involves a team of developers working together in short sprints to deliver working software. The team is led by a Scrum Master, who facilitates the process and removes any impediments to progress. - Kanban is another Agile methodology that is based on visualizing work and limiting work in progress to increase efficiency and productivity. The Kanban board is a tool used to visualize the work that needs to be done, the work that is in progress, and the work that has been completed. It provides a way to manage the flow of work and ensure that the team is working on the most important tasks first. All of these methodologies prioritize collaboration, flexibility, and continuous improvement, but they differ in their specific processes and techniques for achieving these goals. The choice of methodology depends on the needs of the team and the project requirements.

How is an empty class created in python?

An empty class does not have any members defined in it. It is created by using the pass keyword (the pass command does nothing in python). We can create objects for this class outside the class. For example: $ class EmptyClassDemo: pass $ obj=EmptyClassDemo() $ obj.name="Interviewbit" $ print("Name created= ", obj.name) ->Output: Name created = Interviewbit

What is an Interpreted language?

An interpreted language is a programming language for which most of its implementations execute instructions directly, without previously compiling a program into machine-language instructions.

What is a dynamically typed language?

Before we understand a dynamically typed language, we should learn about what typing is. Typing refers to type-checking in programming languages. In a strongly-typed language, such as Python, "1" + 2 will result in a type error since these languages don't allow for "type-coercion" (implicit conversion of data types). On the other hand, a weakly-typed language, such as Javascript, will simply output "12" as result. Type-checking can be done at two stages - Static - Data Types are checked before execution. Dynamic - Data Types are checked during execution. Python is an interpreted language, executes each statement line by line and thus type-checking is done on the fly, during execution. Hence, Python is a Dynamically Typed Language.

In Django what is bootstrap?

Bootstrap is a popular front-end framework that is used to design and develop responsive websites quickly and easily. Bootstrap provides a set of pre-defined HTML, CSS, and JavaScript templates and components, which can be easily customized to create beautiful and responsive web pages. In Django, Bootstrap can be used to enhance the user interface of your web application by adding pre-built components such as forms, tables, buttons, and navigation menus. - Adding Bootstrap to Django Project: To add Bootstrap to a Django project, you can include Bootstrap CSS and JS files in your base HTML template using CDN (Content Delivery Network) or include it in static files. - Using Bootstrap Forms: Bootstrap provides a set of predefined form styles that can be used in Django forms. You can use Django's built-in form classes or create custom forms and apply Bootstrap form styles to them. - Using Bootstrap Tables: Bootstrap provides a set of predefined table styles that can be used in Django templates. You can use Django's built-in table classes or create custom tables and apply Bootstrap table styles to them. - Using Bootstrap Navigation Menus: Bootstrap provides a set of predefined navigation menu styles that can be used in Django templates. You can use Django's built-in url tags or create custom navigation menus and apply Bootstrap navigation menu styles to them. - Using Bootstrap Modal: Bootstrap provides a set of predefined modal styles that can be used in Django templates. You can use Django's built-in views or create custom modals and apply Bootstrap modal styles to them. These are just a few examples of how you can use Bootstrap in Django. Bootstrap offers a wide range of pre-built components and styles that you can use to enhance the user interface of your Django web application.

index() and find(), the main difference?

Both index() and find() are identical in that they return the index position of the first occurrence of the substring from the main string. The main difference is that Python find() produces -1 as output if it is unable to find the substring, whereas index() throws a ValueError exception.

Code Debt is?

Code debt, also known as technical debt, refers to the eventual cost that a software project incurs when code that is quick and easy to implement is chosen over a more robust, long-term solution. Essentially, code debt is the cost of taking shortcuts in software development to save time or meet a deadline, which can lead to a more difficult and expensive cleanup process in the future. This debt can accumulate over time as the codebase grows and becomes more complex. It can manifest itself as a variety of problems, such as decreased performance, increased maintenance costs, and decreased productivity for developers who have to work with the code. Just like financial debt, code debt can have a significant impact on the long-term success of a software project, and it's essential to address it as early as possible to minimize the negative consequences.

Pекурсия.

Рекурсия — это способ организации циклического процесса путем вызова рекурсивной функции. Рекурсивная функция — это функция, которая содержит код вызова самой себя с целью организации циклического процесса. С помощью рекурсивных функций можно с минимальным объемом кода решать некоторые задачи, обойдя использование (объявление) лишних структур данных. Рекурсию можно рассматривать как альтернативу циклам и итерациям. Для того, чтобы рекурсия работала, нужно решить две задачи. Во-первых, нужно найти базовый случай, то есть тот случай, когда функция завершает свою работу. Во-вторых, нужно разбить нашу проблему, которую мы хотим решить с помощью рекурсии, на множество мелких подпроблем; и если мы сможем найти решение для подпроблемы, значит мы решили всю задачу. $ def fact(x): if x == 1 or x == 0: return 1 return fact(x - 1) * x

time.time() in Python returns?

Current time in milliseconds since midnight, January 1, 1970 GMT (the Unix time).

What are decorators in Python?

Decorators in Python are essentially functions that add functionality to an existing function in Python without changing the structure of the function itself. They are represented the @decorator_name in Python and are called in a bottom-up fashion. The beauty of the decorators lies in the fact that besides adding functionality to the output of the method, they can even accept arguments for functions and can further modify those arguments before passing it to the function itself. The inner nested function, i.e. 'wrapper' function, plays a significant role here. It is implemented to enforce encapsulation and thus, keep itself hidden from the global scope.

>>> def extendList(val, list=[ ]): list.append(val) return list >>> list1 = extendList(10) >>> list2 = extendList(123,[ ]) >>> list3 = extendList('a') >>> list1, list2, list3 Как работает этот код?

Default arguments in Python can work in unexpected ways due to them being created only once when the object is defined. Because of this behaviour, we have to be careful when using mutable default arguments, both as class variables or within methods. A way we can avoid these issues is, for methods, by setting the default value within the method body and for classes by defining the variable within the class initialization dunder method.

Что такое словарь (хештаблица), что может быть ключем словаря?

Dictionaries: Implementing Python Hash Tables. Dictionaries in Python are built using hash tables and the open addressing collision resolution method. Please note that since dictionaries are built on top of hash tables, you can only insert an element if its key is hashable. If the key of your element is not hashable (like a list, for example), the interpreter throws an TypeError exception. An empty Python dictionary with 8 buckets that are just 240 bytes of memory long, so the first element in dictionary hasn't changed the size at all.

Which of the following is untrue for Python namespaces?

False: - Python namespaces have keys as addresses of the objects. True: - Python namespaces are implemented as a dictionary in Python. - Lifecycle of a namespace depends upon the scope of the objects they are mapped to. - Namespaces ensure that object names in a program are unique.

Which statement is false for __init__?

False: - __init__ is called manually on object creation. True: - __init__ is a constructor method in Python. - All classes have a __init__ method associated with them. - __init__ allocates memory for objects.

Why is finalize used?

Finalize method is used for freeing up the unmanaged resources and clean up before the garbage collection method is invoked. This helps in performing memory management tasks.

What are generators in Python?

Generators are functions that return an iterable collection of items, one at a time, in a set manner. Generators, in general, are used to create iterators with a different approach. They employ the use of "yield" keyword rather than 'return' to return a generator object. Let's try and build a generator for fibonacci numbers - ## generate fibonacci numbers upto n def fib(n): p, q = 0, 1 while(p < n): yield p p, q = q, p + q x = fib(10) # create generator object

Standard git commands (add, commit, push, clone, pull etc.).

Here are some of the most commonly used Git commands: - git init: Initializes a new Git repository in the current directory. - git clone [url]: Creates a local copy of a remote repository specified by the URL. - git add [file]: Adds a file or changes to the staging area. - git commit -m "[commit message]": Commits changes to the local repository with a descriptive message. - git status: Displays the status of the repository, including any changes or untracked files. - git push: Pushes committed changes to a remote repository. - git pull: Fetches and merges changes from a remote repository. - git branch: Lists all the branches in the repository. - git checkout [branch]: Switches to a different branch. - git merge [branch]: Merges changes from a specified branch into the current branch. - git log: Displays a log of all the commits made in the repository. These are just a few of the most commonly used Git commands. There are many more commands and options available, depending on your specific use case.

Разница между аутентификацией и авторизацией и идентификацией.

Here is what it looks like (Google, for example): 1) First, the system asks for a login. The user enters one and the system recognizes it as a real login. This is identification. 2a) Google then asks for a password. The user provides it, and if the password entered matches the password stored, then the system agrees that the user indeed seems to be real. This is authentication. 2b) In most cases, Google then asks for a one-time verification code from a text message or authenticator app, too. If the user enters that correctly as well, the system will finally agree that he or she is the real owner of the account. This is two-factor authentication. 3) Finally, the system gives the user the right to read messages in their inbox and such. This is authorization.

In Django what is django html, css, js?

In Django, HTML, CSS, and JS are used to create dynamic web pages and user interfaces. - HTML (HyperText Markup Language): is used to create the structure and content of a web page. Django uses HTML templates to generate dynamic HTML pages based on data from the server. Django uses the {{ }} syntax to insert dynamic data into the HTML page. The {% %} syntax is used to define control structures like loops and conditionals. - CSS (Cascading Style Sheets): is used to style and layout the content of a web page. In Django, CSS is typically stored in static files that are served directly to the client. CSS file defines styles, for example, for the <ul>, <li>, and <a> elements. - JavaScript: is used to add interactivity and dynamic behavior to a web page. In Django, JavaScript is typically included in the HTML page using script tags or loaded from static files.

Formatting strings in Python (.format, f, %).

In Python, there are several ways to format strings. Here are the three most common methods: 1) Using the .format() method: The .format() method allows you to insert values into a string by using placeholders that are replaced with values passed as arguments. Placeholders are curly braces {}. $ name = "John" $ age = 25 $ print("My name is {} and I am {} years old.".format(name, age)) -> My name is John and I am 25 years old. 2) Using f-strings (formatted string literals): f-strings were introduced in Python 3.6 and provide a concise way to embed expressions inside string literals, using curly braces {}. $ print(f"My name is {name} and I am {age} years old.") 3) Using the % operator: The % operator allows you to format strings using placeholders that are replaced with values passed as a tuple. Placeholders start with % and have a type specifier to define the type of value to be formatted. $ print("My name is %s and I am %d years old." % (name, age)) Note that %s is used to format strings, while %d is used to format integers. You can use other type specifiers to format other data types.

What is main function in python? How do you invoke it?

In the world of programming languages, the main is considered as an entry point of execution for a program. But in python, it is known that the interpreter serially interprets the file line-by-line. This means that python does not provide main() function explicitly. But this doesn't mean that we cannot simulate the execution of main. This can be done by defining user-defined main() function and by using the __name__ property of python file. This __name__ variable is a special built-in variable that points to the name of the current module. This can be done: $ def main(): print("Hi Interviewbit!") $ if __name__=="__main__": main()

How does inheritance work in python? Explain it with an example.

Inheritance gives the power to a class to access all attributes and methods of another class. It aids in code reusability and helps the developer to maintain applications without redundant code. The class inheriting from another class is a child class or also called a derived class. The class from which a child class derives the members are called parent class or superclass. Python supports different kinds of inheritance, they are: 1) Single Inheritance: Child class derives members of one parent class. 2) Multi-level Inheritance: The members of the parent class, A, are inherited by child class which is then inherited by another child class, B. The features of the base class and the derived class are further inherited into the new derived class, C. Here, A is the grandfather class of class C. 3) Multiple Inheritance: This is achieved when one child class derives members from more than one parent class. All features of parent classes are inherited in the child class. 4) Hierarchical Inheritance: When a parent class is derived by more than one child class, it is called hierarchical inheritance.

Define PYTHONPATH.

It is an environment variable used for incorporating additional directories during the import of a module or a package. PYTHONPATH is used for checking if the imported packages or modules are available in the existing directories. Not just that, the interpreter uses this environment variable to identify which module needs to be loaded.

What are lambda functions?

Lambda functions are generally inline, anonymous functions represented by a single expression. They are used for creating function objects during runtime. They can accept any number of parameters. They are usually used where functions are required only for a short period. $ mul_func = lambda x,y : x*y $ print(mul_func(6, 4)) -># Output: 24

What is lambda in Python? Why is it used?

Lambda is an anonymous function in Python, that can accept any number of arguments, but can only have a single expression. It is generally used in situations requiring an anonymous function for a short time period. Lambda functions can be used in either of the two ways: - Assigning lambda functions to a variable - Wrapping lambda functions inside another function

Python List Methods

List Methods: - append() - Used for appending and adding elements to the end of the List. - copy() - It returns a shallow copy of a list - clear() - This method is used for removing all items from the list. - count() - This methods count the elements - extend() - Adds each element of the iterable to the end of the List - index() - Returns the lowest index where the element appears. - insert(index, element) - Inserts a given element at a given index in a list. - pop(index) - Removes and returns the last value from the List or the given index value. - remove(value) - Removes a given object from the List. - reverse() - Reverses objects of the List in place. - sort() - Sort a List in ascending, descending, or user-defined order - min() - Calculates minimum of all the elements of List - max() - Calculates maximum of all the elements of List - len(list_name) - Calculates the total length of the List - sum()

Что такое MRO?

MRO - сокращение от "Method Resolution Order". MRO is a concept used in inheritance. It is the order in which a method is searched for in a classes hierarchy and is especially useful in Python because Python supports multiple inheritance. In Python, the MRO is: - from bottom to top and - left to right. This means that, first, the method is searched in the class of the object. If it's not found, it is searched in the immediate super class. In the case of multiple super classes, it is searched left to right, in the order by which was declared by the developer.

How is memory managed in Python?

Memory management in Python is handled by the Python Memory Manager. The memory allocated by the manager is in form of a private heap space dedicated to Python. All Python objects are stored in this heap and being private, it is inaccessible to the programmer. Though, python does provide some core API functions to work upon the private heap space. Additionally, Python has an in-built garbage collection to recycle the unused memory for the private heap space.

Что такое метаклассы в Python?

Metaclasses are the 'stuff' that creates classes. You define classes in order to create objects, right? But we learned that Python classes are objects. Well, metaclasses are what create these objects. They are the classes' classes. It's because the function type is in fact a metaclass. type is the metaclass Python uses to create all classes behind the scenes. Now you wonder "why the heck is it written in lowercase, and not Type?" Well, I guess it's a matter of consistency with str, the class that creates strings objects, and int the class that creates integer objects. type is just the class that creates class objects.

What are negative indexes and why are they used?

Negative indexes are the indexes from the end of the list or tuple or string. Arr[-1] means the last element of array Arr[]

Define PIP.

PIP stands for Python Installer Package. As the name indicates, it is used for installing different python modules. It is a command-line tool providing a seamless interface for installing different python modules. It searches over the internet for the package and installs them into the working directory without the need for any interaction with the user. $ pip install <package_name>

What is pickling and unpickling?

Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.

What are the differences between pickling and unpickling?

Pickling is the conversion of python objects to binary form. Whereas, unpickling is the conversion of binary form data to python objects. The pickled objects are used for storing in disks or external memory locations. Unpickled objects are used for getting the data back as python objects upon which processing can be done in python. Python provides a pickle module for achieving this. Pickling uses the pickle.dump() method to dump python objects into disks. Unpickling uses the pickle.load() method to get back the data as python objects.

Python Tuple Methods

Python Tuple Methods Python Tuples is an immutable collection of that are more like lists. - сount() -- The count() method of Tuple returns the number of times the given element appears in the tuple. tuple.count(element) - index() -- The Index() method returns the first occurrence of the given element from the tuple. tuple.index(element, start, end)

What are some of the most commonly used built-in modules in Python?

Python modules are the files having python code which can be functions, variables or classes. These go by .py extension. The most commonly available built-in modules are: - os - math - sys - random - re - datetime - JSON

How can you generate random numbers?

Python provides a module called random using which we can generate random numbers. We have to import a random module and call the random() method. The random() method generates float values lying between 0 and 1 randomly. $ import random $ print(random.random()) To generate customised random numbers between specified ranges, we can use the randrange() method. - Syntax: randrange(beginning, end, step) $ import random $ print(random.randrange(5,100,2))

Redis and RabbitMQ are ...

Redis and RabbitMQ are two different technologies used for handling data and messages in software applications. Redis is an in-memory data structure store that can be used as a database, cache, and message broker. It supports various data structures such as strings, hashes, lists, sets, and sorted sets. Redis is often used to store and manage data in real-time applications, such as chat systems, social networks, and gaming platforms. Redis is also known for its high-performance and scalability. - On the other hand, RabbitMQ is a message broker that enables different applications to communicate with each other through messages. It implements the Advanced Message Queuing Protocol (AMQP) and provides features like message routing, delivery acknowledgments, and message retries. RabbitMQ is often used in distributed systems and microservices architectures to decouple the components of an application and improve its scalability. In summary, Redis is more focused on data storage and management, while RabbitMQ is more focused on message queuing and delivery. However, both technologies can be used together to create highly scalable and performant applications.

Differentiate between deep and shallow copies.

Shallow copy does the task of creating new objects storing references of original elements. This does not undergo recursion to create copies of nested objects. It just copies the reference details of nested objects. Deep copy creates an independent and new copy of an object and even copies all the nested objects of the original element recursively.

TRELO, JIRA are...

TRELO and JIRA are both project management tools used by teams to organize and track their work. - Trello is a visual collaboration tool that uses cards, lists, and boards to help teams organize and prioritize their tasks. Each card represents a task or project, and teams can add notes, comments, and attachments to the cards to keep everyone on the same page. - JIRA, on the other hand, is a powerful issue and project tracking software that allows teams to track tasks, bugs, and issues throughout the development cycle. It offers various features like customizable workflows, agile project management, and integration with other tools to enhance the team's productivity. Both tools have their strengths and weaknesses, and the choice between them depends on the team's specific needs and preferences.

Python String Methods

Table of Python String Methods: - capitalize() - Converts the first character of the string to a capital (uppercase) letter - casefold() - Implements caseless string matching - center() - Pad the string with the specified character. - count() - Returns the number of occurrences of a substring in the string. - encode() - Encodes strings with the specified encoded scheme - endswith() - Returns "True" if a string ends with the given suffix. - expandtabs() - Specifies the amount of space to be substituted with the "\t" symbol in the string - find() - Returns the lowest index of the substring if it is found - format() - Formats the string for printing it to console - format_map() - Formats specified values in a string using a dictionary - index() - Returns the position of the first occurrence of a substring in a string - isalnum() - Checks whether all the characters in a given string is alphanumeric or not - isalpha() - Returns "True" if all characters in the string are alphabets - isdecimal() - Returns true if all characters in a string are decimal - isdigit() - Returns "True" if all characters in the string are digits - isidentifier() - Check whether a string is a valid identifier or not - islower() - Checks if all characters in the string are lowercase - isnumeric() - Returns "True" if all characters in the string are numeric characters - isprintable() - Returns "True" if all characters in the string are printable or the string is empty - isspace() - Returns "True" if all characters in the string are whitespace characters - istitle() - Returns "True" if the string is a title cased string - isupper() - Checks if all characters in the string are uppercase - join() - Returns a concatenated String - ljust() - Left aligns the string according to the width specified - lower() - Converts all uppercase characters in a string into lowercase - lstrip() - Returns the string with leading characters removed - maketrans() - Returns a translation table - partition() - Splits the string at the first occurrence of the separator - replace() - Replaces all occurrences of a substring with another substring - rfind() - Returns the highest index of the substring - rindex() - Returns the highest index of the substring inside the string - rjust() - Right aligns the string according to the width specified - rpartition() - Split the given string into three parts - rsplit() - Split the string from the right by the specified separator - rstrip() - Removes trailing characters - splitlines() - Split the lines at line boundaries - startswith() - Returns "True" if a string starts with the given prefix - strip() - Returns the string without both leading and trailing characters - swapcase() - Converts all uppercase characters to lowercase and vice versa - title() - Convert string to title case - translate() - Modify string according to given translation mappings - upper() - Converts all lowercase characters in a string into uppercase zfill() - Returns a copy of the string with '0' characters padded to the left side of the string

Чем отличаются и как используются декораторы @classmethod и @staticmethod?

The class method in Python is a method, which is bound to the class but not the object of that class. The static methods are also same but also not bound to the class. Class Method: - The class method takes cls (class) as first argument. - Class method can access and modify the class state. - The class method takes the class as parameter to know about the state of that class. - @classmethod decorator is used here. Static Method: - The static method does not take any specific parameter. - Static Method cannot access or modify the class state. - Static methods do not know about class state. These methods are used to do some utility tasks by taking some parameters. - @staticmethod decorator is used here.

В чём состоит отличие процессов от потоков?

The difference is that threads run in the same memory space, while processes have separate memory. This makes it a bit harder to share objects between processes with multiprocessing. Since threads use the same memory, precautions have to be taken or two threads will write to the same memory at the same time. This is what the global interpreter lock is for. Spawning processes is a bit slower than spawning threads.

Write a program for counting the number of every character of a given text file.

The idea is to use collections and pprint module: $ import collections $ import pprint $ with open("sample_file.txt", 'r') as data: count_data = collections.Counter(data.read().upper()) count_value = pprint.pformat(count_data) print(count_value)

Differentiate between a package and a module in python.

The module is a single python file. A module can import other modules (other python files) as objects. Whereas, a package is the folder/directory where different sub-packages and the modules reside. A python module is created by saving a file with the extension of .py. This file will have classes and functions that are reusable in the code as well as across modules. A python package is created by following the below steps: 1) Create a directory and give a valid name that represents its operation. 2) Place modules of one kind in this directory. 3) Create __init__.py file in this directory. This lets python know the directory we created is a package. The contents of this package can be imported across different modules in other packages to reuse the functionality.

Differentiate between new and override modifiers.

The new modifier is used to instruct the compiler to use the new implementation and not the base class function. The Override modifier is useful for overriding a base class function inside the child class.

Python Data Types

There are different types of data types in Python. Some built-in Python data types are: 1. Numeric data types: int, float, complex 2. String data types: str 3. Sequence types: list, tuple, range 4. Binary types: bytes, bytearray, memoryview 5. Mapping data type: dict 6. Boolean type: bool 7. Set data types: set, frozenset

What are the common built-in data types in Python?

There are several built-in data types in Python. Python provides type() and isinstance() functions to check the type of these variables. These data types can be grouped into the following categories: 1) None Type: None keyword represents the null values in Python. Boolean equality operation can be performed using these NoneType objects. 2) Numeric Types: - integers (additionally, booleans are a sub-type of integers), - floating-point numbers, - complex numbers. (integer literals including hex, octal and binary numbers, float literals containing decimal values and/or exponent signs as floating-point numbers (A + Bj) 3) Sequence Types: - lists, - tuples, - range objects. Sequence types have the "in" and "not in" operators. 4) Additional types for processing: 1. Binary data such as bytearray bytes memoryview , 2. Text strings such as str. 5) Mapping Types: A mapping object can map hashable values to random objects in Python. Mappings objects are mutable and there is currently only one standard mapping type, the dictionary (comma-separated list of key: value pairs). 6) Set Types: - set - frozenset. set type is mutable and supports methods like add() and remove(). frozenset type is immutable and can't be modified after creation. Note: set is mutable and thus cannot be used as key for a dictionary. On the other hand, frozenset is immutable and thus, hashable, and can be used as a dictionary key or as an element of another set. 7) Modules: Module is an additional built-in type supported by the Python Interpreter. It supports one special operation, i.e., attribute access: mymod.myobj, where mymod is a module and myobj references a name defined in m's symbol table. The module's symbol table resides in a very special attribute of the module __dict__, but direct assignment to this module is neither possible nor recommended. 8) Callable Types: Callable types are the types to which function call can be applied. They can be user-defined functions, instance methods, generator functions, and some other built-in functions, methods and classes.

Изменяемые и неизменяемые типы данных (mutable / immutable)

There are two kinds of objects in Python: Mutable objects and Immutable objects. The value of a mutable object can be modified in place after it's creation, while the value of an immutable object cannot be changed. - Immutable Object: int, float, complex, string, tuple, bool. - Mutable Object: list, dict, set, byte array, user-defined classes.

In Git how to create a branch?

To create a new branch in Git, you can use the "git branch" command followed by the name of the new branch you want to create. $ git branch new-feature This will create a new branch called "new-feature" based on the current branch you are on. If you want to switch to the new branch, you can use the "git checkout" command: $ git checkout new-feature Alternatively, you can create and switch to the new branch in one step by using the git checkout command $ git checkout -b new-feature This command will create a new branch called "new-feature" and switch to it in one step. Once you have created a new branch, you can start making changes and committing them to the new branch. This allows you to work on a new feature or bug fix without affecting the main branch (usually called "master" or "main") until you are ready to merge your changes back into the main branch.

In Git how to merge a branch? What different kind of merges are in Git?

To merge a branch in Git, you can use the git merge command. First, ensure that you are on the branch that you want to merge another branch into. You can use the command git checkout to switch to the desired branch. Next, use the "git merge" command and specify the branch that you want to merge into the current branch. Git will attempt to automatically merge the changes from the specified branch into the current branch. If there are any conflicts, Git will prompt you to resolve them manually. Once the merge is complete, you can commit the changes with git commit to finalize the merge. In Git, there are several different kinds of merges you can perform: - Fast-forward merge: This is the simplest type of merge, where the changes from the merged branch can be applied directly to the current branch without any conflicts. - Recursive merge: This is the default merge type in Git. If there are conflicts between the changes in the merged branch and the current branch, Git will attempt to automatically merge the changes by creating a new merge commit. - Squash merge: This type of merge combines the changes from the merged branch into a single commit, rather than creating a merge commit. This can be useful for keeping the commit history clean and concise. - Octopus merge: This is a merge that involves three or more branches. Git will attempt to merge all of the branches into a single commit. You can specify the type of merge to use by passing additional options to the git merge command. For example, to perform a squash merge, you can use the --squash option: $ git merge --squash feature-branch - Rebase merge: This is a way to integrate changes from one branch into another by rewinding the changes in the current branch to the common ancestor with the branch being merged and then replaying the changes from the branch being merged on top of it. This can help to keep the commit history linear and easier to understand. - Merge commit: This is a type of merge that creates a new commit to record the fact that the branches were merged. This type of merge is used when there are conflicts between the changes in the merged branch and the current branch. - Three-way merge: This type of merge is used when there are changes in both the current branch and the branch being merged, and Git needs to reconcile the differences between the two branches. Git uses a three-way merge algorithm to compare the changes in the two branches and the common ancestor, and create a new merge commit with the reconciled changes. It's important to choose the right type of merge for your situation, based on the complexity of the changes being merged and your goals for the commit history. It's also important to resolve any conflicts that arise during the merge process to ensure that the merged code works correctly. Additionally, it's important to note that when merging branches, it's always a good practice to ensure that the branch being merged is up-to-date with the latest changes in the base branch. To do this, you can use the "git fetch" command to download the latest changes from the remote repository, and then use the "git rebase" command to apply those changes to the branch being merged. Here's an example of how you could update a feature branch before merging it into the main branch: 1) First, ensure that you are on the feature branch that you want to update. 2) Use the "git fetch" command to download the latest changes from the remote repository. 3) Use the "git rebase" command to apply the latest changes to the feature branch. This will replay all of the commits in the feature branch on top of the latest changes in the base branch, ensuring that the feature branch is up-to-date. 4) Once the feature branch is up-to-date, you can use the "git merge" command to merge the feature branch into the main branch, as described earlier. By keeping your branches up-to-date and using the right type of merge for your situation, you can ensure that your codebase is well-organized, easy to understand, and works correctly.

Write a Program to match a string that has the letter 'a' followed by 4 to 8 'b's.

We can use the re module of python to perform regex pattern comparison here. $ import re $ def match_text(txt_data): pattern = 'ab{4,8}' if re.search(pattern, txt_data): return 'Match found' else: return('Match not found') $ print(match_text("abc")) -># prints Match not found $ print(match_text("aabbbbbc")) -># prints Match found

Write a Program to convert date from yyyy-mm-dd format to dd-mm-yyyy format.

We can use the re module to convert the date string: $ import re $ def transform_date_format(date): return re.sub(r'(\d{4})-(\d{1,2})-(\d{1,2})', '\\3-\\2-\\1', date) $ date_input = "2021-08-01" $ print(transform_date_format(date_input)) You can also use the datetime module: $ from datetime import datetime $ new_date = datetime.strptime("2021-08-01", "%Y-%m-%d").strftime("%d:%m:%Y") $ print(new_data)

Are there any tools for identifying bugs and performing static analysis in python?

Yes, there are tools like PyChecker and Pylint which are used as static analysis and linting tools respectively. PyChecker helps find bugs in python source code files and raises alerts for code issues and their complexity. Pylint checks for the module's coding standards and supports different plugins to enable custom features to meet this requirement.

WAP (Write a program) which takes a sequence of numbers and check if all numbers are unique.

You can do this by converting the list to set by using set() method and comparing the length of this set with the length of the original list. If found equal, return True. $ def check_distinct(data_list): if len(data_list) == len(set(data_list)): return True else: return False $ print(check_distinct([1,6,5,8])) -># Prints True $ print(check_distinct([2,2,5,5,7,8])) -># Prints False

Как в питоне работает трёхместный (тернарный) оператор?

[on_true] if [expression] else [on_false] [если верно] if [выражение] else [если неверно] То есть, когда выражение верное (True), то выполняется код [если верно]. В остальных случаях исполняется код [если неверно]. Например: $ a, b = 10, 20 $ min = a if a < b else b $ print(min) -> 10

What is __init__?

__init__ is a method or constructor in Python. This method is automatically called to allocate memory when a new object/ instance of a class is created. All classes have the __init__ method.

Можно ли сказать, что del и remove() — это одно и то же? Что это такое, в целом?

del и remove() — это методы для списков, они нужны для удаления элементов: - del позволяет удалять элементы под конкретным индексом, - remove() позволяет удалять элементы на основе их значения.

Как проводится отладка программ на Python?

В Python есть модуль pdb. Он позволяет пошагово провести отладку программы. В версии >=3.7 появилась функция breakpoint(), которая также облегчает дебаггинг.

Магические методы?

Так называют специальные методы, обрамленные двумя подчеркиваниями. Магические методы представляют простой способ заставить объекты вести себя аналогично встроенным типам. Это, в частности, позволяет стандартизировать поведение базовых операторов с экземплярами класса.

Если строка (string) начинается с пробела, как его убрать?

Такой пробел можно убрать с помощью метода lstrip(). Если мы захотим убрать пробел из хвоста, то воспользуемся функцией rstrip().

Как исполняется код в питоне?

Файлы питона сначала компилируются в байткод, который затем исполняется.

Что за функция enumerate() в Python?

Функция enumerate() осуществляет итерацию вдоль последовательности (sequence), извлекает индекс и его значение. Enumerate() method adds a counter to an iterable and returns it in a form of enumerating object. This enumerated object can then be used directly for loops or converted into a list of tuples using the list() function. $ l_1 = ["eat", "sleep", "repeat"] $ print (list(enumerate(l1))) -> Output: [(0, 'eat'), (1, 'sleep'), (2, 'repeat')]

Расскажите про функции join() и split() в Python.

Функция join() позволяет соединять символы строки (string), чередуя с указанным символом. Функция split() позволяет разделить строку, чередуя символы с указанным символом.

Что делает функция map()?

Функция map() возвращает итератор, который применяет функцию, переданную ей в первом аргументе, ко всем элементам итерируемого объекта (iterable), переданного ей во втором аргументе. map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.) $ numbers = (1, 2, 3, 4) $ result = map(lambda x: x + x, numbers) $ print(list(result)) -> [2, 4, 6, 8]

Когда в блоке try-except исполняется элемент else?

В блоке if-else элемент else исполняется в случае, если условие в операторе if (if statement) является неверным (False). А вот в блоке try-except элемент else исполняется только в случае, если элемент try не выдает исключение. - Try: This block will test the excepted error to occur - Except: Here you can handle the error - Else: If there is no exception then this block will be executed - Finally: Finally block always gets executed either exception is generated or not

Как работать с числами, которые не входят в десятичную систему счисления?

В питоне можно вводить бинарные, восьмеричные и шестнадцатеричные числа. - Бинарные. Это числа, составленные из 0 и 1. Для ввода в бинарном формате, используется префикс 0b или 0B. Число можно преобразовать в бинарный формат с помощью функции bin(). - Восьмеричные числа могут состоять из цифр от 0 до 7, также используется префикс 0o или 0O. - Шестнадцатеричные числа могут состоять из цифр от 0 до 15, также используется префикс 0x или 0X.

Что такое id или id()?

Возвращает идентификатор переданного объекта, уникальный на время его существования.

Что такое операторы присвоения в питоне?

Все арифметические операторы можно комбинировать с символом присвоения =: *= += и т.д.

Расскажите про логические операторы в питоне.

Всего их три: and, or, not. Как логический оператор можно использовать XOR ^

Как получить список из всех ключей словаря (dictionary keys)?

Данная задача выполняется с помощью функции keys(). The keys() method in Python Dictionary, returns a view object that displays a list of all the keys in the dictionary in order of insertion using Python. $ dictionary_1 = {'A': 'Geeks', 'B': 'For', 'C': 'Geeks'} $ print(dictionary_1.keys()) -> dict_keys(['A', 'B', 'C'])

Что такое оператор принадлежности?

Это операторы in и not in. Они показывают, является ли одно значение частью другого.

Питон чувствителен к регистру?

Язык считается чувствительным к регистру в случае, если он различает имена "myname" и "Myname". То есть, если он отслеживает разницу регистра (между верхним и нижним). Yes!

Suppose list1 = [3, 4, 5, 2, 1, 0], what is list1 after list1.pop(1)?

list1 = [3, 5, 2, 1, 0] (index 1 had element "4")

В каком случае while уместнее, чем for?

В целом, for подойдет во всех случаях, когда применим while, однако есть несколько ситуаций, когда с циклом while проще: - Простые повторяющиеся циклы - Когда не нужно осуществлять итерацию вдоль списка элементов.

Чем файл .pyc отличается от .py?

Оба файла содержат байткод, но .pyc является компилированной версией файла питона. Его байткод не зависит от платформы, поэтому он исполняется на всех платформах, которые поддерживают формат .pyc.

Что быстрее dict, list, set, tuple?

Средняя временная сложность поиска в множествах и словарях соответствует O(1), в случае последовательностей O(n). Кортежи - это неизменяемый тип, поэтому они могут давать выигрыш в скорости перед списками.


Set pelajaran terkait

Lab Quiz Material: Exercise 23 & 24

View Set

Chapter 4 Organizational Behavior

View Set

ATI NSG CARE OF CHILDREN PRACTICE B WITH NGN

View Set

ISYS: Chapter 12 End of Chapter Quiz

View Set

Proportional Reasoning (practice)~ amdm

View Set