Python / FAQ

Python Interview Questions

Python is a high-level programming language known for its simplicity and readability. It is widely used for web development, software development, data analysis, artificial intelligence, scientific computing, and more. Python's versatility and large standard library make it a popular choice for many different types of projects.

Global Variables: Variables declared outside a function or in a global space are called global variables. These variables can be accessed by any function in the program.

Local Variables: Any variable declared inside a function is known as a local variable. This variable is present in the local space and not in the global space.

Use a tuple to store a sequence of items that will not change.
Use a list to store a sequence of items that may change.
Use a dictionary when you want to associate pairs of two items.

Python is a dynamic-typed language. It means that you don’t need to mention the data type of variables during their declaration.
Python supports object-orientated programming as you can define classes along with the composition and inheritance.

Negative numbers mean that you count from the right instead of the left. So, list[-1] refers to the last element, list[-2] is the second-last, and so on.

To convert the string into a number the built-in functions are used like int() a constructor. It is a data type that is used like int (‘1’) == 1.
float() is also used to show the number in the format as float(‘1’) = 1.
The number by default is interpreted as a decimal and if it is represented by int(‘0x1’) then it gives an error as ValueError.

None is just a value that commonly is used to signify 'empty', or 'no value here.
If you write a function, and that function doesn't use an explicit return statement, None is returned instead, for example.
Another example is to use None default values. it is good programming practice to not use mutable objects as default values. Instead, use None as the default value, and inside the function, check if the parameter is None and create a new list/dictionary/whatever if it is.

Consider:
def foo(mydict=None):
if mydict is None:
mydict = {} # Create a new dict for the local namespace

In Python, functions are the first-class objects, which means that:
Functions are objects; they can be referenced to, passed to a variable, and returned from other functions.

In Python, the term monkey patch only refers to dynamic modifications of a class or module at runtime, which means a monkey patch is a piece of Python code that extends or modifies other code at runtime.

The key difference is that tuples are immutable. This means you cannot change the values in a tuple once you have created it.
If you're going to need to change the values using a List.

Python - like C#, Java, and many other languages -- uses garbage collection rather than manual memory management. You just freely create objects and the language's memory manager periodically (or when you specifically direct it to) looks for any objects no longer referenced by your program.

append adds an element to a list, and
extends concatenates the first list with another list (or another iterable, not necessarily a list).
Consider:
x = [1, 2, 3]
x.append([4, 5])
print (x)
# [1, 2, 3, [4, 5]]
x = [1, 2, 3]
x.extend([4, 5])
print (x)
# [1, 2, 3, 4, 5]

Method Resolution Order (MRO) denotes the way a programming language resolves a method or attribute. Python supports classes inheriting from other classes. The class being inherited is called the Parent or Superclass, while the class that inherits is called the Child or Subclass.

Python doesn't allow multi-threading in the truest sense of the word. It has a multi-threading package but if you want to multi-thread to speed your code up, then it's usually not a good idea to use it.

Python has a construct called the Global Interpreter Lock (GIL).
The GIL makes sure that only one of your threads can execute at any one time. A thread acquires the GIL, does a little work, then passes the GIL onto the next thread. This happens very quickly so to the human eye it may seem like your threads are executing in parallel, but they are just taking turns using the same CPU core. All this GIL passing adds overhead to execution.

A lot can be said here. There are a few main points that you should mention:
Python maintains a count of the number of references to each object in memory. If a reference count goes to zero then the associated object is no longer live and the memory allocated to that object can be freed up for something else.

Objects referenced from the global namespaces of Python modules are not always deallocated when Python exits. This may happen if there are circular references. Certain bits of memory are allocated by the C library that are impossible to free (e.g. a tool like Purify will complain about these). Python is, however, aggressive about cleaning up memory on exit and does try to destroy every single object.

EXE and DLLs are assembly executable modules.
EXE is an executable file that runs the application for which it is designed. An EXE is produced when we build an application. Therefore the assemblies are loaded directly when we run an EXE. However, an EXE cannot be shared with the other applications.

Dynamic Link Library (DLL) is a library that consists of code that needs to be hidden. The code is encapsulated inside this library. An application can consist of many DLLs which can be shared with the other programs and applications.

JIT stands for Just In Time. It is a compiler that converts the intermediate code into the native language during the execution

The main differences between value type and reference type are given below:
A Value Type holds the actual data directly within the memory location and a reference type contains a pointer which consists of the address of another memory location that holds the actual data.
Value type stores its contents on the stack memory and reference type stores its contents on the heap memory.
Assigning a value type variable to another variable will copy the value directly and assigning a reference variable to another doesn’t copy the value, instead, it creates a second copy of the reference.
Predefined data types, structures, and enums are examples of value types. Classes, Objects, Arrays, Indexers, Interfaces, etc are examples of reference types

MSIL is the Microsoft Intermediate Language, which provides instructions for calling methods, memory handling, storing and initializing values, exception handling, and so on.
The instructions provided by MSIL are platform-independent and are generated by the language-specific compiler from the source code. JIT compiler compiles the MSIL into machine code based on the requirement.

Yes, ASP.NET and ASP(Active Server Pages) both are different. Let’s check how they are different from each other.
ASP.NET uses .NET languages such as C# and VB.NET, which are compiled into Microsoft Intermediate Language (MSIL). ASP uses VBScript. ASP code is interpreted during the execution.
ASP.NET which is developed by Microsoft is used to create dynamic web applications while ASP is Microsoft’s server-side technology used to create web pages.
ASP.NET is fully object-oriented but ASP is partially object-oriented.
ASP.NET has full XML Support for easy data exchange whereas ASP has no built-in support for XML.
ASP.NET uses the ADO.NET technology to connect and work with databases. ASP uses ADO technology.

Role-based security is used to implement security measures in .NET, based on the roles assigned to the users in the organization. In the organization, authorization of users is done based on their roles.
For example, windows have role-based access like administrators, users, and guests

Assemblies are classified into 2 types. They are:
Private Assembly:
It is accessible only to the application.
We need to copy this private assembly, separately in all application folders where we want to use that assembly. Without copying, we cannot access the private assembly.
It requires to be installed in the installation directory of the application.
Shared or Public Assembly:
It can be shared by multiple applications.
Public assembly does not require copying separately into all application folders. Only one copy of public assembly is required at the system level, we can use the same copy in multiple applications.
It is installed in the Global Assembly Cache(GAC)

There are eight events as given below that take place to successfully render a page:
Page_PreInit
Page_Init
Page_InitComplete
Page_PreLoad
Page_Load
Page_LoadComplete
Page_PreRender
Render

In Python, iterators are used to iterate a group of elements, containers like a list. Iterators are collections of items, and they can be lists, tuples, or dictionaries. Python iterator implements _itr_ and the next() method to iterate the stored elements. We generally use loops to iterate over the collections (list, tuple) in Python.

The following are the benefits of using Python language:
Object-Oriented Language
High-Level Language
Dynamically Typed language
Extensive support Libraries
Presence of third-party modules
Open source and community development
Portable and Interactive
Portable across Operating systems

Python is a partially compiled language and partially interpreted language. The compilation part is done first when we execute our code and this will generate byte code internally this byte code gets converted by the Python virtual machine(p.v.m) according to the underlying platform(machine+operating system).

Mutable data types can be edited i.e., they can change at runtime. Eg – List, Dictionary, etc.
Immutable data types can not be edited i.e., they can not change at runtime. Eg – String, Tuple, etc.
Q30)What is the difference between a Set and a Dictionary?
The set is an unordered collection of data types that is iterable, mutable, and has no duplicate elements.

There are 3 main keywords i.e. try, except, and finally which are used to catch exceptions and handle the recovering mechanism accordingly. Try is the block of a code that is monitored for errors. Except block gets executed when an error occurs.
The beauty of the final block is to execute the code after trying for an error. This block gets executed irrespective of whether an error occurred or not. Finally, the block is used to do the required cleanup activities of objects/variables.

The “for” Loop is generally used to iterate through the elements of various collection types such as List, Tuple, Set, and Dictionary. Developers use a “for” loop where they have both the conditions start and the end. Whereas, the “while” loop is the actual looping feature that is used in any other programming language. Programmers use a Python while loop where they just have the end conditions.

To pass a variable number of arguments to a function in Python, use the special syntax *args and **kwargs in the function specification. It is used to pass a variable-length, keyword-free argument list. By using the *, the variable we associate with the * becomes iterable, allowing you to do operations on it such as iterating over it and using higher-order operations like map and filter.

The location where we can find a variable and also access it if required is called the scope of a variable.
Python Local variable: Local variables are those that are initialized within a function and are unique to that function. It cannot be accessed outside of the function.
Python Global variables: Global variables are the ones that are defined and declared outside any function and are not specified to any function.
Module-level scope: It refers to the global objects of the current module accessible in the program.
Outermost scope: It refers to any built-in names that the program can call. The name referenced is located last among the objects in this scope.

Typed languages are the languages in which we define the type of data type and it will be known by the machine at the compile-time or runtime. Typed languages can be classified into two categories:
Statically typed languages: In this type of language, the data type of a variable is known at the compile time which means the programmer has to specify the data type of a variable at the time of its declaration.
Dynamically typed languages: These are the languages that do not require any pre-defined data type for any variable as it is interpreted at runtime by the machine itself. In these languages, interpreters assign the data type to a variable at runtime depending on its value.

The break statement is used to terminate the loop or statement in which it is present. After that, the control will pass to the statements that are present after the break statement, if available.
Continue is also a loop control statement just like the break statement. continue statement is opposite to that of the break statement, instead of terminating the loop, it forces to execute the next iteration of the loop.
Pass means performing no operation or in other words, it is a placeholder in the compound statement, where there should be a blank left and nothing has to be written there.

range() and range () are two functions that could be used to iterate a certain number of times in for loops in Python. In Python 3, there is no xrange, but the range function behaves like xrange in Python 2.
range() – This returns a list of numbers created using the range() function.
range) – This function returns the generator object that can be used to display numbers only by looping. The only particular range is displayed on demand and hence called lazy evaluation.

Let’s analyze the differences between List and Tuple:
List
Lists are Mutable datatype.
Lists consume more memory
The list is better for performing operations, such as insertion and deletion.
The implication of iterations is Time-consuming
Tuple
Tuples are Immutable datatype.
Tuple consumes less memory as compared to the list
A Tuple data type is appropriate for accessing the elements
The implication of iterations is comparatively Faster

Shallow copy is used when a new instance type gets created and it keeps values that are copied whereas deep copy stores values that are already copied.
A shallow copy has faster program execution whereas a deep copy makes it slow.

In Python, iterators are used to iterate a group of elements, containers like a list. Iterators are collections of items, and they can be lists, tuples, or dictionaries. Python iterator implements _itr_ and the next() method to iterate the stored elements. We generally use loops to iterate over the collections (list, tuple) in Python.

In Python, the generator is a way that specifies how to implement iterators. It is a normal function except that it yields expression in the function. It does not implement the _itr_ and next() method and reduces other overheads as well.
If a function contains at least a yield statement, it becomes a generator. The yield keyword pauses the current execution by saving its states and then resumes from the same when required.