What do you know about Python?
Python is an interpreted, high level, interactive and object-oriented programming language similar to PERL that has gained popularity because of its clear syntax and readability. Python is said to be relatively easy to learn and portable, meaning its statements can be interpreted in a number of operating systems, including UNIX-based systems, Mac OS, MS-DOS, OS/2, and various versions of Microsoft Windows 98.
The Python programming language is freely available and makes solving a computer problem almost as easy as writing out your thoughts about the solution.
What are the important features of Python?
A simple language which is easier to learn
Python has a very simple and elegant syntax. It’s much easier to read and write Python programs
compared to other languages like: C++, Java, C#. Python makes programming fun and allows you to focus on the solution rather than syntax.
Easy-to-maintain: Python’s source code is fairly easy-to-maintaining.
A broad standard library: Python’s bulk of the library is very portable and cross platform Compatible on UNIX, Windows, and Macintosh.
Interactive Mode: Python has support for an interactive mode, which allows interactive testing and debugging of snippets of code.
Portability: You can move Python programs from one platform to another and run it without any changes. It runs seamlessly on almost all platforms including Windows, Mac OS X and Linux. Same interface on all platforms.
Extendable: You can add low-level modules to the Python interpreter. These Modules enable programmers to add to or customize their tools to be more efficient.
Databases: Python provides interfaces to all major commercial databases.
GUI Programming: Python supports GUI applications that can be created and ported to many system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X Window system of UNIX.
Scalable: Python provides a better structure and support for large programs than shell scripting.
Object-oriented: Everything in Python is an object. Object oriented programming (OOP) helps you solve a complex problem intuitively. With OOP, you are able to divide these complex problems into smaller sets by creating objects.
What are the applications of Python programming language?
Web Applications and Web Frameworks:
Python has been used to create a variety of web-frameworks including CherryPy, Django, TurboGears, Bottle, Flask etc. These frameworks provide standard libraries and modules which simplify tasks related to content management, interaction with database and interfacing with different internet protocols such as HTTP, SMTP, XML-RPC, FTP and POP. Plone, a content management system; ERP5, an open source ERP which is used in aerospace, apparel and banking; Odoo – a consolidated suite of business applications; and Google App engine are a few of the popular web applications based on Python.
Language Development: Python’s design and module architecture has influenced development of numerous languages. Boo language uses an object model, syntax and indentation, similar to Python. Further, syntax of languages like Apple’s Swift, Coffee Script, Cobra, and OCaml all share similarity with Python.
Scientific and Numeric Computing: There are numerous libraries available in Python for scientific and numeric computing. There are libraries like: SciPy and NumPy that are used in general purpose computing. And, there are specific libraries like: EarthPy for earth science, AstroPy for Astronomy and so on.
Business Applications: Python is also used to build ERP and e-commerce systems like Odoo is an all-in-one management software that offers a range of business applications that form a complete suite of enterprise management applications and Tryton is a three-tier high-level general-purpose application platform.
Great Community and Support: Python has a large supporting community. There are numerous active forums online which can be handy if you are stuck. Some of them are:
- Learn Python subreddit
- Google Forum for Python
- Python Questions – Stack Overflow
What are the differences Python 2.x and Python 3.0?
Python 2.x is legacy, Python 3.x is the present and future of the language
Python 3.0 was released in 2008. The final 2.x version 2.7 release came out in mid-2010, with a statement of extended support for this end-of-life release. The 2.x branch will see no new major releases after that. 3.x is under active development and has already seen over five years of stable releases, including version 3.3 in 2012, 3.4 in 2014, 3.5 in 2015, and 3.6 in 2016. This means that all recent standard library improvements, for example, are only available by default in Python 3.x.
Guido van Rossum (the original creator of the Python language) decided to clean up Python 2.x properly, with less regard for backwards compatibility than is the case for new releases in the 2.x range. The most drastic improvement is the better Unicode support (with all text strings being Unicode by default) as well as saner bytes/Unicode separation.
Besides, several aspects of the core language (such as print and exec being statements, integers using floor division) have been adjusted to be easier for newcomers to learn and to be more consistent with the rest of the language, and old cruft has been removed (for example, all classes are now new-style, “range()” returns a memory efficient iterable, not a list as in 2.x).
What is PEP8?
PEP 8 is the latest Python coding standard, a set of coding recommendations. It guides to deliver more readable Python code.
What are the Built-in types Available in Python?
The most commonly used built-in types in Python are
- Immutable built-in types of Python
- Mutable built-in types of Python
What makes Python differ from other programming languages?
In python English keywords are used frequently whereas punctuation is used in other languages, and it has fewer syntactical constructions than other languages.
What is the use of Python?
It is used in GIS programming and as a scripting language (for ArcGIS, and Quantum GIS). Python is true general-purpose language.
What is the difference between python and java?
Python is a programming language that boasts a gentler learning curve, and a more intuitive coding style. Java is also another programming language, but with a distinct advantage compared to other programming languages. Programs made with Java can be run on any operating system that is able to run the Java virtual machine. This is because Java does not compile to native bytecode, like Python does; it compiles to a Java bytecode that can be read and executed by the virtual machine.
The use of a virtual machine impairs the performance of Java programs due to the overhead incurred. Programs that are compiled to native code, like Python, can perform at its best because it can take advantage of optimizations. Although you can compile Java programs to native code, it does not perform as well.
Java is a strongly typed language, while Python is not. Basically, Java does not allow the data type of a variable to be changed, while Python does. Unlike most programming languages, Python allows you to assign a string to a variable that once held an integer value. This is not possible with Java, and you need to define a variable for each one with the correct type.
What is the Python Decorator?
Python has an interesting feature called decorators to add functionality to an existing code. This is also called metaprogramming as a part of the program tries to modify another part of the program at compile time.
Explain python memory management?
Memory management in Python involves a private heap containing all Python objects and data structures. The management of this private heap is ensured internally by the Python memory manager. The Python memory manager has different components which deal with various dynamic storage management aspects, like sharing, segmentation, preallocation or caching. Python memory management depend on the implementation.
The standard C implementation of Python uses reference counting to detect inaccessible objects, and a separate mechanism to collect reference cycles, periodically executing a cycle detection algorithm which looks for inaccessible cycles and deletes the objects involved. The gc module provides functions to force garbage collection, obtain debugging statistics, and tune the collector’s parameters.
What does a python do?
Python language is a general-purpose programming language typically used for web development. … SQLite is one free lightweight database commonly used by Python programmers to store data. Many highly trafficked websites, such as YouTube, are created using Python.
What is PYTHONPATH?
PYTHONPATH is an environment variable, much like PATH. You can get a list of environment variables on UNIX-like operating systems by running the ‘env’ command. It’s available in the Properties of My Computer in Windows. PYTHONPATH is similar to PATH in another way, in that it defines a search path.
However, unlike PATH (which tells the operating system which directories to look for executable files in), PYTHONPATH is used by the Python interpreter to find out where to look for modules to import.
What are the Principal differences between The Lambda and Def?
- Def can hold multiple expressions while lambda is a uni-expression function.
- Def generates a function and designates a name so as to call it later.
- Lambda forms a function and returns the function itself.
- Def can have a return statement.
- Lambda can’t have return statements
- Lambda supports to get used inside a list and dictionary.
How is Python executed?
Python files are compiled to bytecode. Which is then executed by the host.
Alternate Answer: Type python. pv at the command line.
What is NumPy?
NumPy is the fundamental package for scientific computing in Python. It is a Python library that provides a multidimensional array object, various derived objects (such as masked arrays and matrices), and an assortment of routines for fast operations on arrays, including mathematical, logical, shape manipulation, sorting, selecting, I/O, discrete Fourier transforms, basic linear algebra, basic statistical operations, random simulation and much more.
What is the Pass Statement in Python?
The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute. The pass statement is a null operation; nothing happens when it executes. The pass is also useful in places where your code will eventually go, but has not been written yet.
Syntax pass
Example:
#!/usr/bin/python
for letter in ‘Python’:
if letter == ‘h’:
pass
print ‘This is pass block’
print ‘Current Letter :’, letter
print “Good bye!”
What is the main purpose of “is” operator?
Evaluates to true if the variables on both sides of the operator are pointing to the same object and false otherwise. y is x, here is results in 1 if id(y) equals id(x).
What is the main purpose of // operator?
// represents floor division which corresponds to the division of operands where the result is the quotient such that after the decimal point are removed.
What is Pickle in python?
The pickle module implements a fundamental, but powerful algorithm for serializing and de-serializing a Python object structure. “Pickling” is the process whereby a Python object hierarchy is converted into a byte stream, and “unpickling” is the inverse operation, whereby a byte stream is converted back into an object hierarchy.
Pickling (and unpickling) is alternatively known as “serialization”, “marshalling,” or “flattening”, however, to avoid confusion, the terms used here are “pickling” and “unpickling”.
What is pickling and unpickling?
Pickle is a module which accepts any Python object. Converts this object into a string and dumps it into a file by using dump function, this is called pickling. While retrieving its original objects from the stored string is called unpickling.
How to use dictionaries in Python?
Python dictionary is an unordered collection of items. While other compound data types have only value as an element, a dictionary has a key: value pair. Dictionaries are optimized to retrieve values when the key is known.
Use {} curly brackets to construct the dictionary, and [] square brackets to index it. Separate the key and value with colons: and with commas, between each pair. Keys must be quoted As with lists we can print out the dictionary by printing the reference to it. A dictionary maps a set of objects (keys) to another set of objects (values). A Python dictionary is a mapping of unique keys to values. Dictionaries are mutable, which means they can be changed. The values that the keys point to can be any Python value. Dictionaries are unordered, so the order that the keys are added doesn’t necessarily reflect what order they may be reported back.
How will you create a dictionary in python?
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]).
dict = {}
dict[‘one’] = “This is one”
dict[2] = “This is two”
tinydict = {‘name’: ‘john’,’code’:6734, ‘dept’: ‘sales’}
What is the difference between list and tuple in Python?
Tuples are lists which can’t be edited. Once you create a tuple, you cannot edit it, it is immutable. Lists on the other hand are mutable, you can edit them, and they work like the array object in JavaScript or PHP. You can add items, delete items from a list; but you can’t do that to a tuple, tuples have a fixed size.
Technically, mutability and the syntax are the only differences between lists and tuples in Python. As a consequence of the mutability difference, tuples are easier on memory and processor, meaning you can gain some performance optimization with the use of tuples in the right places.
What is the output of print (tuple(2)) if tuple = ('abcd', 786 , 2.23, 'john', 70.2 )?
What is the output of print( str(o))if str = 'Hello World!'?
What is the output of print str * 2 if str = ‘Hello World!’?
It will print string two times. Output would be Hello World! Hello World!.
What is the output of print tuple`{`2:`}` if tuple = ( ‘abcd’, 786 , 2.23, ‘sam’, 70.2 )?
It will print elements starting from 3rd element. Output would be (2.23, ‘sam’, 70.200000000000003).
What is the difference between del and remove() method on list?
Del is a clear and fast way to remove elements from a list.To remove a list element, you can use either the del statement if you know exactly which element(s) you are deleting or the remove() method if you do not know.
How will you reverse a list?
list.reverse() − Reverses objects of list in place.
How will you remove last object from a list?
list.pop(obj=list[-1]) − Removes and returns last object or obj from list.
How do you create a Python function?
Python functions are defined using the def statement. An example might be def foo(bar):
What is Iterator
Iterators are containers for objects so that you can loop over the objects. In other words, you can run the for loop over the object. There are many different iterators in the Python standard library.
What is monkey patching?
Monkey patching is changing the behavior of a function or object after it has already been defined. For example: import datetime
datetime.datetime.now = lambda: datetime.datetime(2012, 12, 12)
When would you use triple quotes as a delimiter?
Triple quotes ‘’”” or ‘“are string delimiters that can span multiple lines in Python. Triple quotes are usually used when spanning multiple lines or enclosing a string that has a mix of single and double quotes contained therein.
How can you pick a random item from a range?
randrange ([start,] stop [, step]) − returns a randomly selected element from range(start, stop, step).
Can you explain string join()?
join() is a string method which returns a string concatenated with the elements of an iterable..
How will you check in a string that all characters are alphanumeric?
isalnum() − Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.
What do you know about unit test?
A unit testing framework of python is called unit test. It supports automation testing, sharing of setups, aggregation of tests into collections, shutdown code for tests, etc.
How many except statements can a try-except block have?
More than zero, there has to be at least one except statement.
What is returned by math.ceil() function?
The ceil function returns the smallest integer >= to the number itself.
How can you get a random number in python?
random () − returns a random float r, such that 0 is less than or equal to r and r is less than 1.
What is a CPython?
CPython is the original implementation, written in C. (The “C” part in “CPython” refers to the language that was used to write Python interpreter itself.) Jython is the same language (Python), but implemented using Java. IronPython interpreter was written in C#.
What is the purpose continue statement in python?
Continue statement − Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
What is a GIL?
Global interpreter lock (GIL) is a mutex that protects access to Python objects, preventing multiple threads from executing Python bytecodes at once. This lock is necessary mainly because CPython’s memory management is not thread-safe. (However, since the GIL exists, other features have grown to depend on the guarantees that it enforces.)
What is Python itertools?
Python itertools module is very useful in creating efficient iterators. In almost every program you write with any programming language.It is provide us various ways to manipulate the sequence while we are traversing it.
What is generators?
A generator is simply a function that returns an object on which you can call next until it raises a Stop Iteration exception, such that for every call it returns some value, signaling that all values have been generated.
What is getattr()?
getattr() function is used to get the value of an object’s attribute and if no attribute of that object is found, default value is returned.
What is slicing?
A process of selecting a range of items from sequence types like tuple, strings, list etc. is called as slicing.
How can you copy objects in Python?
There are two ways to copy objects in Python.
copy.copy () function:
- It’ll return a shallow copy of the parameter.
copy.deepcopy () function:
- It’ll return a deep copy of the parameter that you can pass to the function.
However, it is not possible to copy all objects in Python using these functions. For instance, dictionaries have a separate copy method whereas sequences in Python have to be copied by ‘Slicing’.
What is the output of L(1:) if L = (1,2,3)?
2, 3, Slicing fetches sections.
Name a module that is not included in python by default?
Mechanize
Django,gtk
A lot of other can be found at pypi.
What is __init__.py used for?
It declares that the given directory is a package. #Python Docs (From Endophage ‘s comment)
Why and when do you use generators in Python?
A generator in Python is a function which returns an iterable object. We can iterate on the generator object using the <yield> keyword. But we can only do that once because their values don’t persist in memory, they get the values on the fly.
Generators give us the ability to hold the execution of a function or a step as long as we want to keep it. However, here are a few examples where it is beneficial to use generators.
- We can replace loops with generators for efficiently calculating results involving large data sets.
- Generators are useful when we don’t want all the results and wish to hold back for some time.
- Instead of using a callback function, we can replace it with a generator. We can write a loop inside the function doing the same thing as the callback and turns it into a generator.
Explain the use of try: except: raise, and finally?
Try, except and finally blocks are used in Python error handling. Code is executed in the try block until an error occurs. One can use a generic except block, which will receive control after all errors, or one can use specific exception handling blocks for various error types. Control is transferred to the appropriate except block. In all cases, the final block is executed. Raise may be used to raise your own exceptions.
What happens if an error occurs that is not handled in the except block?
The program tenuinates. And an execution trace is sent to sys.stderr.
What happens when a function doesn’t have a return statement? Is this valid?
Yes, this is valid. The function will then return a none object. The end of a function is defined by the block of code being executed (i.e., the indenting) not by any explicit keyword.
What is the different between range () and xrange () functions in Python?
Range () returns a list whereas xrange () returns an object that acts like an iterator for generating numbers on demand.
How do you invoke the Python interpreter for interactive use?
Python or pythonx.y where x.y are the version of the Python interpreter desired.
How are Python blocks defined?
By indents or tabs. This is different from most other languages which use symbols to define blocks. Indents in Python are significant
List down some of the PDB Commands for Debugging Python Programs?
Here are a few PDB commands to start debugging Python code.
Add breakpoint – <b>
Resume execution – <c>
Step by step debugging – <s>
Move to next line – <n>
List source code – <l>
Print an expression – <p>
What does the <yield> keyword do in python?
The <yield> keyword can turn any function into a generator. It works like a standard return keyword. But it’ll always return a generator object. Also, a function can have multiple calls to the <yield> keyword.
See the example below.
def testgen(index):
weekdays = [‘sun’,’mon’,’tue’,’wed’,’thu’,’fri’,’sat’]
yield weekdays[index]
yield weekdays[index+1]
day = testgen(0)
print next(day), next(day)
#output: sun mon
What does the <Self> do?
<Self> is a used in so many places in python.the <self> is a variable that holds the instance of an object. In almost, all the object-oriented languages, it is passed to the methods as hidden parameter.
Is there a switch or case statement in Python? If Not Then what is the reason for the same?
No, Python does not have a Switch statement, but you can write a Switch function and then use it.
How to find bugs or perform static analysis in a Python application?
- You can use PyChecker, which is a static analyzer. It identifies the bugs in Python project and also reveals the style and complexity related bugs.
- Another tool is Pylint, which checks whether the Python module satisfies the coding standard.
Name few Python Web Frameworks for developing web applications?
There are various web frameworks provided by Python. They are
- web2py – it is the simplest of all the web frameworks used for developing web applications.
- cherryPy – it is a Python-based Object oriented Web framework.
- Flask – it is a Python-based micro-framework for designing and developing web applications.
How do you check the file existence and their types in Python?
os.path.exists () :use this method to check for the existence of a file. It returns true if the file exists, false otherwise. Eg: import os; os.path.exists (‘/etc/hosts’)
os.path.isfile () : this method is used to check whether the give path references a file or not. It returns True if the path references to a file, else it returns false. Eg: import os; os.path.isfile (‘/etc/hosts’)
os.path.isdir () : this method is used to check whether the give path references a directory or not. It returns true if the path references to a directory, else it returns false. Eg: import os; os.path.isfile (‘/etc/hosts’)
os.path.getsize () : returns the size of the given file
os.path.getmtime () : returns the timestamp of the given path.
How do you remove duplicates from a list?
- First sort the list
- Second scan the list from the end.
- Third while scanning from right-to-left, delete all the duplicate elements from the list
Does Python supports interfaces like in Java?
Python does not provide interfaces like in Java. Abstract Base Class (ABC) and its feature 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’c provides a sort of “understanding” about methods and their expected behavior. This module was made available from Python 2.7 version onwards.