Posts

What are the different data types in Python?

Python Datatypes : Boolean Numbers Strings Lists Tuples Sets Dictionaries Boolean : Booleans are either true or false. Python has 2 constants named True and False which can be used to assign a boolean value directly. In certain places ( like if statements ), Python expects an expression to a boolean value, these places are called boolean contexts. Numbers : Python supports both int and floating point numbers. Tuples : A tuple is an immutable list, it means a tuple can't be changed in a way once it's created. A tuple is defined in the same way as a list, except that the whole set of an element is enclosed in the parenthesis instead of square brackets. Similarities with the list  : Tuples have a defined order i.e. Indices are 0 based, so the first element of a non-empty tuple is always a_tuple[ 0 ]. Negative indices count from the end of the tuple. Slicing works too, when we slice a list we get a new list. When we slice a tuple, we get a new t

What is composite key?

Composite Key : A composite key is a combination of two or more columns in a table that can be used to uniquely identify each row in the table. When the columns are combined uniqueness is guaranteed but when it taken individually it does not guarantee uniqueness. Sometimes more than one attributes are needed to uniquely identify an entity. A primary key that is made by the combination of more than one attribute is known as a composite key. Ex : Create table abc ( c1 int , c2 varchar(20), c3 varchar(100) , PRIMARY KEY ( c1, c2 ) );

Explain pickling and unpickling in python.

Pickling and Unpickling : Pickle is a standard module which serializes and deserializes a python object structure. Pickle module accepts any python object, converts it into a string representation and dumps into a file(by using dump() function ) which can be used later this process is called pickling. Unpickling is a process of retrieving original python object from the stored string representation for use. Pickling is a process whereby a python object hierarchy is converted into a byte stream and unpickling is the inverse operation, whereby a byte stream is converted back into an object hierarchy. Ex: import pickle a = [ "apple" , "banana" ] file_Name = "abc" # open the file for writing fileObj = open( file_Name , "wb" ) # This writes the object a to the file pickle.dump( a , fileObj) fileObj.close() fileObj = open( file_Name , "r") # load the object from the file into variable b = pickle.load( fileO

What is list comprehension? Also explain generator comprehension, set comprehension and dictionary comprehension?

List Comprehension : List comprehension was introduced in 2.0. List comprehension is an elegant way to define and create a list in Python. List comprehension is a complete substitute for the lambda function as well as the functions map(), filter() and reduce(). >>> Celsius = [39.2, 36.5, 37.3, 37.8] >>> Fahrenheit = [ ((float(9)/5)*x + 32) for x in Celsius ] >>> print Fahrenheit [102.56, 97.700000000000003, 99.140000000000001, 100.03999999999999] Generator Comprehension : Generator comprehensions were introduced with Python 2.6.  They are simply a generator expression with a parenthesis - round brackets - around it. Otherwise, the syntax and the way of working is like list comprehension, but a generator comprehension returns a generator instead of a list. >>> x = (x **2 for x in range(20)) >>> print(x) at 0xb7307aa4> >>> x = list(x) >>> print(x) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 10

Explain slicing and indexing operations.

Slicing and Indexing operations : Indexing operation allows to access a particular item in the sequence directly. Slicing operation allows to retrieve a part of the sequence. In slicing : S[ StartNo : StopNo : Step ] If the start no is omitted, Python will start at the beginning of the sequence. If the stop no is omitted, Python will stop at the end of the sequence. >>> a = [1,2,3,4] >>> a[0:2] # take items 0-2, upper bound noninclusive [1, 2] >>> a[0:-1] #take all but the last [1, 2, 3] >>> a[1:4] [2, 3, 4] >>> a[::-1] # reverse the list [4, 3, 2, 1] >>> a[::2] # skip 2 [1, 3]

What is persistent cookie?

Persistent Cookie : Also called a permanent cookie, or a stored cookie, a cookie that is stored on a user's hard drive until it expires (persistent cookies are set with expiration dates) or until the user deletes the cookie.  Persistent cookies are used to collect identifying information about the user, such as Web surfing behavior or user preferences for a specific Web site. A persistent cookie enables a website to remember you on subsequent visits, speeding up or enhancing your experience of services or functions offered. For example, a website may offer its contents in different languages. On my first visit, I may choose to have the content delivered in French and the site may record that preference in a persistent cookie set on your browser. When you revisit that site it will use the cookie to ensure that the content is delivered in French. Session Cookie : Also called a transient cookie, a cookie that is erased when the user closes the Web browser. The session c

Interview questions and answers

Ques: How are the functions help() and dir() different? Ans: These are the two functions that are accessible from the Python Interpreter. These two functions are used for viewing a consolidated dump of built-in functions. help : It will display the documentation string. It is used to see the help related to modules, keywords, attributes, etc. To view the help for a keyword, topics, you just need to type, help("<keyword>") dir : Without arguments, it will return list of names in the current local scope.  With an argument, it will return a list of valid attributes for that object. Ques:  Which statement of Python is used whenever a statement is required syntactically but the program needs no action? Ans: p ass is no-operation / action statement in Python. If we want to get data from a model  and even if the requested data does not exist, we want to continue with other tasks. In such a scenario, use try-except block with pass statement in the exc

How sessions work in Django?

The session framework stores and retrieves data. It stores the data on the server side and sends and receives the cookies. Cookies contain a session ID, not the data itself unless we are using the cookie-based sessions. Django provides support for anonymous sessions. Configuring the session engine: By default, Django stores sessions in our database. We can configure Django to store session data using these sessions engines: Database-backed sessions Cached sessions File-based sessions Cookie-based sessions Database-backed sessions: To use databased-backed sessions we need to add "django.contrib.sessions" to our INSTALLED_APPS setting. After this configuration, we need to run manage.py migrate to install the database table that stores session data. Cached sessions: For better performance, we can use a cached-based session backend. We should only use it if we are using Memcached cache backend. File-based sessions: To use file-based sess

What is middleware in django?

Image
Middleware  : Middleware is a framework of hooks into Django’s request/response processing. Middleware is a lightweight plugin for Django. It allows modifying request or response or the view parameters. Each middleware component is responsible for doing some specific function. For example, Django includes a middleware component, AuthenticationMiddleware, that associates users with requests using sessions. When to use middleware  : We can use middleware if you want to modify the request i.e HttpRequest object which is sent to the view. Or you might want to modify the HttpResponse object returned from the view. Both these can be achieved by using middleware. We might want to perform an operation before the view executes. In such case, we would use a middleware. Hooks and Application order  : Request phase  : During the request phase, before calling the view. Django applies middleware in the order it's defined in MIDDLE_CLASSES top-down. 2 hooks are available : proc

What is difference between multi-threading and multiprocessing?

Image
Multi-threading vs Multiprocessing : The threading module uses threads, the multiprocessing uses processes. 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. Multiprocessing : Pross : Separate memory space Takes advantage of multiple CPUs & cores Avoids GIL limitations for cPython Child processes are interruptible/killable Cons : Inter-process communication (IPC) a little more complicated with more overhead. Larger memory footprint. Multi-threading : Pross : Lightweight - low memory footprint. Shared memory - makes access to state from another context easier. Allows you to easily make responsive UIs. cPython C extension modules that properly releas