python : Interview Questions

Answer:

Python is a programming language with objects, modules, threads, exceptions and automatic memory management. The benefits of pythons are that it is simple and easy, portable, extensible, build-in data structure and it is an open source.

Answer:

PEP 8 is a coding convention, a set of recommendation, about how to write your Python code more readable.

Answer:

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.

Answer:

Python language is an interpreted language. Python program runs directly from the source code. It converts the source code that is written by the programmer into an intermediate language, which is again translated into machine language that has to be executed.

Answer:

  • Python memory is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have an access to this private heap and interpreter takes care of this Python private heap.
  • The allocation of Python heap space for Python objects is done by Python memory manager. The core API gives access to some tools for the programmer to code.
  • Python also have an inbuilt garbage collector, which recycle all the unused memory and frees the memory and makes it available to the heap space.

Answer:

PyChecker is a static analysis tool that detects the bugs in Python source code and warns about the style and complexity of the bug. Pylint is another tool that verifies whether the module meets the coding standard.

Answer:

A Python decorator is a specific change that we make in Python syntax to alter functions easily.

Answer:

The difference between list and tuple is that list is mutable while tuple is not. Tuple can be hashed for e.g as a key for dictionaries.

Answer:

Everything in Python is an object and all variables hold references to the objects. The references values are according to the functions; as a result you cannot change the value of the references. However, you can change the objects if it is mutable.

Answer:

They are syntax constructions to ease the creation of a Dictionary or List based on existing iterable.

Answer:

There are mutable and Immutable types of Pythons built in types Mutable built-in types

  • List
  • Sets
  • Dictionaries

Immutable built-in types

  • Strings
  • Tuples
  • Numbers

Answer:

In Python, every name introduced has a place where it lives and can be hooked for. This is known as namespace. It is like a box where a variable name is mapped to the object placed. Whenever the variable is searched out, this box will be searched, to get corresponding object.

Answer:

It is a single expression anonymous function often used as inline function.

Answer:

A lambda form in python does not have statements as it is used to make new function object and then return them at runtime.

Answer:

Pass means, no-operation Python statement, or in other words it is a place holder in compound statement, where there should be a blank left and nothing has to be written there.

Answer:

In Python, iterators are used to iterate a group of elements, containers like list.

Answer:

A unit testing framework in Python is known as unittest. It supports sharing of setups, automation testing, shutdown code for tests, aggregation of tests into collections etc.

Answer:

A mechanism to select a range of items from sequence types like list, tuple, strings etc. is known as slicing.

Answer:

The way of implementing iterators are known as generators. It is a normal function except that it yields expression in the function.

Answer:

A Python documentation string is known as docstring, it is a way of documenting Python functions, modules and classes.

Answer:

To copy an object in Python, you can try copy.copy () or copy.deepcopy() for the general case. You cannot copy all objects but most of them.

Answer:

Python sequences can be index in positive and negative numbers. For positive index, 0 is the first index, 1 is the second index and so forth. For negative index, (-1) is the last index and (-2) is the second last index and so forth.

Answer:

In order to convert a number into a string, use the inbuilt function str(). If you want a octal or hexadecimal representation, use the inbuilt function oct() or hex().

Answer:

Xrange returns the xrange object while range returns the list, and uses the same memory and no matter what the range size is.

Answer:

In Python, module is the way to structure program. Each Python program file is a module, which imports other modules like objects and attributes.

The folder of Python program is a package of modules. A package can have modules or subfolders.

Answer:

Local variables: If a variable is assigned a new value anywhere within the function's body, it's assumed to be local.

Global variables: Those variables that are only referenced inside a function are implicitly global.

Answer:

To share global variables across modules within a single program, create a special module. Import the config module in all modules of your application. The module will be available as a global variable across modules.

Answer:

To make a Python Script executable on Unix, you need to do two things,

  • Script file's mode must be executable and
  • the first line must begin with # ( #!/usr/local/bin/python)

Answer:

By using a command os.remove (filename) or os.unlink(filename)

Answer:

To generate random numbers in Python, you need to import command as

import random

random.random()

This returns a random floating point number in the range [0,1)

Answer:

You can access a module written in Python from C by following method,

Module = =PyImport_ImportModule("");

Answer:

It is a Floor Divisionoperator , which is used for dividing two operands with the result as quotient showing only digits before the decimal point. For instance, 10//5 = 2 and 10.0//5.0 = 2.0.

Answer:

  • Python comprises of a huge standard library for most Internet platforms like Email, HTML, etc.
  • Python does not require explicit memory management as the interpreter itself allocates the memory to new variables and free them automatically
  • Provide easy readability due to use of square brackets
  • Easy-to-learn for beginners
  • Having the built-in data types saves programming time and effort from declaring variables

Answer:

The use of the split function in Python is that it breaks a string into shorter strings using the defined separator. It gives a list of all words present in the string.

Answer:

Flask is a web micro framework for Python based on "Werkzeug, Jinja 2 and good intentions" BSD licensed. Werkzeug and jingja are two of its dependencies.

Flask is part of the micro-framework. Which means it will have little to no dependencies on external libraries. It makes the framework light while there is little dependency to update and less security bugs.

Answer:

Flask is a "microframework" primarily build for a small application with simpler requirements. In flask, you don't have to use external libraries. Flask is ready to use.

Pyramid are build for larger applications. It provides flexibility and lets the developer use the right tools for their project. The developer can choose the database, URL structure, templating style and more. Pyramid is heavy configurable.

Like Pyramid, Django can also used for larger applications. It includes an ORM.

Answer:

Flask-WTF offers simple integration with WTForms. Features include for Flask WTF are

  • Integration with wtforms
  • Secure form with csrf token
  • Global csrf protection
  • Internationalization integration
  • Recaptcha supporting
  • File upload that works with Flask Uploads

Answer:

The common way for the flask script to work is

  • Either it should be the import path for your application
  • Or the path to a Python file

Answer:

A session basically allows you to remember information from one request to another. In a flask, it uses a signed cookie so the user can look at the session contents and modify. The user can modify the session if only it has the secret key Flask.secret_key.

Answer:

Basically, Flask is a minimalistic framework which behaves same as MVC framework. So MVC is a perfect fit for Flask, and the pattern for MVC we will consider for the following example
 

from flask import Flask

app = Flask(_name_)

@app.route("/")

Def hello():

return "Hello World"

app.run(debug = True)

In this code your,

Configuration part will be
from flask import Flask

app = Flask(_name_)

View part will be
@app.route("/")

Def hello():

return "Hello World"

While you model or main part will be
app.run(debug = True)
 

Answer:

Flask supports database powered application (RDBS). Such system requires creating a schema, which requires piping the shema.sql file into a sqlite3 command. So you need to install sqlite3 command in order to create or initiate the database in Flask.

Flask allows to request database in three ways

  • before_request() : They are called before a request and pass no arguments
  • after_request() : They are called after a request and pass the response that will be sent to the client
  • teardown_request(): They are called in situation when exception is raised, and response are not guaranteed. They are called after the response been constructed. They are not allowed to modify the request, and their values are ignored.

Answer:

The data in the failed server won't get removed, but there is a provision for auto-failure, which you can configure for multiple nodes. Fail-over can be triggered during any kind of socket or Memcached server level errors and not during normal client errors like adding an existing key, etc.

Answer:

  • When one instance fails, several of them goes down, this will put larger load on the database server when lost data is reloaded as client make a request. To avoid this, if your code has been written to minimize cache stampedes then it will leave a minimal impact
  • Another way is to bring up an instance of Memcached on a new machine using the lost machines IP address
  • Code is another option to minimize server outages as it gives you the liberty to change the Memcached server list with minimal work
  • Setting timeout value is another option that some Memcached clients implement for Memcached server outage. When your Memcached server goes down, the client will keep trying to send a request till the time-out limit is reached

Answer:

Dogpile effect is referred to the event when cache expires, and websites are hit by the multiple requests made by the client at the same time. This effect can be prevented by using semaphore lock. In this system when value expires, first process acquires the lock and starts generating new value.

Answer:

  • Memcached common misuse is to use it as a data store, and not as a cache
  • Never use Memcached as the only source of the information you need to run your application. Data should always be available through another source as well
  • Memcached is just a key or value store and cannot perform query over the data or iterate over the contents to extract information
  • Memcached does not offer any form of security either in encryption or authentication

Answer:


Both tuples and lists are data structures in Python and hold a list of values. Unlike lists, tuples are immutable - they can't be changed.

Answer:

dict is a structure akin a hash map. It stores key-value pairs, where keys are unique and it has O(1) access time. The most important limitation for a dict is that the keys must be hashable/immutable. Meaning, we can use a tuple as a key, but not a list.

Answer:

A callable is an object we can call - function or an object implementing the __call__ special method. Any object can be made callable.

Answer:

[a for a in range(0, 100) if a%2]
 

Answer:

Pickling is converting an object to a string representation in python. Generally used for caching and transferring objects between hosts/processes.

Answer:

A generator is a callable object that acts as an iterable (object you can iterate in for cycles etc).

Answer:

Decorators in Python are used to modify or inject code in functions or classes. Using decorators, you can wrap a class or function method call so that a piece of code can be executed before or after the execution of the original code. Decorators can be used to check for permissions, modify or track the arguments passed to a method, logging the calls to a specific method, etc.

Answer:

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

Answer:

Arguments in python are passed as an assignment. This assignment creates an object that has no relationship between an argument name in source and target. The procedure to write the function using call by reference includes:
The tuple result can be returned to the object which called it. The example below shows it:
 

def function(a, b):
a = 'value'
b = b + 1
# a and b are local variables that are used to assign the new objects
return a, b
# This is the function that is used to return the value stored in b

- The use of global variables allows the function to be called as reference but this is not the safe method to call any function.
- The use of mutable (they are the classes that consists of changeable objects) objects are used to pass the function by reference.
 
def function(a):
a[0] = 'string'
a[1] = a[1] + 1
# The ‘a’ array give reference to the mutable list and it changes the changes that are shared
args = ['string', 10]
func1(args)
print args[0], args[1]
#This prints the value stored in the array of ‘a’
 

Answer:

he command that is used to copy an object in python includes:
- copy.copy() function: This makes a copy of the file from source to destination. It returns a shallow copy of the parameter that is passed.
- copy.deepcopy(): This also creates a copy of the object from source to destination. It returns a deep copy of the parameter that is passed to the function.
The dictionary consists of all the objects and the copy() method which is used as:
 

newdict = olddict.copy()

The assignment statement doesn’t copy any object but it creates a binding between the target and the object that is used for the mutable items. Copy is required to keep a copy of it using the modules that is provided to give generic and shallow operations.

Answer:

- Shallow copy is used when a new instance type gets created and it keeps the values that are copied in the new instance. Whereas, deep copy is used to store the values that are already copied.
- Shallow copy is used to copy the reference pointers just like it copies the values. These references point to the original objects and the changes made in any member of the class will also affect the original copy of it. Whereas, deep copy doesn’t copy the reference pointers to the objects. Deep copy makes the reference to an object and the new object that is pointed by some other object gets stored. The changes made in the original copy won’t affect any other copy that uses the object.
- Shallow copy allows faster execution of the program and it depends on the size of the data that is used. Whereas, deep copy makes it slower due to making certain copies for each object that is been called.

Answer:

The object doesn’t have any name and there is no way the can be found out for objects. The assignment is used to bind a name to the value that includes the name of the object that has to be bound by a value. If the value is callable then the statements are made true and then the program followed can be used to find the reference name of an object.
 

class try:
pass
B = A
a = B()
b = a
print b
<__main__.try instance at 0x16D07CC>
print b

The class consists of name and the names are invoked by using the the variable B that creates an instance for the class try. The method is to find out from all the namespaces that the object exists and then print the name of the object.

Answer:

The ternary operator is the operator that is used to show the conditional statements. This consists of the true or false values with a statement that has to be evaluated for it. The operator will be given as:
 

[on_true] if [expression] else [on_false]
x, y = 25, 50
big = x if x < y else y

This is the lowest priority operator that is used in making a decision that is based on the values of true or false. The expression gets evaluated like if x<y else y, in this case if x<y is true then the value is returned as big=x and if it is incorrect then big=y will be sent as a result.

Answer:

- To convert the string into a number the built-in functions are used like int() 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 are interpreted as decimal and if it is represented by int(‘0x1’) then it gives an error as ValueError. In this the int(string,base) function takes the parameter to convert string to number in this the process will be like int(‘0x1’,16)==16. If the base parameter is defined as 0 then it is indicated by an octal and 0x indicates it as hexadecimal number.
- There is function eval() that can be used to convert string into number but it is a bit slower and present many security risks like __import__('os').system("rm -rf$HOME") - use of this will delete the home directory of the system.

Answer:

The sequences in python are indexed and it consists of the positive as well as negative numbers. The numbers that are positive uses ‘0’ as first index and ‘1’ as the second index and the process goes on like that. The index for the negative number starts from ‘-1’ that represents the last index in the sequence and ‘-2’ as the penultimate index and the sequence carries forward like the positive number. The negative index is used to remove any new-line spaces from the string and allow the string to except the last character that is given as S[:-1]. The negative index is also used to show the index to represent the string in correct order.

Answer:

There is a method which is built-in to show the instances of an object that consists of many classes by providing a tuple in a table instead of individual classes. The method is isinstance(obj,cls)

isinstance(obj, (class1, class2, ...)) is used to check the object’s presence in one of the classes. The built in types can also have many formats of the same function like isinstance(obj, str) or isinstance(obj, (int, long, float, complex)).

It is not preferred to use the class instead user-defined classes are made that allow easy object-oriented style to define the behavior of the object’s class. These perform different thing based on the class. The function differs from one class to another class.
To find out the object of the particular class the following program is used:
 

def search(obj):
if isinstance(obj, box):
# This is the code that is given for the box and write the program in the object
elif isinstance(obj, Document):
# This is the code that searches the document and writes the values in it
elif
obj.search()
#This is the function used to search the object’s class.
 

Answer:

Delegation is an object oriented technique (also called a design pattern). Let's say you have an object x and want to change the behaviour of just one of its methods. You can create a new class that provides a new implementation of the method you're interested in changing and delegates all other methods to the corresponding method of x. The example shows a class that captures the behavior of the file and converts data from lower to uppercase.
 

class upcase:
def __init__(self, out):
self._out = out
def write(self, s):
self._outfile.write(s.upper())
def __getattr__(self, name):
return getattr(self._out, name)

The write() method is used in the upcase class converts the string to the uppercase before calling another method. The delegation is being given using the self.__outfile object.

Answer:

“Self” is a variable that represents the instance of the object to itself. In most of the object oriented programming language, this is passed to the methods as a hidden parameters that is defined by an object. But, in python, it is declared and passed explicitly. It is the first argument that gets created in the instance of the class A and the parameters to the methods are passed automatically. It refers to separate instance of the variable for individual objects. This is the first argument used in the class instance and the “self” method is defined explicitly to all the methods that are used and present. The variables are referred as “self.xxx”.

Answer:

“Self” is a reference variable and an instance attribute that is used instead of the local variable inside the class. The function or the variable of the self like self.x or self.meth() can be used in case the class is not known. There are no variables declared as local. It doesn’t have any syntax and it allow the reference to be passed explicity or call the method for the class that is in use. The use of writebaseclass.methodname(self, <argument list>) shows that the method of _init_() can be extended to the base class methods. This also solves the problem that is syntactic by using the assignment and the local variables. This tells a way to the interpreter the values that are to be used for the instance variables and local variables. The use of explicit self.var solves the problem mentioned above.

Answer:

The compiling and linking allows the new extensions to be compiled properly without any error and the linking can be done only when it passes the compiled procedure. If the dynamic loading is used then it depends on the style that is being provided with the system. The python interpreter can be used to provide the dynamic loading of the configuration setup files.
The steps required are as follows:
- Create a file with any name and in any lanugage supported by the compiler of your system. For example comp.c
- Place this file in the Modules/ directory of the distribution which is getting used.
- Add a line in the file Setup.local present in the Modules/ directory.
- Run the file using spam comp.o
- After successful run of this rebuild the interpreter by using the make command on the top-level directory.
- If the file is changed then run rebuildMakefile by using the command as ‘make Makefile’.

Answer:

To extract the value it requires the object type to be defined and the values are fetched according to the object type.
The values are extracted as:
- If the object is a tuple then PyTuple_Size() method is used that returns the length of the values and the method PyTuple_GetItem() returns the data item stored at a specific index.
- If the object is a list then PyListSize() and PyList_GetItem() perform the same function as they are for tuple.
- Strings use PyString_Size() to return the length of the value and PyString_AsString() returns the pointer to its value.
- To check the type of the object and the extracted values, methods like PyString_Check(), PyTuple_Check(), PyList_Check(), etc are used.

Answer:

The steps required to make a script executable are:
- First create a script file and write the code that has to be executed in it.
- Make the file mode as executable by making the first line starts with #! this is the line that python interpreter reads.
- Set the permission for the file by using chmod +x file. The file uses the line which is the most important line to be used:
 

#!/usr/local/bin/python

- This explains the pathname that is given to the python interpreter and it is independent of the environment programs.
- Absolute pathname should be included so that the interpreter can interpret and execute the code accordingly. The sample code that is written:
 
#! /bin/sh
# Write your code here
exec python $0 ${1+"$@"}
# Write the function that need to be included.
 

Answer:

The global interpreter lock allows the running of the thread one at a time. This is used to distribute the functionality among all the virtual machines that are used. Python allows the switching between the threads to be performed by using the byte code instructions to provide platform-independence. The sys.setcheckinterval() method is used to allow the switching to occur during the implementation of the program and the instruction. This provides the understanding in the field of accounting to use the byte code implementation that makes it portable to use. The atomicity can be provided such that the shared variables can be given as built-in data types.

Answer:

The module which is used to write and read the binary data is known as struct. This module allows many functionalities to be used that consist of the string class. This class contains the binary data that is in the form of numbers that gets converted in python objects for use and vice versa. The program can read or write the binary data is:
 

import struct
f = open(file-name, "rb")
# This Open() method allows the file to get opened in binary mode to make it portable for # use.
s = f.read(8)
x, y, z = struct.unpack(">hhl", s)

The ‘>” is used to show the format string that allows the string to be converted in big-endian data form. For homogenous list of data the array module can be used that will allow the data to be kept in more organized fashion.

Answer:

The popen2() module is used to run the sub-process but due to some difficulty in processing like creation of deadlock keeping a process blocked and waiting for the output from the child and child is waiting for the input. The deadlock occurs due to the fact that parent and child doesn’t have the synchronization and both are waiting to get the processor to provide the resources to one another. Use of popen3() method allows the reading of stdout and stderr to take place where the internal buffer increases and there is no read() takes place to share the resources. popen2() takes care of the deadlock by providing the methods like wait() and waitpid() that finish a process first and when a request comes, it hands over the responsibility to the process waiting for the resources.
The program is used to show the process and run it.
 

import popen2
fromchild, tochild = popen2.popen2("command")
tochild.write("input\n")
tochild.flush()
output = fromchild.readline()
 

Answer:

Random module is the standard module that is used to generate the random number.
The method is defined as:
 

import random
random.random()

The statement random.random() method returns the floating point number that is in the range of [0, 1). The function generates the random float numbers. The methods that are used with the random class are the bound methods of the hidden instances. The instances of the Random can be done to show the multi-threading programs that creates different instance of individual threads. The other random generators that are used in this are:
- randrange(a, b): it chooses an integer and define the range in-between [a, b). It returns the elements by selecting it randomly from the range that is specified. It doesn’t build a range object.
- uniform(a, b): it chooses a floating point number that is defined in the range of [a,b).Iyt returns the floating point number
- normalvariate(mean, sdev): it is used for the normal distribution where the mu is a mean and the sdev is a sigma and used for standard deviation.
- The Random class is used to instantiate an independent multiple random number generators.

Answer:

Singleton pattern is used to provide a mechanism that limits the number of instances that can be used by one class. It also allows the same object to be shared between many different parts of the code. This allows the global variables to be used as the actual data that is hidden by the singleton class interface. The singleton class interface can have only one public member and one class method Handle. Private constructors are not used to create an object that is used outside the class. The process waits for the static member function to create new instances and return the singleton object.
The code that is used to call the singleton object is:
 

Singleton& Singleton::Handle()
{
   if( !psingle )
   {
       psingle = new Singleton;
   }
   return *psingle;
}
 

Answer:

A namespace in Python ensures that object names in a program are unique and can be used without any conflict. Python implements these namespaces as dictionaries with 'name as key' mapped to a corresponding 'object as value'. This allows for multiple namespaces to use the same name and map it to a separate object. A few examples of namespaces are as follows:

  • Local Namespace includes local names inside a function. the namespace is temporarily created for a function call and gets cleared when the function returns.
  • Global Namespace includes names from various imported packages/ modules that is being used in the current project. This namespace is created when the package is imported in the script and lasts until the execution of the script.
  • Built-in Namespace includes built-in functions of core Python and built-in names for various types of exceptions.
Lifecycle of a namespace depends upon the scope of objects they are mapped to. If the scope of an object ends, the lifecycle of that namespace comes to an end. Hence, it isn't possible to access inner namespace objects from an outer namespace.

Answer:

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:

  • local scope refers to the local objects available in the current function.
  • global scope refers to the objects available throught the code execution since their inception.
  • 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.

Answer:

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 behaviour 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 amiguity, 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 both their namespaces as separate identities.
temp = 10 	 # global-scope variable

def func():
      temp = 20   # local-scope variable
      print(temp)

print(temp) 	 # output => 10
func() 		 # output => 20
print(temp) 	 # output => 10
This behaviour can be overriden 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
      print(temp)

print(temp) 	 # output => 10
func() 		 # output => 20
print(temp) 	 # output => 20
 

Answer:

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 by the @decorator_name in Python and are called in bottom-up fashion. For example:
 

# decorator function to convert to lowercase
def lowercase_decorator(function):
    def wrapper():
        func = function()
        string_lowercase = func.lower()
        return string_lowercase
    return wrapper

# decorator function to split words
def splitter_decorator(function):
    def wrapper():
        func = function()
        string_split = func.split()
        return string_split
    return wrapper

@splitter_decorator	# this is executed next
@lowercase_decorator	# this is executed first
def hello():
    return 'Hello World'

hello() 	 # output => [ 'hello' , 'world' ]

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.
 
# decorator function to capitalize names
def names_decorator(function):
    def wrapper(arg1, arg2):
        arg1 = arg1.capitalize()
        arg2 = arg2.capitalize()
        string_hello = function(arg1, arg2)
        return string_hello
    return wrapper

@names_decorator
def say_hello(name1, name2):
    return 'Hello ' + name1 + '! Hello ' + name2 + '!'

say_hello('sara', 'ansh') 	 # output => 'Hello Sara! Hello Ansh!'
 

Answer:

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 mutabletuples 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] = 'ansh'    # modifying tuple => throws an error
my_list[0] = 'ansh'    # modifying list => list modified

print(my_tuple[0])     # output => 'sara'
print(my_list[0])     # output => 'ansh'
 

Answer:

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). Let's check out some examples, where comprehensions can be truly beneficial:

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]

squared_dict = {x:x**2 for x in my_list}    # dict comprehension
# output => {11: 121, 2: 4 , 3: 9 , 5: 25 , 7: 49}

Performing conditional filtering operations on the entire list
 
my_list = [2, 3, 5, 7, 11]

squared_list = [x**2 for x in my_list if x%2 != 0]    # list comprehension
# output => [9 , 25 , 49 , 121]

squared_dict = {x:x**2 for x in my_list if x%2 != 0}    # dict comprehension
# output => {11: 121, 3: 9 , 5: 25 , 7: 49}

Combining multiple lists into one
Comprehensions allow for multiple iterators and hence, can be used to combine multiple lists into one.
 
a = [1, 2, 3]
b = [7, 8, 9]

[(x + y) for (x,y) in zip(a,b)]  # parallel iterators
# output => [8, 10, 12]

[(x,y) for x in a for y in b]    # nested iterators
# output => [(1, 7), (1, 8), (1, 9), (2, 7), (2, 8), (2, 9), (3, 7), (3, 8), (3, 9)]

Flattening a multi-dimensional list
A similar approach of nested iterators (as above) can be applied to flatten a multi-dimensional list or work upon its inner elements.
 
my_list = [[10,20,30],[40,50,60],[70,80,90]]

flattened = [x for temp in my_list for x in temp]
# output => [10, 20, 30, 40, 50, 60, 70, 80, 90]

Note: List comprehensions have the same effect as the map method in other languages. They follow the mathematical set builder notation rather than map and filter functions in Python.

Answer:

There are several built-in data types in Python. Although, Python doesn't require data types to be defined explicitly during variable declarations but type errors are likely to occur if the knowledge of data types and their compatibility with each other are neglected. Python provides type() and isinstance() functions to check the type of these variables. These data types can be grouped into the following catetgories-

None Type
None keyword represents the null values in Python. Boolean equality operation can be performed using these NoneType objects.

Class Name Description
NoneType Represents the NULL values in Python

Numeric Types
There are three distint numeric types - integersfloating-point numbers, and complex numbers. Additionally, booleans are a sub-type of integers.
Class Name Description
int Stores integer literals including hex, octal and binary numbers as integers
float Stores literals containing decimal values and/or exponent sign as floating-point numbers
complex Stores complex number in the form (A + Bj) and has attributes: real and imag
bool Stores boolean value (True or False)
Note: The standard library also includes fractions to store rational numbers and decimal to store floating-point numbers with user-defined precision.

Sequence Types
According to Python Docs, there are three basic Sequence Types - liststuples, and range objects. Sequence types have the in and not in operators defined for their traversing their elements. These operators share the same priority as the comparison operations.
Class name Description
list Mutable sequence used to store collection of items.
tuple Immutable sequence used to store collection of items.
range Represents an immutable sequence of numbers generated during execution.
str Immutable sequence of Unicode code points to store textual data.
Note: The standard library also includes additional types for processing:
1. Binary data such as bytearray bytes memoryview , and
2. Text strings such as str .


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.
Class Name Description
dict Stores comma-separated list of key: value pairs

Set Types
Currently, Python has two built-in set types - set and frozensetset type is mutable and supports methods like add() and remove()frozenset type is immutable and can't be modified after creation.
Class Name Description
set Mutable unordered collection of distinct hashable objects
frozenset Immutable collection of distinct hashable objects
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.

Modules
Module is an additional built-in type supported by the Python Interpreter. It supports one special operation, i.e., attribute accessmymod.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.

Callable Types
Callable types are the types to which function call can be applied. They can be user-defined functionsinstance methodsgenerator functions, and some other built-in functionsmethods and classes.
 

Answer:

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 copy module -

  • 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 are references 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.
from copy import copy, deepcopy

list_1 = [1, 2, [3, 5], 4]

## shallow copy

list_2 = copy(list_1) 
list_2[3] = 7
list_2[2].append(6)

list_2    # output => [1, 2, [3, 5, 6], 7]
list_1    # output => [1, 2, [3, 5, 6], 4]

## deep copy

list_3 = deepcopy(list_1)
list_3[3] = 8
list_3[2].append(7)

list_3    # output => [1, 2, [3, 5, 6, 7], 8]
list_1    # output => [1, 2, [3, 5, 6], 4]
 

Answer:

Python packages and Python modules are two mechanisms that allow for modular programming in Python. Modularizing ahs 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 similary 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.

Note: You can technically import the package as well, but alas, it doesn't import the modules within the package to the local namespace, thus, it is practically useless.

Answer:

  • 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.
  • Protected attributes are attributes defined with a 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.
  • Private attributes are attributes with double underscore prefixed to their identifier eg. __ansh. They cannot be accessed or modified from the outside directly and will result in an AttributeError if such an attempt is made.

Answer:

__init__ is a contructor method in Python and is automatically called to allocate memory when a new object/instance is created. All classes have a __init__ method associated with them. It helps in distinguishing methods and attributes of a class from local variables.
 

# class definition
class Student:
    def __init__(self, fname, lname, age, section):
        self.firstname = fname
        self.lastname = lname
        self.age = age
        self.section = section

# creating a new object
stu1 = Student("Sara", "Ansh", 22, "A2")
 

Answer:

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.
Pass As explained above, pass keyword in Python is generally used to fill-up empty blocks
and is similar to an empty statement represented by a semi-colon in languages such as Java, C++, Javascript etc.
 
pat = [1, 3, 2, 1, 2, 3, 1, 0, 1, 3]

for p in pat:
    pass
    if (p == 0):
        current = p
        break
    elif (p % 2 == 0):
        continue
    print(p)    # output => 1 3 1 3 1

print(current)    # output => 0
 

Answer:

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.

Answer:

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.

Answer:

  • .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.

Answer:

  • 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 official CPython, or JIT(Just in Time compiler) compiled by PyPy.

Answer:

  • unittest is a unit testing framework of Python.
  • Unit testing means testing different components of software separately. Can you think why unit testing is important? Imagine a scenario, you are building software which 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.

Answer:

  • 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.

Answer:

  • 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.

 

def appendNumber(arr):
    arr.append(4)

arr = [1, 2, 3]

print(arr)  #Output: => [1, 2, 3]
appendNumber(arr)
print(arr)  #Output: => [1, 2, 3, 4]

Answer:

  • Iterator is an object.
  • It remembers its state i.e., where it is during iteration (see code below to see how)
  • __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.
class ArrayList:
    def __init__(self, number_list):
        self.numbers = number_list

    def __iter__(self):
        self.pos = 0
        return self

    def __next__(self):
        if(self.pos < len(self.numbers)):
            self.pos += 1
            return self.numbers[self.pos - 1]
        else:
            raise StopIteration

array_obj = ArrayList([1, 2, 3])

it = iter(array_obj)

print(next(it)) #output: 2
print(next(it)) #output: 3

print(next(it))
#Throws Exception
#Traceback (most recent call last):
#...
#StopIteration
 

Answer:

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

Answer:

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

Answer:

  • You can use split() function to split a string based on a delimiter to a list of strings.
  • You can use 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.
 

Answer:

  • 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.
  • 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.
import array

a = array.array('i', [1, 2, 3])

for i in a:
     print(i, end=' ')    #OUTPUT: 1 2 3

a = array.array('i', [1, 2, 'string'])    #OUTPUT: TypeError: an integer is required (got type str)

a = [1, 2, 'string']

for i in a:
    print(i, end=' ')    #OUTPUT: 1 2 string

Answer:

*args

  • *args is a special syntax used in function definition to pass variable-length argument.
  • “*” means variable length and “args” is the name used by convention. You can use any other.
def multiply(a, b, *argv):
    mul = a * b

    for num in argv:
        mul *= num

    return mul

print(multiply(1, 2, 3, 4, 5)) #output: 120
 

**kwargs

  • **kwargs is a special syntax used in function definition to pass variable-length keyworded argument.
  • Here, also, “kwargs” is used just by convention. You can use any other name.
  • Keyworded argument means a variable which has a name when passed to a function.
  • It is actually a dictionary of variable name and its value.
def tellArguments(**kwargs):
    for key, value in kwargs.items():
        print(key + ": " + value)
tellArguments(arg1 = "argument 1", arg2 = "argument 2", arg3 = "argument 3")
#output:
# arg1: argument 1
# arg2: argument 2
# arg3: argument 3

Answer:

  • Negative indexes are the indexes from the end of the list or tuple or string.
  • Arr[-1] means last element of array Arr[]
arr = [1, 2, 3, 4, 5, 6]

#get the last element
print(arr[-1]) #output 6

#get the second last element
print(arr[-2]) #output 5
 

Answer:

  • Python uses private heaps to maintain its memory. So the heap holds all the Python objects and the data structures. This area is only accessible to the Python interpreter; programmers can’t use it.
  • And it’s the Python memory manager that handles the Private heap. It does the required allocation of the memory for Python objects.
  • Python employs a built-in garbage collector, which salvages all the unused memory and offloads it to the heap space.

Answer:

Lambda vs. def.

  • Def can hold multiple expressions while lambda is a uni-expression function.
  • Def generates a function and designates a name to call it later. Lambda forms a function object and returns it.
  • Def can have a return statement. Lambda can’t have return statements.
  • Lambda supports to get used inside a list and dictionary.

Answer:

Python has a regular expression module “re.”

Check out the “re” expression that can check the email id for .com and .co.in subdomain.

 

import re
print(re.search(r"[0-9a-zA-Z.]+@[a-zA-Z]+\.(com|co\.in)$","micheal.pages@mp.com"))

Answer:

No, Python does not have a Switch statement, but you can write a Switch function and then use it.

Answer:

Range() generates a list of numbers, which is used to iterate over for loops
 

for i in range(5):
    print(i)
 

The range() function accompanies two sets of parameters.

  • range(stop)
    • stop: It is the no. of integers to generate and starts from zero. eg. range(3) == [0, 1, 2].
  • range([start], stop[, step])
    • Start: It is the starting no. of the sequence.
    • Stop: It specifies the upper limit of the sequence.
    • Step: It is the incrementing factor for generating the sequence.
  • Points to note:
    • Only integer arguments are allowed.
    • Parameters can be positive or negative.
    • The range() function in Python starts from the zeroth index.

Answer:

There are two optional clauses you can use in the try-except block.

  • The “else” clause
    • It is useful if you want to run a piece of code when the try block doesn’t create an exception.
  • The “finally” clause
    • It is useful when you want to execute some steps which run, irrespective of whether there occurs an exception or not.

Answer:

A string in Python is a sequence of alpha-numeric characters. They are immutable objects. It means that they don’t allow modification once they get assigned a value. Python provides several methods, such as join(), replace(), or split() to alter strings. But none of these change the original object.

Answer:

Python has support for formatting any value into a string. It may contain quite complex expressions.

One of the common usages is to push values into a string with the %s format specifier. The formatting operation in Python has the comparable syntax as the C function printf() has.

Answer:

Python strings are indeed immutable.

Let’s take an example. We have an “str” variable holding a string value. We can’t mutate the container, i.e., the string, but can modify what it contains that means the value of the variable.

Answer:

An index is an integer data type which denotes a position within an ordered list or a string.

In Python, strings are also lists of characters. We can access them using the index which begins from zero and goes to the length minus one.

For example, in the string “Program,” the indexing happens like this:

 

Program 0 1 2 3 4 5

Answer:

A function is an object which represents a block of code and is a reusable entity. It brings modularity to a program and a higher degree of code reusability.

Python has given us many built-in functions such as print() and provides the ability to create user-defined functions.

Answer:

We can create a Python function in the following manner.

Step-1: to begin the function, start writing with the keyword def and then mention the function name.

Step-2: We can now pass the arguments and enclose them using the parentheses. A colon, in the end, marks the end of the function header.

Step-3: After pressing an enter, we can add the desired Python statements for execution.

Answer:

A function in Python gets treated as a callable object. It can allow some arguments and also return a value or multiple values in the form of a tuple. Apart from the function, Python has other constructs, such as classes or the class instances which fits in the same category.

Answer:

The purpose of a function is to receive the inputs and return some output.

The return is a Python statement which we can use in a function for sending a value back to its caller.

Answer:

In call-by-value, the argument whether an expression or a value gets bound to the respective variable in the function.

Python will treat that variable as local in the function-level scope. Any changes made to that variable will remain local and will not reflect outside the function.

Answer:

The Python trunc() function performs a mathematical operation to remove the decimal values from a particular expression and provides an integer value as its output.

Answer:

It is not at all necessary for a function to return any value. However, if needed, we can use None as a return value.

Answer:

The continue is a jump statement in Python which moves the control to execute the next iteration in a loop leaving all the remaining instructions in the block unexecuted.

The continue statement is applicable for both the “while” and “for” loops.

Answer:

The id() is one of the built-in functions in Python.
 

Signature: id(object)
It accepts one parameter and returns a unique identifier associated with the input object.

Answer:

The main() is the entry point function which happens to be called first in most programming languages.

Since Python is interpreter-based, so it sequentially executes the lines of the code one-by-one.

Python also does have a Main() method. But it gets executed whenever we run our Python script either by directly clicking it or starts it from the command line.

We can also override the Python default main() function using the Python if statement. Please see the below code.
 

print("Welcome")
print("__name__ contains: ", __name__)
def main():
    print("Testing the main function")
if __name__ == '__main__':
    main()
The output:
Welcome
__name__ contains:  __main__
Testing the main function
 

Answer:

The __name__ is a unique variable. Since Python doesn’t expose the main() function, so when its interpreter gets to run the script, it first executes the code which is at level 0 indentation.

To see whether the main() gets called, we can use the __name__ variable in an if clause compares with the value “__main__.”

Answer:

Python’s print() function always prints a newline in the end. The print() function accepts an optional parameter known as the ‘end.’ Its value is ‘\n’ by default. We can change the end character in a print statement with the value of our choice using this parameter.

# Example: Print a  instead of the new line in the end.
print("Let's learn" , end = ' ')  
print("Python") 

# Printing a dot in the end.
print("Learn to code from techbeamers" , end = '.')  
print("com", end = ' ')
The output is:
Let's learn Python
Learn to code from techbeamers.com
 

Answer:

In Python, the len() is a primary string function. It determines the length of an input string.

>>> some_string = 'techbeamers'
>>> len(some_string)
11
 

Answer:

The chr() function got re-added in Python 3.2. In version 3.0, it got removed.

It returns the string denoting a character whose Unicode code point is an integer.

For example, the chr(122) returns the string ‘z’ whereas the chr(1212) returns the string ‘?’.

Answer:

The ord(char) in Python takes a string of size one and returns an integer denoting the Unicode code format of the character in case of a Unicode type object, or the value of the byte if the argument is of 8-bit string type.

>>> ord("z")
122
 

Answer:

Python provides the rstrip() method which duplicates the string but leaves out the whitespace characters from the end.

The rstrip() escapes the characters from the right end based on the argument value, i.e., a string mentioning the group of characters to get excluded.

The signature of the rstrip() is:
 

str.rstrip([char sequence/pre>


#Example
test_str = 'Programming    '
# The trailing whitespaces are excluded
print(test_str.rstrip())

Answer:

Python provides this built-in isalpha() function for the string handling purpose.

It returns True if all characters in the string are of alphabet type, else it returns False.

Answer:

Python’s split() function works on strings to cut a large piece into smaller chunks, or sub-strings. We can specify a separator to start splitting, or it uses the space as one by default.

#Example
str = 'pdf csv json'
print(str.split(" "))
print(str.split())
The output:
['pdf', 'csv', 'json']
['pdf', 'csv', 'json']
 

Answer:

Python provides the join() method which works on strings, lists, and tuples. It combines them and returns a united value.

Answer:

Python provides the title() method to convert the first letter in each word to capital format while the rest turns to Lowercase.

#Example
str = 'lEaRn pYtHoN'
print(str.title())
The output:
Learn Python
Now, check out some general purpose Python interview questions.

Answer:

CPython has its core developed in C. The prefix ‘C’ represents this fact. It runs an interpreter loop used for translating the Python-ish code to C language.

Answer:

PyPy provides maximum compatibility while utilizing CPython implementation for improving its performance.

The tests confirmed that PyPy is nearly five times faster than the CPython. It currently supports Python 2.7.

Answer:

Python supports GIL (the global interpreter lock) which is a mutex used to secure access to Python objects, synchronizing multiple threads from running the Python bytecodes at the same time.

Answer:

ython ensures safe access to threads. It uses the GIL mutex to set synchronization. If a thread loses the GIL lock at any time, then you have to make the code thread-safe.

For example, many of the Python operations execute as atomic such as calling the sort() method on a list.

Answer:

A dictionary is a data structure known as an associative array in Python which stores a collection of objects.

The collection is a set of keys having a single associated value. We can call it a hash, a map, or a hashmap as it gets called in other programming languages.

Answer:

Sets are unordered collection objects in Python. They store unique and immutable objects. Python has its implementation derived from mathematics.

Answer:

A dictionary has a group of objects (the keys) map to another group of objects (the values). A Python dictionary represents a mapping of unique Keys to Values.

They are mutable and hence will not change. The values associated with the keys can be of any Python types.

Answer:

A Python list is a variable-length array which is different from C-style linked lists.

Internally, it has a contiguous array for referencing to other objects and stores a pointer to the array variable and its length in the list head structure.

Here are some Python interview questions on classes and objects.

Answer:

Python supports object-oriented programming and provides almost all OOP features to use in programs.

A Python class is a blueprint for creating the objects. It defines member variables and gets their behavior associated with them.

We can make it by using the keyword “class.” An object gets created from the constructor. This object represents the instance of the class.

In Python, we generate classes and instances in the following way.
 

>>>class Human:  # Create the class
...     pass
>>>man = Human()  # Create the instance
>>>print(man)
<__main__.Human object at 0x0000000003559E10>

Answer:

A class is useless if it has not defined any functionality. We can do so by adding attributes. They work as containers for data and functions. We can add an attribute directly specifying inside the class body.
 

>>> class Human:
...     profession = "programmer" # specify the attribute 'profession' of the class
>>> man = Human()
>>> print(man.profession)
programmer
After we added the attributes, we can go on to define the functions. Generally, we call them methods. In the method signature, we always have to provide the first argument with a self-keyword.
>>> class Human:
    profession = "programmer"
    def set_profession(self, new_profession):
        self.profession = new_profession      
>>> man = Human()
>>> man.set_profession("Manager")
>>> print(man.profession)
Manager
 

Answer:

We can specify the values for the attributes at runtime. We need to add an init method and pass input to object constructor. See the following example demonstrating this.
 

>>> class Human:
    def __init__(self, profession):
        self.profession = profession
    def set_profession(self, new_profession):
        self.profession = new_profession

>>> man = Human("Manager")
>>> print(man.profession)
Manager
 

Answer:

Inheritance is an OOP mechanism which allows an object to access its parent class features. It carries forward the base class functionality to the child.

We do it intentionally to abstract away the similar code in different classes.

The common code rests with the base class, and the child class objects can access it via inheritance. Check out the below example.
 

class PC: # Base class
    processor = "Xeon" # Common attribute
    def set_processor(self, new_processor):
        processor = new_processor

class Desktop(PC): # Derived class
    os = "Mac OS High Sierra" # Personalized attribute
    ram = "32 GB"

class Laptop(PC): # Derived class
    os = "Windows 10 Pro 64" # Personalized attribute
    ram = "16 GB"

desk = Desktop()
print(desk.processor, desk.os, desk.ram)

lap = Laptop()
print(lap.processor, lap.os, lap.ram)
The output:
Xeon Mac OS High Sierra 32 GB
Xeon Windows 10 Pro 64 16 GB
 

Answer:

The composition is also a type of inheritance in Python. It intends to inherit from the base class but a little differently, i.e., by using an instance variable of the base class acting as a member of the derived class.
To demonstrate composition, we need to instantiate other objects in the class and then make use of those instances

class PC: # Base class
    processor = "Xeon" # Common attribute
    def __init__(self, processor, ram):
        self.processor = processor
        self.ram = ram

    def set_processor(self, new_processor):
        processor = new_processor

    def get_PC(self):
        return "%s cpu & %s ram" % (self.processor, self.ram)

class Tablet():
    make = "Intel"
    def __init__(self, processor, ram, make):
        self.PC = PC(processor, ram) # Composition
        self.make = make

    def get_Tablet(self):
        return "Tablet with %s CPU & %s ram by %s" % (self.PC.processor, self.PC.ram, self.make)

if __name__ == "__main__":
    tab = Tablet("i7", "16 GB", "Intel")
    print(tab.get_Tablet())
The output is:
Tablet with i7 CPU & 16 GB ram by Intel