1. What is Python?
Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently where as other languages use punctuation, and it has fewer syntactical constructions than other languages.
2. What is a Python module?
A module is a Python script that generally contains import statements, functions, classes and variable definitions, and Python runnable code and it “lives” file with a ‘.py’ extension. zip files and DLL files can also be modules.Inside the module, you can refer to the module name as a string that is stored in the global variable name .
3. What happens in the background when you run a Python file?
When we run a .py file, it undergoes two phases. In the first phase it checks the syntax and in the second phase it compiles to bytecode (.pyc file is generated) using Python virtual machine, loads the bytecode into memory and runs.
4. What happens with the following function definition?
Here the issue is with function definition, it is a syntax error and the code will not run. The default argument is following the non-default argument, which is not right as per Python function definition rules. Non-default arguments should be placed first and then comes the default arguments in the function definition. Here is the right way of defining:
def welcome(city, name=’guest’): print ‘Hello’, name, ‘Welcome to’, city
The order of passing values to a function is, first one has to pass non-default arguments, default arguments, variable arguments, and keyword arguments.
5. What are the differences between Python 2.x and Python 3.x?
Python 2.x is an older version of Python while Python 3.x is newer. Python 2.x is legacy now but Python 3.x is the present and future of this language. The most visible difference between them is in print statement. In Python 2 it is print “Hello” and in Python 3, it is print (“Hello”).
6. 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 finally block is executed. Raise may be used to raise your own exceptions. (SVR Technologies)
7. 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.
8. Explain the difference between local and global namespaces?
Local namespaces are created within a function. when that function is called. Global name spaces are created when the program starts. (python interview questions and answers)
9. What Is A String In Python?
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.
10. What is Threads Life Cycle?
Threads Life Cycle
Creating the object of a class which is overwriting run method of thread class is known as a creating thread
Whenever thread is created then we call thread is in new state or birth state thread.
Whenever we call the start method on the new state threads then those threads will be forwarded for scheduling
The threads which are forwarded for scheduling are known as ready state threads
Whenever scheduling time occurs, ready state thread starts execution
The threads which are executing are known as running state threads
Whenever sleep fun or join methods are called on the running state threads then immediately those threads will wait.
The threads which are waiting are known as waiting state threads
Whenever waiting time is over or specified thread execution is over then immediately waiting state threads are forwarded for scheduling.
If running state threads execution is over then immediately those threads execution will be terminated
The threads which execution is terminated are known as dead state threads.
11. What do you mean by the dictionary in Python?
The built-in data types of Python known as Dictionary. For e.g. “Country”.
Enlisted below are some of the benefits of using Python.
Application development is faster and easy.
Extensive support of modules for any kind of application development including data analytics/machine learning/math-intensive applications.
Excellent support community to get your answers.
13. How are data types defined in Python and how much bytes do integer and decimal data types hold?
In Python, there is no need to define a variable’s data type explicitly.
Based on the value assigned to a variable, Python stores the appropriate data type. In the case of numbers such as Integer, Float, etc, the length of data is unlimited.
14. How does Lambda function differ from a normal function in Python?
Lambda is similar to the inline function in C programming. It returns a function object. It contains only one expression and can accept any number of arguments.
In case of a normal function, you can define a function name, pass parameter and mandatorily have a return statement. The Lambda function can be typically used for simple operations without the use of function names. It can also be used in the place of a variable.
15. Does the same Python code work on multiple platforms without any changes?
Yes. As long as you have the Python environment on your target platform (Linux, Windows, Mac), you can run the same code. (python interview questions and answers)
16. What is the difference between locals() and globals ()?
locals() is accessed within the function and it returns all names that can be accessed locally from that function.
globals() returns all names that can be accessed globally from that function.
17. What is the difference between ‘match’ and ‘search’ in Python?
Match checks for the match at the beginning of the string whereas search checks for the match anywhere in the string.
18. What is swapcase() function in the Python?
It is a string’s function which converts all uppercase characters into lowercase and vice versa. It is used to alter the existing case of the string. This method creates a copy of the string which contains all the characters in the swap case. If the string is in lowercase, it generates a small case string and vice versa. It automatically ignores all the non-alphabetic characters. See an example below.
19. Give an example of shuffle() method?
This method shuffles the given string or an array. It randomizes the items in the array. This method is present in the random module. So, we need to import it and then we can call the function. It shuffles elements each time when the function calls and produces different output.
20. What is the use of break statement?
It is used to terminate the execution of the current loop. Break always breaks the current execution and transfer control to outside the current block. If the block is in a loop, it exits from the loop, and if the break is in a nested loop, it exits from the innermost loop.
21. How to create a Unicode string in Python?
In Python 3, the old Unicode type has replaced by “str” type, and the string is treated as Unicode by default. We can make a string in Unicode by using art.title.encode(“utf-8”) function.
22. Draw a comparison between the range and xrange in Python?
In terms of functionality, both range and xrange are identical. Both allow for generating a list of integers. The main difference between the two is that while range returns a Python list object, xrange returns an xrange object.
Xrange is not able to generate a static list at runtime the way range does. On the contrary, it creates values along with the requirements via a special technique called yielding. It is used with a type of object known as generators.
If you have a very enormous range for which you need to generate a list, then xrange is the function to opt for. This is especially relevant for scenarios dealing with a memory-sensitive system, such as a smartphone.
The range is a memory beast. Using it requires much more memory, especially if the requirement is gigantic. Hence, in creating an array of integers to suit the needs, it can result in a Memory Error and ultimately lead to crashing the program. (python interview questions and answers)
23. Give a detailed explanation about setting up the database in Django?
The process of setting up a database is initiated by using the command edit mysite/setting.py. This is a normal Python module with a module-level representation of Django settings. Django relies on SQLite by default, which is easy to be used as it doesn’t require any other installation.
SQLite stores data as a single file in the filesystem. Now, you need to tell Django how to use the database. For this, the project’s setting.py file needs to be used. Following code must be added to the file for making the database workable with the Django project:
24. How will you distinguish between NumPy and SciPy?
Typically, NumPy contains nothing but the array data type and the most basic operations, such as basic element-wise functions, indexing, reshaping, and sorting. All the numerical code resides in SciPy.
As one of NumPy’s most important goals is compatibility, the library tries to retain all features supported by either of its predecessors. Hence, NumPy contains a few linear algebra functions despite the fact that these more appropriately belong to the SciPy library.
SciPy contains fully-featured versions of the linear algebra modules available to NumPy in addition to several other numerical algorithms.
25. What do you understand by monkey patching in Python?
The dynamic modifications made to a class or module at runtime are termed as monkey patching in Python. Consider the following code snippet.
26. How to save an image when you know the URL?
To save an image locally, you would use this type of a code:
27. What Packages in the Standard Library, Useful for Data Science Work, Do You Know?
When Guido van Rossum created Python in the 1990s, it wasn’t built for data science. Yet, today, Python is the leading language for machine learning, predictive analytics, statistics, and simple data analytics.
This is because Python is a free and open-source language that data professionals could easily use to develop tools that would help them complete data tasks more efficiently.
The following packages in the Python Standard Library are very handy for data science projects:
NumPy (or Numerical Python) is one of the principle packages for data science applications. It’s often used to process large multidimensional arrays, extensive collections of high-level mathematical functions, and matrices. Implementation methods also make it easy to conduct multiple operations with these objects.
There have been many improvements made over the last year that have resolved several bugs and compatibility issues. NumPy is popular because it can be used as a highly efficient multi-dimensional container of generic data. It’s also an excellent library as it makes data analysis simple by processing data faster while using a lot less code than lists. (Python Training Online)
Pandas is a Python library that provides highly flexible and powerful tools and high-level data structures for analysis. Pandas is an excellent tool for data analytics because it can translate highly complex operations with data into just one or two commands.
Pandas comes with a variety of built-in methods for combining, filtering, and grouping data. It also boasts time-series functionality that is closely followed by remarkable speed indicators.
SciPy is another outstanding library for scientific computing. It’s based on NumPy and was created to extend its capabilities. Like NumPy, SciPy’s data structure is also a multidimensional array that’s implemented by NumPy.
The SciPy package contains powerful tools that help solve tasks related to integral calculus, linear algebra, probability theory, and much more.
Recently, this Python library went through some major build improvements in the form of continuous integration into multiple operating systems, methods, and new functions. Optimizers were also updated, and several new BLAS and LAPACK functions were wrapped.
28. What is a decorator?
APEX syntax has different features such as variable declaration to store the different values in the memory. The queries will be like SOQL which will be used to execute the queries, loop statements to perform the iterations in performing the operations, flow control statements can be used to control the flow execution whether to start or stop the execution process, DML statements can be used to manipulate the data by executing the queries. (python interview questions and answers)
29. How many Keywords are there in Python? And why should we know them?
There are 33 keywords in Python. We should know them to know about their use so that in our work we can utilize them. Another thing is, while naming a variable, the variable name cannot be matched with the keywords. So, we should know about all the keywords.
30. How do you execute a Python Script?
From the command line, type python .py or pythonx.y
.py where the x.y is the version of the Python interpreter desired.
Learn how to use Python, from beginner basics to advanced techniques, with online video tutorials taught by industry experts. Enroll for Free Python Training Demo!
31. When would you use triple quotes as a delimiter?
APEX syntax has different features such as variable declaration to store the different values in the memory. The queries will be like SOQL which will be used to execute the queries, loop statements to perform the iterations in performing the operations, flow control statements can be used to control the flow execution whether to start or stop the execution process, DML statements can be used to manipulate the data by executing the queries.
32. What is Abnormal Termination?
The concept of terminating the program in the middle of its execution without executing the last statement of the main module is known as an abnormal termination
Abnormal termination is an undesirable situation in programming languages.
33. What is Multithreading?
Thread Is a functionality or logic which can execute simultaneously along with the other part of the program
Thread is a lightweight process
Any program which is under execution is known as process
We can define the threads in python by overwriting run method of thread class
Thread class is a predefined class which is defined in threading module
Thread in module is a predefined module
If we call the run method directly the logic of the run method will be executed as a normal method logic
In order to execute the logic of the run method as we use start method of thread class.
34. Explain Python is one Line?
Python is a modern powerful interpreted language with threads, objects, modules, exceptions and also have the property of automatic memory management.
35. Describe how to send email from a Python Script?
The smtplib module is used to defines an SMTP client session object that can be used to send email using Pythons Script. (python interview questions and answers)
36. Does Python allow you to program in a structured style?
Yes. It does allow to code is a structured as well as Object-oriented style. It offers excellent flexibility to design and implement your application code depending on the requirements of your application.
37. Explain List, Tuple, Set, and Dictionary and provide at least one instance where each of these collection types can be used?
List: Collection of items of different data types which can be changed at run time.
Tuple: Collection of items of different data types which cannot be changed. It only has read-only access to the collection. This can be used when you want to secure your data collection set and does not need any modification.
Set: Collection of items of the similar data type.
Dictionary: Collection of items with key-value pairs.
Generally, List and Dictionary are extensively used by programmers as both of them provide flexibility in data collection.
38. How does For loop and While loop differ in Python and when do you choose to use them?
For loop is generally used to iterate through the elements of various collection types such as List, Tuple, Set, and Dictionary.
While loop is the actual looping feature that is used in any other programming language. This is how Python differs in handling loops from the other programming languages.
39. Explain Python Functions?
A function is a section of the program or a block of code that is written once and can be executed whenever required in the program. A function is a block of self-contained statements which has a valid name, parameters list, and body. Functions make programming more functional and modular to perform modular tasks. Python provides several built-in functions to complete tasks and also allows a user to create new functions as well.
40. What is the Python decorator?
Python decorator is a concept which allows to call or declare a function inside a function, pass a function as an argument, return a function from the function. The decorator provides extra facility to the function. It also helps to organize a piece of code within a function.
41. Describe how multithreading is achieved in Python?
Even though Python comes with a multi-threading package, if the motive behind multithreading is to speed the code then using the package is not the go-to option.
The package has something called the GIL or Global Interpreter Lock, which is a construct. It ensures that one and only one of the threads execute at any given time. A thread acquires the GIL and then do some work before passing it to the next thread.
This happens so fast that to a user it seems that threads are executing in parallel. Obviously, this is not the case as they are just taking turns while using the same CPU core. Moreover, GIL passing adds to the overall overhead to the execution.
Hence, if you intend to use the threading package for speeding up the execution, using the package is not recommended. (python interview questions and answers)
42. What do you understand by the process of compilation and linking in Python?
In order to compile new extensions without any error, compiling and linking is used in Python. Linking initiates only and only when the compilation is complete.
In the case of dynamic loading, the process of compilation and linking depends on the style that is provided with the concerned system. In order to provide dynamic loading of the configuration setup files and rebuilding the interpreter, the Python interpreter is used.
43. What Are Class Or Static Variables In Python Programming?
In Python, all the objects share common class or static variables.
But the instance or non-static variables are altogether different for different objects.
The programming languages like C++ and Java need to use the static keyword to make a variable as the class variable. However, Python has a unique way to declare a static variable.
All names initialized with a value in the class declaration becomes the class variables. And those which get assigned values in the class methods becomes the instance variables.
44. What Is A Function In Python Programming?
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.
45. What Is Python, What Are The Benefits Of Using It, And What Do You Understand Of PEP 8?
Benefits Of Python Programming
Python is a dynamic-typed language. It means that you don’t need to mention the data type of variables during their declaration. It allows to set variables like var1=101 and var2 =” You are an engineer.” without any error.
Python supports object orientated programming as you can define classes along with the composition and inheritance. It doesn’t use access specifiers like public or private).
Functions in Python are like first-class objects. It suggests you can assign them to variables, return from other methods and pass as arguments.
Developing using Python is quick but running it is often slower than compiled languages. Luckily, Python enables to include the “C” language extensions so you can optimize your scripts.
Python has several usages like web-based applications, test automation, data modeling, big data analytics and much more. Alternatively, you can utilize it as a “glue” layer to work with other languages.
PEP 8 is the latest Python coding standard, a set of coding recommendations. It guides to deliver more readable Python code.
You may erroneously expect list1 to be equal to  and list3 to match with [‘a’], thinking that the list argument will initialize to its default value of  every time there is a call to the extendList.
However, the flow is like that a new list gets created once after the function is defined. And the same get used whenever someone calls the extendList method without a list argument. It works like this because the calculation of expressions (in default arguments) occurs at the time of function definition, not during its invocation.
The list1 and list3 are hence operating on the same default list, whereas list2 is running on a separate object that it has created on its own (by passing an empty list as the value of the list parameter).