Softpro India
Python is the most desirable talent in the programming field. Python Interview Questions and Answers are presenting you to the frequently-posted questions in Python interviews. Our Python Interview Questions is an outstanding store for anyone who is in need to boost the interview preparation. Hundred plus questions on Python Programming are posted by our experts and Python skilled professionals that help with various expertise levels to gain the supreme advantage from our blog. We have designed with a special purpose of serving students and experts who are preparing for numerous Python Certification Exams and Interviews. Engineers, IT Professionals, Sales, and Marketing employees, and Software Developers can make use of this questionnaire to excel in Python career.
Here is the list of most frequently asked Python Interview Questions and Answers in technical interviews. These questions and answers are suitable for both freshers and experienced professionals at any level. The questions are for intermediate to somewhat advanced Networking professionals, but even if you are just a beginner or fresher you should be able to understand the answers and explanations here we give.
Python Interview Questions and Answers for beginners and experts. List of frequently asked Python Interview Questions with answers by Softpro India. We hope these Python interview questions and answers are useful and will help you to get the best job in the networking industry. This Python interview questions and answers are prepared by Python Professionals based on MNC Companies expectation. Stay tune we will update New Python Interview questions with Answers Frequently. If you want to learn Practical Python Training then please Join our Python training in Lucknow & Python training in Uttar Pradesh..
Besant Technologies supports the students by providing Python interview questions and answers for the job placements and job purposes. Python is the leading important course in the present situation because more job openings and the high salary pay for this Python and more related jobs. We provide the Python online training also for all students around the world through the Gangboard medium. These are top Python interview questions and answers, prepared by our institute experienced trainers.
Python, a programming language that has modules, threads, automatic memory management, objects, and exceptions. Pythons are easy and simple to use, open-source, extensible, transferrable, and build-in data structure.
Two memory-efficient ways in ranked order (first is best) –
Advantages:
def readInChunks(file obj, chunkSize=2048): “”” Lazy function to read a file piece by piece. Default chunk size: 2kB. “”” while True: data = fileObj.read(chunkSize) if not data: break yield data f = open(‘bigFile’) for chuck in readInChunks(f): do_something(chunk) f.close()
The <__init__.py> module can help in fulfilling the following objectives.
We can either use a “Shallow Copy” or follow a “Deep Copy” approach. Shallow Copy method. The content of an object (say dictionary) doesn’t get copied by value but by creating a new reference.
SHALLOW COPY METHOD.
>> a = {1: [1,2,3]} >>> b = a.copy() >>> a, b ({1: [1, 2, 3]}, {1: [1, 2, 3]}) >>> a[1].append(4) >>> a, b ({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]}) 1 2 3 4 5 6 7 >>> a = {1: [1,2,3]} >>> b = a.copy() >>> a, b ({1: [1, 2, 3]}, {1: [1, 2, 3]}) >>> a[1].append(4) >>> a, b ({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})
DEEP COPY METHOD.
It copies all the contents by value.
>> c = copy.deepcopy(a) >>> a, c ({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]}) >>> a[1].append(5) >>> a, c ({1: [1, 2, 3, 4, 5]}, {1: [1, 2, 3, 4]}) 1 2 3 4 5 6 >>> c = copy.deepcopy(a) >>> a, c ({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]}) >>> a[1].append(5) >>> a, c ({1: [1, 2, 3, 4, 5]}, {1: [1, 2, 3, 4]})
You can use a global variable in other functions by declaring it as global in each function that assigns to it:
globvar = 0 def set_globvar_to_one(): global globvar # Needed to modify global copy of globvar globvar = 1 def print_globvar(): print globvar # No need for global declaration to read value of globvar set_globvar_to_one() print_globvar() # Prints 1 1 2 3 4 5 6 7 8
I imagine the reason for it is that, since global variables are so dangerous, Python wants to make sure that you really know that’s what you’re playing with by explicitly requiring the global keyword.
Python has an interesting for statement which lets you specify an else suite.
In a construct like this one:
for i in foo: if bar(i): break else: baz()
the else suite is executed after the for, but only if the for terminates normally (not by a break).
Here’s some code written without for…else:
def contains_even_number(l): “Prints whether or not the list l contains an even number.” has_even_number = False for elt in l: if elt % 2 == 0: has_even_number = True break if has_even_number: print “list contains an even number” else: print “list does not contain an even number”
The equivalent code snippet below illustrates how the use of for…else lets you remove an extraneous flag variable from that loop:
def contains_even_number(l): “Prints whether or not the list l contains an even number.” for elt in l: if elt % 2 == 0: print “list contains an even number” break else: print “list does not contain an even number”
Use your good judgment when deciding whether to use the for…else construct. It’s not unequivocally better, but when there’s an asymmetry between the two possibilities, you can make your code more readable by using for…else to keep the “happy path” logic at the top and the exceptional/error case at the bottom.
Iterator objects in python conform to the iterator protocol, which basically means they provide two methods:
__iter__() and next().The __iter__ returns the iterator object and is implicitly called at the start of loops. The next() method returns the next value and is implicitly called at each loop increment. next() raises a StopIteration exception when there is no more value to return, which is implicitly captured by looping constructs to stop iterating. Here’s a simple example of a counter:
class Counter: def __init__(self, low, high): self.current = low self.high = high def __iter__(self): return self def next(self): # Python 3: def __next__(self) if self.current > self.high: raise StopIteration else: self.current += 1 return self.current – 1 for c in Counter(3, 8): print c This will print: 3 4 5 6 7 8
You could except the ImportError exception: try: from Pyside2 import QtCore, QtGui except ImportError: from PySide import QtCore, QtGui Alternatively, you can use the importlib module: import importlib import sys PySide = importlib.import_module(‘Pyside2’ if ‘Pyside2’ in sys.modules else ‘PySide’)
object created of that class. USING STATIC METHOD.
class Base: numOfInstances = 0 def __init__(self): Base.numOfInstances += 1 def getNumInstances(): print Base.numOfInstances # Using python built-in staticmethod, @decoration symbol also can be used getNumInstances = staticmethod(getNumInstances) b1 = Base() b1.getNumInstances() # It should print 1 b2 = Base() b2.numOfInstances = 15 b1.getNumInstances() # It should print 2 b2.getNumInstances() #It should print 2
Let’s extend the Base class and see what happens –
class Base: numOfInstances = 0 def __init__(self): Base.numOfInstances += 1 def getNumInstances(): print Base.numOfInstances # Using python built-in staticmethod,@decoration symbol also can be used getNumInstances =staticmethod(getNumInstances) class Derived(Base): numOfInstances = 0 def __init__(self): Derived.numOfInstances +=1 b1 = Base() d1 = Derived() d2 = Derived() d1.getNumInstances() #It’s printing 1 But we have created 2 instances of Derived Derived.getNumInstances() #It’s printing 1 But we have created 2 instances of Derived
We shouldn’t use the static method
class Base: numOfInstances = 0 def __init__(self): Base.numOfInstances += 1 def getNumInstances(): print Base.numOfInstances getNumInstances = staticmethod(getNumInstances) class Derived(Base): def __init__(self): Base.__init__(self) b1 = Base() d1 = Derived() d2 = Derived() d1.getNumInstances() #It should print 3 Base.getNumInstances() #It should print 3
class Base: numOfInstances = 0 def countInstances(cls): cls.numOfInstances += 1 countInstances = classmethod(countInstances) def getNumInstances(cls): print cls.numOfInstances getNumInstances = classmethod(getNumInstances) def __init__(self): self.countInstances() class Derived(Base): numOfInstances = 0 def __init__(self): Base.__init__() # Why we call explicitly to super class’s __init__ ?? #people from c++ background who already know oops, We will talk about operator overloading in another article b1 = Base() b2 = Base() d1 = Derived() d2 = Derived() d3 = Derived() b1.getNumInstances() Base.getNumInstances() #Both should print 2 d1.getNumInstances() Derived.getNumInstances() #Both should print 3
Both are used to read the content from the file but in different ways. f.read() reads the whole file as an individual string and allows relatively easy file-wide manipulations, such as a file-wide regex search or substitution.
If file xyz.py contains text
“`def print_triangle(n): for x in range(1, n + 1): num_list = [str(num % 10) for num in range(x, 2*x)]“` If i write below code with open(‘xyz.py’, ‘r’) as f: print f.read() The o/p will be whole file >>> def print_triangle(n): for x in range(1, n + 1): num_list = [str(num % 10) for num in range(x, 2*x)] f.readline() reads a single line of the file, allowing the user to parse a single line without reading the entire file. If i use only readline() with open(‘xyz.py’, ‘r’) as f: print f.readline() The o/p will be whole file >>> def print_triangle(n):
You can trigger an exception in your Python script in the following ways.
raise – it is used to manually raise an exception:
raise exception-name (“message”)
Example:
> voting_age = 15
>>> if voting_age < 18: raise ValueError(“voting age should be atleast 18 and above”)
Output
ValueError: voting age should be at least 18 and above
assert statement assert statements are used to tell your program to test that condition attached to assert keyword, and trigger an exception whenever the condition becomes false.
Example:
>>> a = -10
>>> assert a > 0 #to raise an exception whenever a is a negative number
Output
AssertionError
Another way of raising and exception can be done by making a programming mistake, but that’s not usually a good way of triggering an exception.
If class A is a subclass of class B, then everything in B is accessible in /by class A. In addition, class A can define methods that are unavailable in B, and also it is able to override methods in B. For Instance, If class B and class A both contain a method called func(), then func() in class B can override func() in class A. Similarly, a method of class A can call another method defined in A that can invoke a method of B that overrides it.
We can either use a “Shallow Copy” or follow a “Deep Copy” . Shallow Copy method. The content of an object (say dictionary)doesn’t get copied by value but by creating a new reference.
SHALLOW COPY METHOD.
> a = {1: [1,2,3]} >>> b = a.copy() >>> a, b ({1: [1, 2, 3]}, {1: [1, 2, 3]}) >>> a[1].append(4) >>> a, b ({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]}) 1 2 3 4 5 6 7 >>> a = {1: [1,2,3]} >>> b = a.copy() >>> a, b ({1: [1, 2, 3]}, {1: [1, 2, 3]}) >>> a[1].append(4) >>> a, b ({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})
DEEP COPY METHOD.
It copies all the contents by value. >>> c = copy.deepcopy(a) >>> a, c ({1: [1, 2, 3, 4]}, {1: [1, ” open=”no” style=”default” icon=”plus” anchor=”” class=””]2, 3, 4]}) >>> a[1].append(5) >>> a, c ({1: [1, 2, 3, 4, 5]}, {1: [1, 2, 3, 4]}) 1 2 3 4 5 6 >>> c = copy.deepcopy(a) >>> a, c ({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]}) >>> a[1].append(5) >>> a, c ({1: [1, 2, 3, 4, 5]}, {1: [1, 2, 3, 4]})
Python does not provide interfaces like in Java. Abstract Base Class (ABC) and its features are provided by the Python’s “abc” module. Abstract Base Class is a mechanism for specifying what methods must be implemented by its implementation subclasses. The use of ABC’ provides a sort of “understanding” about methods and their expected behavior. This module was made available from Python 2.7 version onwards.
Python has a for syntax which can be combined with else syntax.
for i in foo: if bar(i): break else: baz()
the else suite is executed after the for, but only if the for terminates normally.
Here’s code is written without for…else:
def contains_even_number(l): “Prints whether or not the list l contains an even number.” has_even_number = False for elt in l: if elt % 2 == 0: has_even_number = True break if has_even_number: print “list contains an even number” else: print “list does not contain an even number”
The equivalent code snippet below illustrates how the use of for…else lets you remove flag variable from that loop:
def contains_even_number(l): “Prints whether or not the list l contains an even number.” for elt in l: if elt % 2 == 0: print “list contains an even number” break else: print “list does not contain an even number”
Use your good judgment when deciding whether to use the for else construct.When there’s an asymmetry between the two possibilities, you can make the code more readable by using for…else to keep the exceptional/error case at the bottom.
Accessors and mutators are called getters and setters in language like “Java”. For example, if x is a property of a user-defined class, then the class would have methods called setX() and getX(). Python has @property “decorator” that allows you to add getters and setters to access the attribute of the class.
since class C does not contain the definition of the method func(), they Python searches for the func() in parent classes. As the search is performed in a left-to-right fashion, Python executes the method func() which is present in class A and not the func() method in B.
USING STATIC METHOD.
class Base: numOfInstances = 0 def __init__(self): Base.numOfInstances += 1 def getNumInstances(): print Base.numOfInstances # Using python built-in staticmethod,@decoration symbol also can be used getNumInstances = staticmethod(getNumInstances) b1 = Base() b1.getNumInstances() # It should print 1 b2 = Base() b2.numOfInstances = 15 b1.getNumInstances() # It should print 2 b2.getNumInstances() #It should print 2
Lets extend Base class and see what happens –
class Base: numOfInstances = 0 def __init__(self): Base.numOfInstances += 1 def getNumInstances(): print Base.numOfInstances # Using python built-in staticmethod, @decoration symbol also can be used getNumInstances = staticmethod(getNumInstances) class Derived(Base): numOfInstances = 0 def __init__(self): Derived.numOfInstances +=1 b1 = Base() d1 = Derived() d2 = Derived() d1.getNumInstances() #It’s printing 1 But we have created 2 instances of Derived Derived.getNumInstances() #It’s printing 1 But we have created 2 instances of Derived
We shouldn’t use static method –
You can use the static method if it is not acting on any data or a method that can be used by all the instances and all the classes in the hierarchy. Static Method is used if the Base class needs to keep count of instances of all it’s subclass too.
Class Base: numOfInstances = 0 def __init__(self): Base.numOfInstances += 1 def getNumInstances(): print Base.numOfInstances getNumInstances = staticmethod(getNumInstances) class Derived(Base): def __init__(self): Base.__init__(self) b1 = Base() d1 = Derived() d2 = Derived() d1.getNumInstances() #It should print 3 Base.getNumInstances() #It should print 3
USING CLASS METHOD:
class Base: numOfInstances = 0 def countInstances(cls): cls.numOfInstances += 1 countInstances = classmethod(countInstances) def getNumInstances(cls): print cls.numOfInstances getNumInstances = classmethod(getNumInstances) def __init__(self): self.countInstances() class Derived(Base): numOfInstances = 0 def __init__(self): Base.__init__() b1 = Base() b2 = Base() d1 = Derived() d2 = Derived() d3 = Derived() b1.getNumInstances() Base.getNumInstances() #Both should print 2 d1.getNumInstances() Derived.getNumInstances() #Both should print 3
Q21. Given a list and a number find two numbers in the list that sums up to the number given?” open=”no” style=”default” icon=”plus” anchor=”” class=””]
a = [1,2,3,4,5,6,8] given_no = 9 mm = [] count =0 for x,y in enumerate(a): for j in range(x+1, len(a)): total_of_two_items = a[x] + a[j] if total_of_two_items == given_no: mm.append((a[x],a[j])) print mm
list, dict, set, byte array Immutable :
int, float, complex, string, tuple, frozen set ,bytes x = 10 x = y
We are creating an object of type int. identifiers x and y points to the same object.
id(x) == id(y) id(y) == id(10) if we do a simple operation. x = x + 1 Now id(x) != id(y) id(x) != id(10)
The object x is changed. object 10 was never modified. Immutable objects does not allow modification after creation of objects.
In the case of mutable objects-
m = list([1, 2, 3]) n = m
We are creating an object of type list. identifiers m and m tagged to the same list object, which is a collection of 3 immutable int objects.
id(m) == id(n)
Now pop an item from list does change the object, m.pop() object id will not be changed id(m) == id(n) m and n are pointing to the same list object after the modification. The list object will be [1, 2].Python handles mutable and immutable objects differently. Immutable are quicker to access than mutable objects.
Two memory efficient ways in ranked order (first is best) –
advantages
with open(“x.txt”) as f: for line in f:
do something with data. The with statement handles opening and closing the file and also if an exception is raised in the inner block. The for line in f is the file object f as an iterable, which automatically uses buffered IO and memory management so you don’t have to worry about large files.
USE OF YIELD
Sometimes one might want more fine-grained control over how much to read in each iteration. In that case use iter & yield. Note with this method one explicitly needs close the file at the end.
def readInChunks
(fileObj, chunkSize=2048): “”” Lazy function to read a file piece by piece. Default chunk size: 2kB. “”” while True: data = fileObj.read(chunkSize) if not data: break yield data f = open(‘bigFile’) for chuck in readInChunks(f): do_something(chunk) f.close()
The <__init__.py> module can help in fulfilling following objectives.
Python has two built-in functions that work with inheritance:
For example you could except the Import Error exception: try: from Pyside2 import QtCore, QtGui except ImportError: from PySide import QtCore, QtGui Alternatively, you can use the importlib module: import importlib import sys PySide = importlib.import_module(‘Pyside2’ if ‘Pyside2’ in sys.modules else ‘PySide’)
Both .py and .pyc files hold the byte code. “.pyc” is a compiled version of the Python file. This file is automatically generated by Python to improve performance. The .pyc file is having bytecode which is platform-independent. It can be executed on any operating system that supports a .pyc format.
Note: there is no difference in speed when a program is read from .pyc or .py file; the only difference is the load time.
Import MySQLdb module as : import MySQLdb Establish a connection to the database. db = MySQLdb.connect(“host”=”local host”, “database-user”=”user-name”, “password”=”password”, “database-name”=”database”) Initialize the cursor variable upon the established connection: c1 = db.cursor() Retrieve the information by defining a required query string. s = “Select * from dept” Fetch the data using fetch() methods and print it. data = c1.fetch(s) Close the database connection. db.close()
ODBC (“Open Database Connectivity) API standard allows the connections with any database that supports the interface, such as PostgreSQL database or Microsoft Access in a transparent manner.
There are 3 ODBC modules for Python:
All the members of a class are public by default in Python. You don’t need to define an access specifier for members of the class. By adding `_` as the prefix to the member of a class. By adding this convention you are telling others please don’t use this object, if you are not a subclass the respective class.
Example:
class Person:
empid = None
_salary = None #salary is a protected member & it can accessible by the subclasses of Person
Example:
>>>help(str) or
>>>help() – it will open the prompt for help as help>
to view help for a module, help> module module name Inorder to view the documentation of ‘str’ at the help>, type help>modules str
to view help for a keyword, topics, you need to type, help> “keywords python-keyword” and “topics list”
dir() – will display the defined symbols.
Ex: >>>dir(str) – will only display the defined symbols.
<The answer is No. So the builtin functions for eg max(), min(), filter(), map(), etc they are functions of standard module.To view them, we can pass the module ” builtins ” as an argument to “dir()”. It will display the all builtin exceptions, functions, and other objects as a list. For eg, >>dir(__builtins ) [‘AssertionError’,‘ArithmeticError’, ‘AttributeError’, ……… ]
Iterator objects in python conform to the iterator protocol, which basically means they provide two methods:
__iter__() and next().The __iter__ returns the iterator object and is implicitly called at the start of loops. The next() method returns the next value and is implicitly called at each loop increment. next() raises a StopIteration exception when there are no more value to return, which is implicitly captured by looping constructs to stop iterating.
Here’s a simple example of a counter:
Class Counter: def __init__(self, low, high): self.current = low self.high = high def __iter__(self): return self def next(self): # Python 3: def __next__(self) if self.current > self.high: raise StopIteration else: self.current += 1 return self.current – 1 for c in Counter(3, 8): print c This will print: 3 4 5 6 7 8
Whenever Python exists, especially those python modules which are having circular references to other objects or the objects that are referenced from the global namespaces are not always deallocated/freed/uncollectable. It is not possible to deallocate those parts of memory that are reserved/booked by libraries in C. On exit, because of having its own efficient deallocation mechanism, Python would try to deallocate/ destroy every object.
zip() function- it will take multiple lists say list1, list2, etc and convert them into a single list of tuples by taking their corresponding elements of the lists that are passed as parameters.
Example:
list1 = [‘A’, ‘B’,’C’] and list2 = [10,20,30]. zip(list1, list2) # results in a list of tuples say [(‘A’,10),(‘B’,20),(‘C’,30)]
whenever the given lists are of different lengths, zip stops generating tuples when the first list ends.
import copy x = 645 y = 666 dig1 = list(str(x)) dig2 = list(str(y)) bb = [] vv = [] for i,j in enumerate(dig1): temp1 = [] if j == ‘5’ or j == ‘6’: temp1 = copy.deepcopy(dig1) if j == ‘5’: temp1[i] = ‘6’ else: temp1[i] = ‘5’ bb.append(”.join(temp1)) for k,l in enumerate(dig2): temp2 = [] if l == ‘5’ or l == ‘6’: temp2 = copy.deepcopy(dig2) if l == ‘5’: temp1[k] = ‘6’ else: temp1[k] = ‘5’ vv.append(”.join(temp2)) nn = zip(bb,vv) aa = [] for no in nn: temp = list(no) aa.append(int(temp[0])+int(temp[1])) print aa print “max=” + str(max(aa)) print “min=” + str(min(aa))
In Python, by default, all the parameters (arguments) are passed “by reference” to the functions. Thus, if you change the value of the parameter within a function, the change is reflected in the calling function.
We can see the pass “by value” kind of a behaviour every time we pass arguments to the functions that are of type say strings, numbers, tuples. This is because of the immutable nature of them.
This is how you can overload the constructors Python constructor – _init__ () is a first method of a class. Every time we try to instantiate an object __init__() is automatically invoked by
python to initialize members of an object.
The shortest way to open a text file is by using “with” command as follows:
with open(“file-name”, “r”) as fp: fileData = fp.read() #to print the contents of the file print(fileData)
This particular function takes the name of a directory and prints the paths files within that directory as well as any files contained in the contained directories.
This function is similar to os.walk. Please don’t use os.walk in your answer. We are interested in your ability to work with nested structures.
fill_this_in Answer
def print_directory_contents(sPath):
import os
for sChild in os.listdir(sPath):
sChildPath = os.path.join(sPath,sChild)
if os.path.isdir(sChildPath):
print_directory_contents(sChildPath)
else:
print(sChildPath)
A0 = dict(zip((‘a’,’b’,’c’,’d’,’e’),(1,2,3,4,5))) =======> {‘a’: 1, ‘c’: 3, ‘b’: 2, ‘e’: 5, ‘d’: 4}
zip((‘a’,’b’,’c’,’d’,’e’),(1,2,3,4,5)) ==========> [(‘a’, 1), (‘b’, 2), (‘c’, 3), (‘d’, 4), (‘e’, 5)] dict(zip((‘a’,’b’,’c’,’d’,’e’),(1,2))) =======> {‘a’: 1, ‘b’: 2}
A1 =range(10) ========> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] A2 =sorted([i for i in A1 if i in A0])========> [] A3 =sorted([A0[s] for s in A0])========> [1, 3, 2, 5, 4] A4 =[i for i in A1 if i in A3]========> [1, 2, 3, 4, 5] A5 ={i:i*i for i in A1}========> {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
A6 =[[i,i*i] for i in A1]========> [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]
We can use *args when we are not sure how many args we are going to pass to a function. We can also use if we want to pass a stored list or tuple of arguments to a function. **kwargs is used when we don’t know how many keyword arguments will
be passed to a function, or it can be used to pass the values of a dictionary as keyword arguments. The *args and **kwargs are a convention.You can also use *abc and **wxyz .
Below is the Eg:
def f(*args,**kwargs): print(args, kwargs)
l = [1,2,3] t = (4,5,6)
d = {‘a’:7,’b’:8,’c’:9}
f()f(1,2,3)
# (1, 2, 3) {}
f(1,2,3,”groovy”)
# (1, 2, 3, ‘groovy’) {}
f(a=1,b=2,c=3)
# () {‘a’: 1, ‘c’: 3, ‘b’: 2}
f(a=1,b=2,c=3,zzz=”hi”)
# () {‘a’: 1, ‘c’: 3, ‘b’: 2, ‘zzz’: ‘hi’}
f(1,2,3,a=1,b=2,c=3)
# (1, 2, 3) {‘a’: 1, ‘c’: 3, ‘b’: 2}
f(*l,**d)
# (1, 2, 3) {‘a’: 7, ‘c’: 9, ‘b’: 8}
f(*t,**d)
# (4, 5, 6) {‘a’: 7, ‘c’: 9, ‘b’: 8}
f(1,2,*t)
# (1, 2, 4, 5, 6) {}
f(q=”winning”,**d)
# () {‘a’: 7, ‘q’: ‘winning’, ‘c’: 9, ‘b’: 8}
f(1,2,*t,q=”winning”,**d) # (1, 2, 4, 5, 6) {‘a’: 7, ‘q’: ‘winning’, ‘c’: 9, ‘b’: 8}
def f2(arg1,arg2,*args,**kwargs): print(arg1,arg2, args, kwargs)
f2(1,2,3)
# 1 2 (3,) {}
f2(1,2,3,”groovy”)
# 1 2 (3, ‘groovy’) {}
f2(arg1=1,arg2=2,c=3)
# 1 2 () {‘c’: 3}
f2(arg1=1,arg2=2,c=3,zzz=”hi”) # 1 2 () {‘c’: 3, ‘zzz’: ‘hi’}
f2(1,2,3,a=1,b=2,c=3)
# 1 2 (3,) {‘a’: 1, ‘c’: 3, ‘b’: 2}
f2(*l,**d)
# 1 2 (3,) {‘a’: 7, ‘c’: 9, ‘b’: 8}
f2(*t,**d)
# 4 5 (6,) {‘a’: 7, ‘c’: 9, ‘b’: 8}
f2(1,2,*t)
# 1 2 (4, 5, 6) {}
f2(1,1,q=”winning”,**d)
# 1 1 () {‘a’: 7, ‘q’: ‘winning’, ‘c’: 9, ‘b’: 8}
f2(1,2,*t,q=”winning”,**d) # 1 2 (4, 5, 6) {‘a’: 7, ‘q’: ‘winning’, ‘c’: 9, ‘b’: 8}
A decorator is a special kind of function that takes a function and returns a function, or takes a class and returns a class. The @ symbol is just syntax that allows you to decorate something in a way that’s easy to read.
@my_decorator
def my_func(stuff):
do_things
Is equivalent to
def my_func(stuff):
do_things
my_func = my_decorator(my_func)
Actual Answer
The decorators @classmethod, @staticmethod and @property are used on functions defined within classes. Here is how they behave:
class MyClass(object):
def __init__(self):
self._some_property = “properties are nice”
self._some_other_property = “VERY nice”
def normal_method(*args,**kwargs):print(“calling normal_method({0},{1})”.format(args,kwargs))
@classmethod
def class_method(*args,**kwargs):
print(“calling class_method({0},{1})”.format(args,kwargs))
@staticmethod
def static_method(*args,**kwargs):
print(“calling static_method({0},{1})”.format(args,kwargs))
@property
def some_property(self,*args,**kwargs):
print(“calling some_property getter({0},{1},{2})”.format(self,args,kwargs))
return self._some_property
@some_property.setter
def some_property(self,*args,**kwargs):
print(“calling some_property setter({0},{1},{2})”.format(self,args,kwargs))
self._some_property = args[0] @property
def some_other_property(self,*args,**kwargs):
print(“calling some_other_property getter({0},{1},{2})”.format(self,args,kwargs))
return self._some_other_property
o = MyClass()
o.normal_method
# <bound method MyClass.normal_method of <__main__.MyClass instance at 0x7fdd2537ea28>>
o.normal_method()
# normal_method((<__main__.MyClass instance at 0x7fdd2537ea28>,),{})
o.normal_method(1,2,x=3,y=4)
# normal_method((<__main__.MyClass instance at 0x7fdd2537ea28>, 1, 2),{‘y’: 4, ‘x’: 3})
# class methods always get the class ‘cls’ as the first argument
o.class_method
# <bound method classobj.class_method of <class __main__.MyClass at 0x7fdd2536a390>>
o.class_method()
# class_method((<class __main__.MyClass at 0x7fdd2536a390>,),{})
o.class_method(1,2,x=3,y=4)
# class_method((<class __main__.MyClass at 0x7fdd2536a390>, 1, 2),{‘y’: 4, ‘x’: 3})
# static methods have no arguments except the ones you pass in when you call them
o.static_method
# <function static_method at 0x7fdd25375848>
o.static_method()
# static_method((),{})
o.static_method(1,2,x=3,y=4)
# static_method((1, 2),{‘y’: 4, ‘x’: 3})
# properties are a way of implementing getters and setters. It is an error to call them explicitly
o.some_property
# calling some_property getter(<__main__.MyClass instance at 0x7fb2b70877e8>,(),{})
# ‘properties are nice’o.some_property()
# calling some_property getter(<__main__.MyClass instance at 0x7fb2b70877e8>,(),{})
# Traceback (most recent call last):
# File “<stdin>”, line 1, in <module>
# TypeError: ‘str’ object is not callable
o.some_other_property
# calling some_other_property getter(<__main__.MyClass instance at 0x7fb2b70877e8>,(),{})
# ‘VERY nice’
# o.some_other_property()
# calling some_other_property getter(<__main__.MyClass instance at 0x7fb2b70877e8>,(),{})
# Traceback (most recent call last):
# File “<stdin>”, line 1, in <module>
# TypeError: ‘str’ object is not callable
o.some_property = “groovy”
# calling some_property setter(<__main__.MyClass object at 0x7fb2b7077890>,(‘groovy’,),{})
o.some_property
# calling some_property getter(<__main__.MyClass object at 0x7fb2b7077890>,(),{})
# ‘groovy’
The object does not 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,it has the name of the object that has to be bound by a value. If the value is callable then the statements are made true.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 names are invoked by using the the variable B which creates an instance for the class try.
There is a builtin method which is 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 written as is instance(obj,cls) and in more details written as: isinstance(obj, (class1, class2, …)) it checks that the object’s presence in one of the classes. The built in types can also have many formats of the same function for eg isinstance(obj, str) or isinstance(obj, (int, long, float, complex)).
It is not preferred to use the class instead of user-defined class. These perform different thing that is 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.
The functions and the methods that are used for the functionality uses the string module.
This is represented as by using the join function in it:
“, “.join([‘1’, ‘2’, ‘4’, ‘8’, ’16’]) that results in “1, 2, 4, 8, 16”
The string var that is used provide a fixed string to allow the names that are used to be bounded to the strings. join() is a string method that is used to provide a separator string to use the function over the sequence of the string and insert the function to an adjacent elements.
This method uses any number of args that follow some rules. The ‘join’ is used for string module that is used to join the string characters together.
For Eg: string.join([‘1’, ‘2’, ‘4’, ‘8’, ’16’], “, “)
The steps which are required to make any script executable are to:
First create a script file and write the code that has to be executed in it.
We need to make the file mode as executable by making the first line starting 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 that is the most important line to be used:
#!/usr/local/bin/python
The above line explains that the pathname that is given to the python interpreter and it is independent of the environment programs.
The file’s Absolute path name should be given 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.
The module that is used to write and read the binary data is known as struct.. This class contains the binary data. It is in the form of numbers.It 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”)
# Open() method allows the file to get opened in binary mode.
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 data form. For homogenous list of data the array can be used that will allow the data to be kept more in organized fashion.
Singleton pattern is used to provide a mechanism that limits the number of instances that can be used by one class.
This also allows the same object to be shared in many different parts of the code. This allows the global variables to be used as the actual data which is used 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;
}
py is an empty py file which is used for importing a module in a directory. _init_.py provides an easy way to organize the files.
If there is a module maindir/subdir/module.py,_init_.py is placed in all the directories so that the module can be imported using the following command- import maindir.subdir.module
For instance if list[4] has an even value the it has be included in the new output list because it has an even index but if list[5] has an even value it should not be included in the list because it is not at an even index.
[x for x in list [: 2] if x%2 == 0] The above code will take all the numbers present at even indices and then discard the odd numbers.
def xyz ():
return [lambda x: i * x for i in range (4)] print [m (2) for m in xyz ()] The output for the above code will be [6, 6,6,6]. The reason for this is that because of late binding the value of variable ‘i’ is looked up when any functions returned by ‘xyz’ are called.
The dynamic process of creating a list while performing some operation on the data so that it can be accessed using an iterator is referred to as List Comprehension.
Example: [ord (j) for j in string.ascii_uppercase] [65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90]
word = ‘aeioubcdfg’
print word [:3] + word [3:] The output for the above code will be: ‘aeioubcdfg’.
You can use a global variable in other func’s by declaring it as global in each func that assigns to it:
globvar = 0
def set_globvar_to_one():
global globvar # Needed to modify global
copy of globvar
globvar = 1
def print_globvar():
print globvar # No need for global
declaration to read value of globvar
set_globvar_to_one()
print_globvar() # Prints 1
1
2
3
4
5
6
7
8
Global variables are so dangerous so Python wants to make sure that you really know that’s what you’re playing with by explicitly requiring the global keyword.
print list [8:] The output for the above code will be an empty list [].
Most people might get confused in the answer with an index error.
Because the code is trying to access a member in the list whose index exceeds the total number of members in the list.
The code is trying to access the slice of a list at a start index which is greater than the number of members in the list.
def foo (i= []):
i.append (1)
return i
>>> foo ()
>>> foo ()The output for the above code will be-
[1] [1, 1] Argument to the function foo is evaluated only once when the function is defined. However, since it is a list, on every
all the list is modified by appending a 1 to it.
def factorial(n):
if n<=1:
return 1
else:
temp = ”
for i in range(1,n+1):
if n % i == 0:
temp += str(i) +’,’
return temp
num = raw_input(“Enter any number: “)
print factorial(int(num))
Python is an interpreted language which doesn’t require the compiler to run a program.
It is dynamically typed and well suited to object-oriented programming as well as it allows the definition of classes, composition, and inheritance.
Functions and classes are first class objects in python which means they can be assigned to variables, returned from other functions and given into the functions.
Python can be applied in automation, web applications, big data applications etc.… It is used as “glue” code to get combined with other languages.
List are mutable (edited) while Tuple is immutable which can’t be edited.
Lists slower when compared with Tuples.
List can have multiple data type in the single list where it can’t happen while using a tuple.
Syntax: list = [1,’python’, 2.0] Syntax: tuple = [1, 2, 3]
Dictionary is one of the built-in datatype in python which is represented with key and corresponding values to it. These are indexed based on keys.
Example: Dict = {‘Name’: ‘Ayesha’, ‘Age’: 10, ‘School’: ‘DPS’}
print Dict [Name] O/P: Ayesha
print Dict [Age] O/P: 10
print Dict [School’] O/P: DPS
In the above example Name, Age and School are Keys whereas the O/P are the corresponding values assigned to that keys.
When we are not sure about the number of arguments going to be passed with in a function, or if we want to pass a list of argument with in a function then we’ll be using “*args”.
When we don’t know how many keyword arguments to be passed in a function, or to pass the values of a dictionary as keyword arguments “**kwargs” are used.
Generally, in python we start an index representation with ‘0’ followed by integers, when we want in a reverse format we’ll start the index from ‘-1’ and follows.
Negative index is used to remove new-line spaces from a string and allows a string to except the last character that is given as S [:-1].
while(True):
ch = int(input())
print (“Enter value :”)
print(“HELLO WORLD”)
if (ch == 0):
exit()
num = [1,2,3,4,5,6,7] index = 0
For val in num:
index = index + 1
If index == 1 or index == 2:
continue
print(“Value”,val)
Recursion is the process of coding a problem, in which a function calls itself one or more times in the body of code. When it is returning the return value of this function call. If a function fulfils the condition of recursion, then it is known as recursive function.
Example: finding the factorial value.
n = 5
def factorial (n):
if n == 1:
return 1
else:
return n*factorial(n- 1)
Output: 120
Dict = {‘Name’: ‘Ayesha’, ‘School’: ‘DPS’}
key = input()
if key in Dict.key():
print(“Key is present”)
else:
print(“Key is not present”)
import pandas as pd
data = pd.series{‘A’:[1,2], ‘B’:[3,4]}
df = pd.DataFrame(data)
Print(df)
df1 = pd.melt(df,var_name = ‘stack’, value_name = ‘value’)
Print(df1)
Output: df = df1 =
A B stack value
1 3 A 1
2 4 A 2
B 3
B 4
It is not possible to de-allocate the memory that is reserved by the C library.
The python modules which are having circular references to the other objects are not always de-allocated.
Due to its own clean up mechanism, python would try to de-allocate every other object.
import pandas as pd
import numpy as np
s = pd.series([‘python’,’is’,’an’,’interpreter’])
s.str.cat(sep = ‘_’)
output:
python_is_an_interpreter
The maximum number of rows and columns are [60*20] to be get displayed in a Data Frame.
But we can set the maximum number as below so that we can increase the number of rows and columns to be displayed.
Syntax: pd.set_option(“Display.max_rows”,100)
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(1,2))
print(df)
output: 0.1234 1.2345
Xrange will not able to generate a static list at run-time like range does.
It creates the values as we need them with a special technique called yielding.
This is used with a type of objects known as generators.
It means if we have a large range to be get generate a list for, say a billion, xrange is the best function to be used.
Syntax: import os
Print(os.getcwd( ))
Python provides modules with functions which enable you to manipulate text and binary files on the file system. Based on them you can create files, update the contents, copy, and delete files.
The modules are os, shutil.
with open(“file-name”, ‘r’) as f:
filedata = fp.read( )
print(filedata)
Python supports 7 sequence types. They are str, list, tuple, unicode, xrange, byte array, and buffer.
Class is a blueprint created by a programmer for an object.
This defines a set of attributes that will characterize any object that is instantiated from this class.
class shark:
def swim(self):
print(“The shark is swimming”)
def be_awesome(self):
print(“The shark is being awesome”)
The constructor method is used to initialize data. It gets run as soon as an object of a class is defined. The constructor is defined as “ __init__” method, it will be the first definition of a class and looks as follows:
class shark:
def __ init __(self):
print(“This is the constructor method”)
import pandas as pd
import numpy as np
df = pd.DataFrame({‘A’:[3,1,1],’B’:[1,3,2]})
sort = df.sort_values(by = ‘B’)
print(sort)