Top 100 Python Interview Questions & Answers

Primavera P6 is the newest addition to the suite of project management solutions that is project, program and portfolio management tool which is one of the dominant project management software tools that is used for planning, managing and executing projects in a number of diverse industries, such as construction, manufacturing, energy, and IT.

Our Primavera Interview Questions is the one-stop resource which helps you to boost your interview preparation. The main aim of our blog is to boost your confident level and make you crack the interview successfully. We have 100+ questions on Primavera Programming basics prepared by our expert team that help you with different expertise levels to reap the maximum benefit from our blog. These most frequently asked questions are revised every three months to cope up with the industry standard.

Frequently asked Python Interview Questions

Q1.Define Python?

Answer:Python is a high-level, object-oriented, general-purpose computer programming language which can run on different platforms such as Windows, Linux, UNIX, and Macintosh. It is easy to learn with built-in data structures, libraries, dynamic typing which supports objects, modules, threads, exception-handling, and automatic memory management that helps in modelling real-world problems and building applications to solve these problems.

Q2. What is scope in Python?

Answer:A scope is a block of code where an object in Python remains relevant. Namespaces uniquely identify all the objects inside a program

  • A local scope refers to the local objects available in the current function.
  • A global scope refers to the objects available throughout the code execution since their inception.
  • A module-level scope refers to the global objects of the current module accessible in the program.
  • An outermost scope refers to all the built-in names callable in the program.
  • The objects in this scope are searched last to find the name referenced.

Q3. What are the key features of Python?

  • Python is dynamically typed, interpreted language which does not need to be compiled before it is run and to state the types of variables when declaring them or anything like that.
  • Python is an object oriented programming which allows the definition of classes along with composition and inheritance.
  • Python functions are first-class objects that can be assigned to variables, returned from other functions and passed into functions.
  • Python is used in– web applications, automation, scientific modelling, big data applications and many more.

Q4. What is PEP 8?

Answer:PEP 8 stands for Python Enhancement Proposal which is a document that provides guidelines on how to write the Python code. It is a set of rules that specify how to format Python code for maximum readability.

Q5. What are the common built in data types in Python?

  • Integers
  • Floating-point
  • Complex numbers
  • Strings
  • Boolean
  • Built-in functions

Q6. What are Python modules?

Answer: Python modules are files containing Python code that can be imported inside another Python Program. This code can either be functions classes or variables. A Python module is a .py file containing executable code.

Some of the commonly used built-in modules are:
  • os
  • sys
  • math
  • random
  • data time
  • JSON

Attend a Free Online Mock Interview

Q7. What are the applications of Python?

Answer:
  • Web and Internet Development/li>
  • Games
  • Scientific and computational applications
  • Language development
  • Image processing and graphic design applications
  • Enterprise and business applications development
  • Operating systems
  • GUI based desktop applications

Q8. What are the advantages of Python?

  • Python is an interpreted language that does not require prior compilation of code and executes instructions directly.
  • It is Free and open source which is very flexible and extensible with any module.
  • Python is a high level language that allows to implement the Object-Oriented concepts to build application solution.
  • It has built-in data structure: Tuple, List, and Dictionary
  • Python programs are readable that can run on cross platforms without affecting its performance.

Q9. Explain Python Function?

Answer: A function is a block of self-contained statements that is written once with a valid name, parameters list, body and can be executed whenever required in the program. Python provides several built-in functions to complete tasks and also allows a user to create new functions as well.
Built-In Functions: E.g.: copy(), len(), count()
User-defined Functions: are defined by a user known as user-defined functions.

Q10. What is namespace?

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

  • Local Namespace 
  • Global Namespace.
  • Built-in Namespace 

Q11. What are local and global variables?

Answer: Local variable is declared inside a function stored on the stack whereas Global variable is declared outside the function stored on a fixed location decided by the compiler. Local variable doesn't provide data sharing whereas Global variable provides data sharing.

Q12. What is self?

Answer: Self is an instance or an object of a class that is explicitly included as the first parameter. It helps to differentiate between the methods and attributes of a class with local variables. The self-variable in the init method refers to the newly created object while in other methods, it refers to the object whose method was called.

Q13. What is slicing in Python?

Answer:Slicing can be done on strings, arrays, lists, and tuples that start is the starting index from where to slice and stop is the ending index. Step is the number of steps to jump. Default value for start is 0, stop is number of items, step is 1.
Syntax for slicing is [start : stop : step].

Q14. What are decorators?

Answer:Decorators are useful tool that allows to add functionality to an existing code. It allows the user to wrap another function to extend the behaviour of the wrapped function, without permanently modifying it.

Q15. How Python is interpreted?

Answer:In python, .py source code is first compiled to give .pyc which is bytecode. This bytecode can be then interpreted by the official CPython or JIT(Just in Time compiler) compiled by PyPy. Source code is a file with .py extension.

Python compiles the source code to a set of instructions for a virtual machine. The Python interpreter is an implementation of that virtual machine. This intermediate format is called “bytecode”.

Q16. How are arguments passed by value or by reference in python?

Answer:

  • Pass by value: Copy of the actual object is passed. Changing the value of the copy of the object will not change the value of the original object.
  • Pass by reference: Reference to the actual object is passed. Changing the value of the new object will change the value of the original object.
  • In Python, arguments are passed by reference, i.e., reference to the actual object is passed.

Q17. How do you create a class?

Answer: Python is an object oriented programming language in which everything is an object, with its properties and methods.
A Class is a blueprint for creating objects.To creates a class, use the keyword class:
Example:
Create a class named MyClass, with a property named x:
class MyClass:
  x = 5

Q18. Are access specifiers used in python?

Answer: Python does not make use of access specifiers specifically like private, public, protected, etc. However, it does not deprive this to any variables. It has the concept of imitating the behaviour of variables by making use of a single (protected) or double underscore (private) as prefixed to the variable names. By default, the variables without prefixed underscores are public.

Q19. Python an interpreted language. Explain.

Answer: An interpreted language is any programming language which is not in machine-level code before runtime. Therefore, Python is an interpreted language.

Q20.What is the difference between .py and .pyc files?

Answer: The .py files are the python source code files. While the .pyc files contain the bytecode of the python files, .pyc files are created when the code is imported from some other source. The interpreter converts the source .py files to .pyc files which help by saving time.

Q21. How is memory managed in Python?

Answer:Memory management is managed by Python private heap space where all Python objects and data structures are located. The python interpreter takes care of the private heap. The allocation of heap space for Python objects is done by Python’s memory manager. The core API gives access to some tools for the programmer to code.
Python has an inbuilt garbage collector, which recycles all the unused memory and so it can be made available to the heap space.

Q22. How to install Python on Windows and set path variable?

Answer: To install Python on Windows, follow the below steps:

  • Install python from this link: https://www.python.org/downloads/
  • After this, install it on your PC. Look for the location where PYTHON has been installed on your PC using the following command on your command prompt: cmd python. 
  • Then go to advanced system settings and add a new variable and name it as PYTHON_NAME and paste the copied path
  • Look for the path variable, select its value and select ‘edit’.
  • Add a semicolon towards the end of the value if it’s not present and then type %PYTHON_HOME%

Q23. What is a lambda function?

Answer: An anonymous function is known as a lambda function. This function can have any number of parameters but, can have just one statement.
Example:
A=lambda x,y:xy

Q24. What is the difference between range & xrange?

Answer: Xrange and range are the exact same like functionality that provide a way to generate a list of integers to use. The difference is that range returns a Python list object and x range returns an xrange object that doesn’t generate a static list at run-time like range does. It creates the values as need with a special technique called yielding.

Q25.What are the generators in python?

Answer: Functions that return an iterable set of items are called generators. It is a special type of function which returns an iterator object with a sequence of values. In a generator function, a yield statement is used rather than a return statement.

Q26.What is the usage of help() and dir() function in Python?

Answer:

  • Help() function: is used to display the documentation string and also facilitates you to see the help related to modules, keywords, attributes, etc.
  • Dir() function: is used to display the defined symbols.
  • Both functions are accessible from the Python interpreter and used for viewing a consolidated dump of built-in functions. 

Q27.Does Python have OOps concepts?

Answer: Python is an object-oriented programming language which means that any program can be solved by creating an object model. However, Python can be treated as procedural as well as structural language.

Q28. What are Python libraries? Name a few of them.

Answer: Python libraries are a collection of Python packages. Some of the majorly used python libraries are – Numpy, Pandas, Matplotlib, Scikit-learn and many more.

Q29. What is Polymorphism?

Answer:Polymorphism means the ability to take multiple forms. So, for instance, if the parent class has a method named ABC then the child class also can have a method with the same name ABC having its own parameters and variables. Python allows polymorphism.

Q30. What is map function in Python?

Answer: Map function executes the function given as the first argument on all the elements of the iterable given as the second argument. If the function given takes in more than 1 argument, then many iterables are given. #Follow the link to know more similar functions.

Q31. Define encapsulation?

Answer:Encapsulation means binding the code and the data together. A Python class in an example of encapsulation.

Q32. Explain Inheritance with an example?

Answer: Inheritance allows one class to gain all the members (say attributes and methods) of another class. Inheritance provides code reusability, makes it easier to create and maintain an application. The class from which we are inheriting is called super-class and the class that is inherited is called a derived / child class.

Q33. What are Python packages?

Answer: Python packages are namespaces containing multiple modules. It is basically a directory with Python files and a file with the name __init__ . py. 

Q34. What is lambda function in Python?

Answer: The anonymous function in python is a function that is defined without a name. The normal functions are defined using a keyword "def", whereas, the anonymous functions are defined using the lambda function. The anonymous functions are also called as lambda functions.

Q35.Why is finalize used?

Answer: Finalize method is used for freeing up the unmanaged resources and clean up before the garbage collection method is invoked. This helps in performing memory management tasks.

Q36. What is a dynamically typed language?

Answer: Typing refers to type-checking in programming languages. In a strongly-typed language, such as Python, "1" + 2 will result in a type error. On the other hand, a weakly-typed language, such as Javascript, will simply output "12" as result.
Type-checking can be done at two stages -
Static - Data Types are checked before execution.
Dynamic - Data Types are checked during execution.
Python is an interpreted language, executes each statement line by line and thus type-checking is done on the fly, during execution. Hence, Python is a Dynamically Typed Language.

Q37.What is pass in Python?

Answer: The pass keyword represents a null operation which is generally used for the purpose of filling up empty blocks of code that may execute during runtime but has yet to be written. Without the pass statement in the following code, we may run into some errors during code execution.

Q38. What is __init__?

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

Q39. How do you copy an object in Python?

Answer: In Python, the assignment statement (= operator) creates a binding between the existing object and the target variable name. To create copies of an object, we need to use the copy module. There are two ways of creating copies for the given object using the copy module -
Shallow Copy is a bit-wise copy of an object in which the copied object created has an exact copy of the values in the original object. If either of the values is a reference to other objects, just the reference addresses for the same are copied.
Deep Copy copies all values recursively from source to target object, i.e. it even duplicates the objects referenced by the source object.

Q40. Explain split() and join() functions in Python?

Answer: Use split() function to split a string based on a delimiter to a list of strings.
Use join() function to join a list of strings based on a delimiter to give a single string.
string = "This is a string."
string_list = string.split(' ') #delimiter is ‘space’ character or ‘ ‘
print(string_list) #output: ['This', 'is', 'a', 'string.']
print(' '.join(string_list)) #output: This is a string.

Q41. What do you know about pandas?

Answer:

  • Pandas is an open-source, python-based library used in data manipulation applications requiring high performance. The name is derived from “Panel Data” having multidimensional data. This was developed in 2008 by Wes McKinney and was developed for data analysis.
  • Pandas are useful in performing 5 major steps of data analysis - Load the data, clean/manipulate it, prepare it, model it, and analyze the data.

Q42. What do you understand by NumPy?

Answer: NumPy is short for NUMerical PYthon which is one of the most popular, easy-to-use, versatile, open-source, python-based, general-purpose package that is used for processing arrays. This is very famous for its highly optimized tools that result in high performance and powerful N-Dimensional array processing feature that is designed explicitly to work on complex arrays.
It is flexible to perform various operations like trigonometric operations, algebraic and statistical computations which is most commonly used in performing scientific computations and various broadcasting functions.

Q43. What are some of the most commonly used built-in modules in Python?

Answer: Python modules are the files having python code which can be functions, variables or classes with .py extension. The most commonly available built-in modules are:

  • os
  • math
  • sys
  • random
  • re
  • date
  • time
  • JSON

Q44.What is main function in python? How do you invoke it?

Answer: In the programming language world, the main is considered as an entry point for a program execution. In python, it is known that the interpreter serially interprets the file line-by-line which means that python does not provide main() function explicitly. The execution can be done by defining user-defined main() function and by using the __name__ property of python file. This __name__ variable is a special built-in variable that points to the name of the current module. 

Q45. What are Keywords?

Answer: Keywords are reserved words which are used as identifiers, function name or variable name. They help define the structure and syntax of the language. There are a total of 33 keywords in Python 3.7 which can change in the next version, i.e., Python 3.8

Q46. What is dictionary in Python? Give an example.

Answer:A Python dictionary is a collection of items in no particular order. Python dictionaries are written in curly brackets with keys and values. Dictionaries are optimised to retrieve value for known keys.
Example
d={“a”:1,”b”:2}

Q47. What is the bytes() function?

Answer: The bytes() function returns a bytes object. It is used to convert objects into bytes objects, or create empty bytes object of the specified size.

Q48. What is a dynamically typed language?

Answer: Before we understand a dynamically typed language, we should learn about what typing is. Typing refers to type-checking in programming languages. In a strongly-typed language, such as Python, "1" + 2 will result in a type error since these languages don't allow for "type-coercion" (implicit conversion of data types). On the other hand, a weakly-typed language, such as Javascript, will simply output "12" as result.
Type-checking can be done at two stages -
Static - Data Types are checked before execution.
Dynamic - Data Types are checked during execution.
Python is an interpreted language, executes each statement line by line and thus type-checking is done on the fly, during execution. Hence, Python is a Dynamically Typed Language.

Q49.What are lists and tuples? What is the key difference between the two?

Answer: Lists and Tuples are both sequence data types that can store a collection of objects in Python. The objects stored in both sequences can have different data types. Lists are represented with square brackets ['sara', 6, 0.19], while tuples are represented with parantheses ('ansh', 5, 0.97).
The key difference is that the lists are mutable, tuples on the other hand are immutable objects. This means that lists can be modified, appended or sliced on the go but tuples remain constant and cannot be modified in any manner.

Q50. What is break, continue statements?

Answer: The break statement terminates the loop immediately and the control flows to the statement after the body of the loop.
The continue statement terminates the current iteration of the statement, skips the rest of the code in the current iteration and the control flows to the next iteration of the loop.

Q51. What is PYTHONPATH?

Answer: PYTHONPATH is an environment variable which can set to add additional directories where Python will look for modules and packages. This is especially useful in maintaining Python libraries that do not wish to install in the global default location.

Q52. What are iterators in Python?

Answer: An iterator is an object which remembers its state i.e., where it is during iteration. __iter__() method initializes an iterator that has a __next__() method which returns the next item in iteration and points to the next element.
Upon reaching the end of iterable object __next__() must return StopIteration exception and also self-iterable.Iterators are objects with which we can iterate over iterable objects like lists, strings, etc.

Q53. Explain how to delete a file in Python?

Answer:To delete a file use command os.remove(file_name)
import os
os.remove("ChangedFile.csv")
print("File Removed!")

Q54. How do you create a class in Python?

Answer: To create a class in python, we use the keyword “class” as shown in the example below:
class InterviewbitEmployee:
def __init__(self, emp_name):
self.emp_name = emp_name

Q55. What do you understand by reindexing in pandas?

Answer:Reindexing is the process of conforming a dataframe to a new index with optional filling logic. If the values are missing in the previous index, then NaN/NA is placed in the location.
A new object is returned unless a new index is produced that is equivalent to the current one. The copy value is set to False. This is also used for changing the index of rows and columns in the dataframe.

Q56. How will you read CSV data into an array in NumPy?

Answer: This can be achieved by using the genfromtxt() method by setting the delimiter as a comma.
from numpy import genfromtxt
csv_data = genfromtxt('sample_file.csv', delimiter=',')

Q57. Define GIL?

Answer: GIL stands for Global Interpreter Lock which is a mutex used for limiting access to python objects and aids in effective thread synchronization by avoiding deadlocks. It helps in achieving multitasking.

Q58. Are there any tools for identifying bugs and performing static analysis in python?

Answer: Yes, there are tools like PyChecker and Pylint which are used as static analysis and linting tools respectively. PyChecker helps find bugs in python source code files and raises alerts for code issues and their complexity. Pylint checks for the module’s coding standards and supports different plugins to enable custom features to meet this requirement.

Q59. What is a classifier?

Answer: Classifiers are special hypotheses that are used to assign class labels to any particular data point which is used to predict the class of any data point. A classifier is a method used in supervised learning in Machine Learning that uses training data to understand the relation between input variables and the class.

Q60. What are the different types of operators in Python?

Answer: Python has the following basic operators:
Arithmetic( Addition(+), Substraction(-), Multiplication(*), Division(/), Modulus(%) ), Relational ( <, >, <=, >=, ==, !=, ),
Assignment ( =. +=, -=, /=, *=, %= ),
Logical ( and, or not ), Membership, Identity, and Bitwise Operators

Q61. What are the tools present to perform statics analysis?

Answer: The two static analysis tools used to find bugs in Python are:
(i)Pychecker
(ii)Pylint
Pychecker detects bugs from the source code and warns about its style and complexity while, Pylint checks whether the module matches upto a coding standard.

Q62. What does len() do?

Answer: len() is used to determine the length of a string, a list, an array, and so on. ex: str = “greatlearning”
print(len(str))
output: 13

Q63. What is the type ()?

Answer: Type() is a built-in method which either returns the type of the object or returns a new type object based on the arguments passed.
ex: a = 100
type(a)
output: int

Q64. Pattern questions. Print the following pattern?

#
# #
# # #
# # # #
# # # # #

Answer: def pattern_1(num):
for i in range(0, n):
for j in range(0, i+1):
print("#",end="")
print("\r")
num = int(input("Enter the number of rows in pattern: "))
pattern_1(num)

Q65. Write a python program to print the factorial of a number?

Answer: To print the factorial of a number: factorial = 1 #check if the number is negative, positive or zero if num<0: print("Sorry, factorial does not exist for negative numbers") elif num==0: print("The factorial of 0 is 1") else for i in range(1,num+1): factorial = factorial*i print("The factorial of",num,"is",factorial)

Q66. What are the limitations of Python?

Answer: There are certain limitations of Python, which include the following:
Python has design restrictions which is slower when compared with C and C++ or Java. It is inefficient in mobile computing that consists of an underdeveloped database access layer.

Q67. Can we use a break and continue together in Python? How?

Answer: There are certain limitations of Python, which include the following:
Python has design restrictions which is slower when compared with C and C++ or Java. It is inefficient in mobile computing that consists of an underdeveloped database access layer.

Q68.Can we use a break and continue together in Python? How?

Answer: Break and continue can be used together in Python. The break will stop the current loop from execution, while jump will take to another loop.

Q69. What are the different stages of the Life Cycle of a Thread?

Answer: The different stages of the Life Cycle of a Thread can be stated as follows.

  • Create a class where we can override the run method of the Thread class. We make a call to start() on the new thread. The thread is taken forward for scheduling purposes.
  • Execution takes place wherein the thread starts execution, and it reaches the running state. Thread wait until the calls to methods including join() and sleep() takes place.
  • After the waiting or execution of the thread, the waiting thread is sent for scheduling. Running thread is done by executing the terminates and reaches the dead state.

Q70. What is Flask and what are the benefits of using it?

Answer: Flask is a web microframework for Python with Jinja2 and Werkzeug as its dependencies. As such, it has some notable advantages:
Flask has little to no dependencies on external libraries because there is a little external dependency to update and fewer security bugs, the web microframework is lightweight to use.

Q71.Explain the Dogpile effect.

Answer: The event when the cache expires and websites are hit by multiple requests made by the client at the same time. Using a semaphore lock prevents the Dogpile effect. In this system when value expires, the first process acquires the lock and starts generating new value.

Q72. What is [::-1} used for?

Answer: [::-1} reverses the order of an array or a sequence. However, the original array or the list remains unchanged.

Q73.How are comments written in Python?

Answer: Comments in Python start with a # character, they can also be written within docstring(String within triple quotes)

Q74. Is indentation necessary in Python?

Answer:Indentation is required in Python if not done properly the code is not executed properly and might throw errors. Indentation is usually done using four space characters.

Q75. Write a program for counting the number of every character of a given text file?

Answer: The idea is to use collections and pprint module as shown below: import collections import pprint with open("sample_file.txt", 'r') as data: count_data = collections.Counter(data.read().upper()) count_value = pprint.pformat(count_data) print(count_value)

Q76. How can the ternary operators be used in python?

Answer: The Ternary operator is the operator that is used to show the conditional statements. This consists of the true or false values with a statement that has to be evaluated for it. Syntax: The Ternary operator will be given as: [on_true] if [expression] else [on_false]x, y = 25, 50big = x if x < y else y

Q77. Explain split(), sub(), subn() methods of “re” module in Python?

Answer: To modify the strings, Python’s “re” module is providing 3 methods. They are: split() – uses a regex pattern to “split” a given string into a list.
sub() – finds all substrings where the regex pattern matches and then replace them with a different string
subn() – it is similar to sub() and also returns the new string along with the no. of replacements.

Q78. What is the difference between copy and view in an array?

Answer: The main difference between a copy and a view of an array is that the copy is a new array, and the view is just a view of the original array. The copy owns the data and any changes made to the copy will not affect original array, and any changes made to the original array will not affect the copy.
The view does not own the data and any changes made to the view will affect the original array, and any changes made to the original array will affect the view.

Q79. How to install NumPy?

Answer: Install NumPy after installing Python, PIP using this command:
C:\Users\Your Name>pip install numpy
If this command fails, then use a python distribution that already has NumPy
installed like, Anaconda, Spyder etc.

Q80. How to create a new fine in Python?

Answer: To create a new file in Python, use the open() method, with one of the following parameters:
x- Create - will create a file, returns an error if the file exist
a- Append - will create a file if the specified file does not exist
w- Write - will create a file if the specified file does not exist

Q81. What are the different types of inheritance in Python?

Answer:

  • Single Inheritance – where a derived class acquires the members of a single super class.
  • Multi-level inheritance – a derived class d1 in inherited from base class base1, and d2 are inherited from base2.
  • Hierarchical inheritance – from one base class you can inherit any number of child classes
  • Multiple inheritances – a derived class is inherited from more than one base class.

Q82.What is type conversion in Python?

Answer: Python provides with a much needed functionality of converting one form of data type into the needed one and this is known as type conversion.
Type Conversion is classified into types:
1. Implicit Type Conversion: In this form of Type conversion python interpreter helps in automatically converting the data type into another data type without any User involvement.
2. Explicit Type Conversion: In this  form of Type conversion the data  type inn changed into a required type by the user.

Q83. State few functions of explicit conversion ?

Answer: int() –  function converts any data type into integer.
float() –   function converts any data type into float.
ord() –   function converts characters into integer.
hex() –  function converts integers to hexadecimal strings.
oct() –   function converts integer to octal strings.
tuple() – function convert to a tuple.

Q84. Is python case sensitive?

Answer: Yes, Python is a case sensitive language which means that Function and function both are different in python alike SQL and Pascal.

Q85. How can you randomize the items of a list in place in Python?

Answer: This can be easily achieved by using the Shuffle() function from the random library as shown below:
from random import shuffle
List = ['He', 'Loves', 'To', 'Code', 'In', 'Python']
shuffle(List)
print(List)
Output: [‘Loves’,’He’ ,’To ,’In’, ‘Python’,’Code’]

Q86.What are negative indexes and why are they used ?

Answer: To access an element from ordered sequences, we simply use the index of the element, which is the position number of that particular element. The index usually starts from 0, i.e., the first element has index 0, the second has 1, and so on.

Q87. What are the generators in python?

Answer: Generator is a special type of function that returns an iterable set of items that does not return a single value.

Q88.What are python comprehensions?

Answer: Python comprehensions are like decorators, that help to build altered and filtered lists, dictionaries or sets from a given list, dictionary or set. Comprehension saves a lot of time and code that might be considerably more complex and time consuming.
Comprehensions are beneficial in following scenarios:
Performing mathematical operations on the entire list
Performing conditional filtering operations on the entire list
Combining multiple lists into one
Flattening a multi-dimensional list

Q89. What do you understand by Tkinter?

Answer: Tkinter is a built-in Python module that is used to create GUI applications. It is Python’s standard toolkit for GUI development. Tkinter comes with Python, so there is no separate installation needed. We can start using it by importing it in our script.

Q90. What are the generators in python?

Answer: Python has various file processing modes. To open a file, there are three modes: read-only mode (r) write-only mode (w) read–write mode (rw) To open a text file using the above modes, we will have to append‘t’ with them as follows: read-only mode (rt) write-only mode (wt) read–write mode (rwt) Similarly, a binary file can be opened by appending ‘b’ with them as follows: read-only mode (rb) write-only mode (wb) read–write mode (rwb) To append the content in the files, we can use the append mode (a): For text files, the mode would be ‘at’ For binary files, it would be ‘ab’

Q91. Is Python fully object oriented?

Answer: Python does follow an object-oriented programming paradigm and has all the basic OOPs concepts such as inheritance, polymorphism, and more, with the exception of access specifiers. Python doesn’t support strong encapsulation (adding a private keyword before data members). Although, it has a convention that can be used for data hiding, i.e., prefixing a data member with two underscores.

Q92.Explain the use of the 'with' statement and its syntax?

Answer: In Python, using the ‘with’ statement, we can open a file and close it as soon as the block of code, where ‘with’ is used, exits. In this way, we can opt for not using the close() method. with open("filename", "mode") as file_var:

Q93.How will you read a random line in a file?

Answer: We can read a random line in a file using the random module. For example: import random def read_random(fname): lines = open(fname).read().splitlines() return random.choice(lines) print(read_random (‘hello.txt’))

Q94. What is the purpose of is, not and in operators?

Answer: Operators are referred to as special functions that take one or more values(operands) and produce a corresponding result.
is: returns the true value when both the operands are true  (Example: “x” is ‘x’)
not: returns the inverse of the boolean value based upon the operands (example:”1” returns “0” and vice-versa.
In: helps to check if the element is present in a given Sequence or not.

Q95. How to add values to a python array?

Answer: In python, adding elements in an array can be easily done with the help of extend(),append() and insert() functions.

Q96. Write a code to sort a numerical list in Python?

Answer: The following code can be used to sort a numerical list in Python:
list = [“2”, “5”, “7”, “8”, “1”]
list = [int(i) for i in list]
list.sort()
print (list)

Q97. How will you remove the last object from a list in Python?

Answer: list.pop(obj=list[-1]):
Here, −1 represents the last element of the list. Hence, the pop() function removes the last object (obj) from the list.

Q98. What is the difference between / and // operator in Python?

Answer: /: is a division operator and returns the Quotient value.
10/3
3.33
// : is known as floor division operator and used to return only the value of quotient before decimal
10//3
3

Q99. What is regression?

Answer: Regression is termed as supervised machine learning algorithm technique which is used to find the correlation between variables and help to predict dependent variable(y) based upon the independent variable (x).
It is mainly used for prediction, time series modelling, forecasting and determining the causal-effect relationship between variables.
Scikit library is used to implement the regression and all machine learning algorithms.
There are two different type of regression algorithm in machine learning:
Linear Regression: Used when the variables are continuous and numeric in nature.
Logistic Regression: Used when the variables are continuous and categorical in nature.

Q100. What is classification?

Answer: Classification refers to a predictive modelling process where a class label is predicted for a given example of input data. It helps categorize the provided input into a label that other observations with similar features have. For example, it can be used for classifying a mail whether it is spam or not or for checking whether users will churn or not based on their behaviour.
These are some of the classification algorithms used in Machine Learning:
Decision tree
Random forest classifier
Support vector machine