Pytth
Pytth
List :
b. List is a container to contain different types of objects and is used to iterte objects.
c. Syntax of List
Tuple :
c. Syntax of Tuple
tup = (1,2,'a','d')
A Decorator is just a function that takes another function as an argument, add some kind of
functionality and then returns another function.
All of this without altering the source code of the original function that you passed in.
e.g.
def decorator_func(func):
def wrapper_func(func):
print("wrapper_func Worked")
return func()
print("decorator_func Worked")
return wrapper_func
def show():
print("Show Worked")
decorator_show = decorator_func(show)
decorator_show
@decorator_func
def display():
print('Display Worked')
display()
output:
decorator_func Worked
warpper_func Worked
List Comprehension :
syntax:
Example:
Common Way:
l = []
for i in range(10):
if i % 2:
l.append(i)
print(i)
ls = [i for i in range(10) if i % 2]
Output:
[1,3,5,7,9]
Dict Comprehension :
syntax:
Common Way:
d = {}
sqr = i* i
d[i] = i * i
print(d)
print(d1)
Output:
. Memory Management in python involves a private heap containing all python objects and data
structures. Interpreter takes care of python heap and that the programmer has no access to it.
. The allocation of heap space for python objects is done by Python memory manager. The core API of
python provides some tools for the programmer to code reliable and more robust program.
. Python also has a build in garbage collector which recycles all the unused memory. When an object is
no longer referenced by the program, the heap space it occupies can be freed. The garbage collector
determines
. objects which are no longer referenced by the program frees the occupied memory and make it
available to the heap space.
Generator :
. Generators are mostly used in loops to generate an iterator by returning all the values in the
loop without affecting the iteration of the loop.
e.g.
def sqr(n):
yield i * i
a = sqr(3)
print(next(a))
print(next(a))
print(next(a))
Output:
9
Iterator:
. An iterator is an object which contains a countable number of values and it is used to iterate
over iterable objects like list, tuples, sets, etc.
. Iterators are used mostly to iterate or convert other objects to an iterator using iter() function.
e.g.
iter_list= iter(['A','B','C'])
print(next(iter_list))
print(next(iter_list))
print(next(iter_list))
Output:
__init__.py file
The __init__.py file lets the python interpreter know that a directory contains code for a python
module. It can be blank. Without one , you cannot import modules from another folder into your
project.
The role of the __init__.py file is similar to the __init__ function in a python class. The file essentially the
constructor of your package or directory without it being called such. It sets up how packages or
functions will be imported into your other files.
__init__() function
The __init__method is similar to constructors in c++ and java. Constructors are used to initialize the
object's state.
class Person:
self.name = name
# sample method
def say_hi(self):
p = Person('Sorav')
p.say_hi()
Module :
The module is a simple python file that contains collections of functions and global variables and with
having a .py extension file. It is an executable file and to organize all the modules we have the concept
called package in python.
A module is a single file (or files ) that are imported under one import and used.
e.g.
import <my_module>
import numpy
Package:
The package is a simple directory having collections of modules . This directory contains Python
modules and also having __init__.py file by which the interpreter interprets it as a package. The package
is simply a namespace . The package also contains sub-packages inside it.
e.g.
Range :
Memory Consumption - Since range() returns a list of elements, it takes more memory.
Operations - Since it returns a list, all kinds of arithmetic operations can be performed.
Xrange :
. Generators are mostly used in loops to generate an iterator by returning all the values in the
loop without affecting the iteration of the loop.
e.g.
def sqr(n):
yield i * i
a = sqr(3)
print(next(a))
print(next(a))
print(next(a))
Output:
10. What are inbuilt data types in python or Explain Mutable & Immutable data Types in Python ?
A first fundamental distinction that python makes on data is about whether or not the value of an object
changes.
B.
age = 25
print(discount)
In inheritance, the child class acquires the properties and can access all the data members and
functions defined in the parent class. A child class can also provide its specific implementation to the
functions of the parent class.
In python, a derived class can inherit base class by just mentioning the base in the bracket after the
derived class name.
class Animal:
def speak(self):
print("Animal Speaking")
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
d.bark()
d.speak()
Output:
dog barking
Animal Speaking
Local Variable:
. It is created when the function starts execution and lost when the functions terminate.
. Data Sharing is not possible as data of the local variable can be accessed by only one function.
. Parameters passing is required for local variables to access the value in other function.
. When the value of the local variable is modified in one function, the changes are not visible in
another function.
. Local variables can be accessed with the help of statements, inside a function in which they are
declared.
Global Variable:
. It is created before the program's global execution starts and lost when the program
terminates.
. Data Sharing is possible as multiple functions can access the same global variable.
. Parameters passing is not necessary for a global variable as it is visible throughout the
program.
. When the value of the global variables is modified in one function changes are visible in the
rest of the program.
. A break statement , when used inside the loop , will terminate the loop and exit. If used inside
nested loops , it will break out from the current loop.
. A continue statement will stop the current execution when used inside a loop, and the control will go
back to the start of the loop.
. A pass statement is a null statement . When the Python interpreter comes across the pass
statement, it does nothing and is ignored.
The 'self' parameter is a reference to the current instance of the class, and is used to access variables
that belongs to the class.
class car():
self.model = model
self.color = color
def show(self):
Pickling:
In python, the pickle module accepts any Python object, transforms it into a string
representation , and dumps it into a file by using the dump function.
This process is known as pickling . The function used for this process is pickle.dump().
Unpickling:
The process of retrieving the original python obect from the stored string representation is
called unpickling.
- Pickling, also called serialization, involves converting a Python object into a series of bytes
which can be written out to a file.
- Unpickling , or de-serialization , does the opposite - It converts a series of bytes into the
python objects it represents.
List:
Tuples:
cmp(),len(),max(),min(),sum(),any(),all(),sorted(),index(),count()
Sets:
add(),clear(),copy(),difference(),difference_update(),discard(),intersection(),intersection_update(),
pop(),remove(),union(),update()
Dictionary:
Iterator:
. An iterator is an object which contains a countable number of values and it is used to iterate
over iterable objects like list, tuples, sets, etc.
. Iterators are used mostly to iterate or convert other objects to an iterator using iter() function.
iter_list= iter(['A','B','C'])
print(next(iter_list))
print(next(iter_list))
print(next(iter_list))
Output:
19. Explain Type Conversions in Python (int, float, str, oct etc.) ?
int()
a = '100'
d = int(a)
print(d)
print(type(d))
float()
a = '100'
d = float(a)
print(d)
print(type(d))
oct()
a = 100
d = oct(a)
print(d)
print(type(d))
hex()
Convert the integer into a suitable hexadecimal form for the number of the integer.
a = 100
d = hex(a)
print(d)
print(type(d))
ord()
Returns the integer of the Unicode point of the character in the Unicode case or the byte value
in the case of an 8-bit argument.
a ='A'
d = ord(a)
print(d)
print(type(d))
chr()
Returns the character (string) from the integer (represents unicode code point of the character).
a = 100
d = chr(a)
print(d)
print(type(d))
eval()
a = '100+2+'3
d = eval(a)
print(d)
print(type(d))
When you are not clear how many arguments you need to pass to a particular function, then we use
*args and **kwargs .
The *args keyword represents a varied number of arguments. it is used to add together the values of
multiple arguments.
The **kwargs keyword represents an arbitrary number of arguments that are passed to a function.
**kwargs keywords are stored in a dictionary . You can access each item by referring to the keyword you
associated
With the 'With' statement , you get better syntax and exceptions handling.
f = open('srv.txt')
content = f.read()
print(content)
f.close
With open('srv.txt')
contnt=f.read()
print(content)
Read Only r
Write only w
Append Only a
Text mode t
Exclusive creation x
Binary mode b
PythonPath is an environment variable which you can set to add additional directories where python
will look for modules and package.
The PythonPath variable holds a string with the name of various directories that need to be added to the
sys.path directory list by python.
The primary use of this variable is to allow users to import modules that are made installable yet.
Finally : Finally block always gets executed either exception is generated or not.
try:
# some code..!
except:
# Optional Block
else:
# Some code...
# execute if no exception
finally:
if __name__=="__main__":
if __name__=="__main__":
main()
main()
Division of Integers Whenever two integers are divided When two integers are divided,
of strings is unicode.
you require to define them with "u".
understandable.
difficult to understand.
Python pip is the package manager for Python packages. We can use pip to install packages that
do not come with Python.
The basic syntax of pip commands in command prompt is :
pip 'arguments'
Web Applications
Desktop Applications
Networking Applications
Machine Learning
Artificial Intelligence
Data Analysis
IOT Applications
name = 'sorav'
x= list(dct.keys())
print(x)
x = [*dct.keys()]
print(x)
*x, = dct.keys()
print(x)
dct.keys()
Abstraction :
. It highlights what the work of an object instead of how the object works is
. In a nutshell , abstraction is hiding implementation with the help of an interface and an abstract
class.
Encapsulation :
. It is the mechanism of hiding the code and the data together from the outside world or misuse.
. It focuses on the inner details of how the object works. Modifications can be done later to the
settings.
. It focuses on interval working or inner viewing , e.g. the production of the car.
. It is supported using, e.g. public, private and secure access modification systems.
. In a nutshell, encapsulation is hiding the data with the help of getters and setters.
31. Does Python Support Multiple Inheritance. (Diamond Problem)
Diamond Problem :
Java does not allow is multiple inheritance where one class can inherit properties from more
than one class.
lis =[]
tup = ()
dict = {}
st = set()
- .py files contain the source code of program. Whereas, .pyc files contains the bytecode of your
program.
- Python compiles the .py files and saves it as .pyc files , so it can reference them in subsequent
invocations.
- The .pyc contain the compiled bytecode of Python source files. This code is then executed by
Python's virtual machine.
Syntax:
str_object [Start_Position:End_Position:Step]
s = 'HelloWorld'
print(s[0:4])
Hell
We can gives the negatives values also.
35. Can we Concatenate Two Tuples ? If yes ? How ? Since Tuple is Immutable.
t1 = (1,2,3)
t1= t1 + t2
Output:
Lists:
. The lists are build-in data structure so we don't need to import it.
. The lists are less compatible than the array to store the data.
_a :
. Python doesn't have real private methods, so one underline in the begining of a
variable/function/method name means it's a private variable/function/method and it is for internal use
only.
__a :
. leading double underscore tell python interpreter to rewrite name in order to avoid conflict in
subclass.
. Interpreter changes variable name with class extension and that features known mangling.
. So Multiple time It use as the private member because another class can not access that variable
directly.
. Main purpose for __ is to use variable/method in class only If you want to use it outside of the class
you can make public api.
__a__ :
. Name with start with __ and ends with same considers special methods in Python.
. Python provide this methods to use it as the operator overloading depending on the user.
. Python provides this convention to differentiate between the user defined function with the
module's function.
using Split()
dct.clear()
dc.pop('A')
del dct['B]
dct.copy()
dct = dct2
40. What is the difference between Anonymous & Lambda Function ?
Lambda Function :
sq(5)
Anonymous Function :
. While normal functions are defined using def keyword, Anonymous functions are defined using the
lambda keyword.
def suare(x):
return x*x
MutliThreading :
. It is a technique where multiple threads are spawned by a process to do different tasks, at about the
same tme, just one after the other.
. This gives you the illusion that the threads are running in parallel, bt they are actually run in a
concurrent manner.
.In Python, the Global Interpreter Lock (GIL) prevents the threads fro running simultaneously.
Multiprocessing :
. It is a technique where parallelism in its truest form is achieved.
. Multiple processes are run across multiple CPU cores, which do not share the resources among
them.
. Each process can have many threads running in its own memory space.
. In Python, each process has its own instance of Python interpreter doing the job of executing the
instructions.
. The GIL of python allows only one thread to be executed at a time. It is often a hurdle , as it
does not allow multi-threading in python to save time.
. The Python Global Interpreter Lock or GIL , in simple words , is a mutex(or a lock) that allows
only one thread to hold the control of the Python Interpreter.
. This means that only one thread can be in a state of execution at any point in time. The impact
of the GIL isn't visible to developers who execute single - threaded programs
. Since the GIL allows only one thread to execute at a time even in a multi-thread architecture
with more than one CPU core, the GIL has gained a reputation as an "infamous" feature of Python.
. Basically, GIL in Python doesn't allow multi-threading which can sometimes be considered as a
disadvantage.
Create a Class :
class Student :
name = 'Gorav'
obj = Student()
print(obj.name)
Namespace :
. There is a chance the name of the variable you are going to use is already existing as name of
another variable or as the name of another function or another method.
. In such scenario , we need to learn about how all these names are managed by a python program.
This is the concept of namespace.
- Local Namespace : All the names of the functions and variables declared by a program are held
in this namespace. This namespace exists as long as the program runs.
- Global Namespace : This namespace holds all the names of functions and other variables that
are included in the modules being used in the python program. It includes all the names that are part of
the Local namespace.
- Built-In Namespace : This is the highest level of namespace which is available with default
names available as part of the python interpreter that is loaded as the programming environnment. It
include Global namespace which in turn include the local namespace.
We can acces all the names defined in the built-in namespace as follows.
builtin_names=dir(__builtins__)
print(name)
if not lst:
return[]
print(reverseList([1,2,3,4,5]))
Output :
[5,4,3,2,1]
Unit Testing is the first level of software testing where the smallest testable parts of a software are
tested. This is used to validate that each unit of the software performs as designed . The unittest test
framework is python's xUnit style framework. This is how you can import it.
Import unittest
- It is a software testing method by which individual units of source code are put under various tests to
determine whether they are fit for use(Source).It determines and ascertains the quality of your code.
- Generally, when the development process is complete , the developer codes criteria , or the results
that are known to be potentially practical and useful , into the test script to verify a particular unit's
correctness. During test case execution, various frameworks log tests that fail any criterion and report
them in a summary.
- The developers are expected to write automated test scripts, which ensures that each and every
section or a unit meets its design and behaves as expected.
- Though writing manual tests for your code is definitely a tedious and time-consuming task, Python's
built-in unit testing framework has made life a lot easier.
- The unit test framework in Python is called unittest, which comes packaged with Python.
- Unit Testing makes your code future proof since you anticipate the cases where your code could
potentially fail or produce a bug. Though you cannot predict all of the cases, You still address most of
them.
Map() Function :
The map() function iterates through all items in the given iterable and executes the function we
passed as an argument on each of them.
The syntax is :
map(function,iterable(s))
fruit = ["Apple","Banana","Mango"]
mp = map(lambda s : s[0]=="A",fruit)
print(list(mp))
Output:
[True,False,False]
Filter() Function :
The filter() function takes a function object and an iterable and creates a new list. As the name
suggests , filter() forms a new list that contains only elements that satisfy a certain condition, i.e. the
function we passed returns True.
The syntax is :
filter(function,iterable(s))
fruit = ["Apple","Banana","Mango"]
flt = filter(lambda s : s[0]=="A",fruit)
print(list(flt))
Output:
['Apple','Apricot']
Reduce() Function :
The reduce() function works differently than map() and filter() . It does not return a new list
based on the function and iterable we've passed. Instead , it returns a single value.Also in Python3
reduce() isn't a built-in function anymore, and it can be found in the functools module.
The syntax is :
reduce(function,sequence[,initial])
list = [2,4,7,3]
Output:
16
Shallow Copy :
Deep Copy:
. A deep copy constructs a new compound object and then, recursively, inserts copies into it of
the objects found in the original.
In Python, the term monkey patch refers to dynamic (or run-time) modifications of a class or
module.In Python , we can actually change the behaviour of code at run-time.
- In Python, we sometimes see method names with a double underscore(__), such as the
__init__ method that every class has. These methods are called "dunder" methods.
- In Python, Dunder methods are used for operator overloading and customizing some other
function's behaviour.