Python Interview Questions and Answers for Fresher and Experienced - Cloud Network

Networking | Support | Tricks | Troubleshoot | Tips

Buymecoffe

Buy Me A Coffee

Saturday, April 13, 2019

Python Interview Questions and Answers for Fresher and Experienced

Q :- What is Python? What are the benefits of using Python?
Ans :- Python is a programming language with objects, modules, threads, exceptions and automatic memory management. The benefits of pythons are that it is simple and easy, portable, extensible, build-in data structure and it is an open source.
Or
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

Q :- How are the functions help() and dir() different?
Ans :- These are the two functions that are accessible from the Python Interpreter. These two functions are used for viewing a consolidated dump of built-in functions.

  1. help() – it will display the documentation string. It is used to see the help related to modules, keywords, attributes, etc.
In order to scrap the web:load the web page which is interesting to you. To load the web page, use “requests” module.
parse HTML from the web page to find the interesting information.Python has few modules for scraping the web. They are urllib2, scrapy, pyquery, BeautifulSoup, etc.
Q :-  What is PEP 8?
Ans :-  PEP 8 is a coding convention, a set of recommendation, about how to write your Python code more readable.

Q :- In Python what are iterators?
Ans :- In Python, iterators are used to iterate a group of elements, containers like list.

Q :- What is unittest in Python?
Ans :- A unit testing framework in Python is known as unittest. It supports sharing of setups, automation testing, shutdown code for tests, aggregation of tests into collections etc.

Q :- In Python what is slicing?
Ans :- A mechanism to select a range of items from sequence types like list, tuple, strings etc. is known as slicing.
Q :- What are generators in Python?
Ans :- The way of implementing iterators are known as generators. It is a normal function except that it yields expression in the function.

Q :- What is docstring in Python?
Ans :- A Python documentation string is known as docstring, it is a way of documenting Python functions, modules and classes.

Q :- How can you copy an object in Python?
Ans :- To copy an object in Python, you can try copy.copy () or copy.deepcopy() for the general case. You cannot copy all objects but most of them.

Q :- What is negative index in Python?
Ans :- Python sequences can be index in positive and negative numbers. For positive index, 0 is the first index, 1 is the second index and so forth. For negative index, (-1) is the last index and (-2) is the second last index and so forth.

Q :- How you can convert a number to a string?
Ans :- In order to convert a number into a string, use the inbuilt function str(). If you want a octal or hexadecimal representation, use the inbuilt function oct() or hex().

Q :- What is the difference between Xrange and range?
Ans :- Xrange returns the xrange object while range returns the list, and uses the same memory and no matter what the range size is.

Q :- What is namespace in Python?
Ans :- In Python, every name introduced has a place where it lives and can be hooked for. This is known as namespace. It is like a box where a variable name is mapped to the object placed. Whenever the variable is searched out, this box will be searched, to get corresponding object.

Q :- What is lambda in Python?
Ans :- It is a single expression anonymous function often used as inline function.

Q :- Why lambda forms in python does not have statements?
Ans :- A lambda form in python does not have statements as it is used to make new function object and then return them at runtime.

Q :- What is pass in Python?
Ans :- Pass means, no-operation Python statement, or in other words it is a place holder in compound statement, where there should be a blank left and nothing has to be written there.

Q :- What is Dict and List comprehensions are?
Ans :- They are syntax constructions to ease the creation of a Dictionary or List based on existing iterable.

Q :- What are the built-in type does python provides?
Ans :- There are mutable and Immutable types of Pythons built in types Mutable built-in types

  1. List
  2. Sets
  3. Dictionaries
  4. Immutable built-in types
  5. Strings
  6. Tuples
  7. Numbers
Q :- What are Python decorators?
Ans :- A Python decorator is a specific change that we make in Python syntax to alter functions easily.

Q :- What is the difference between list and tuple?
Ans :- The difference between list and tuple is that list is mutable while tuple is not. Tuple can be hashed for e.g as a key for dictionaries.

Q :- How are arguments passed by value or by reference?
Ans :- Everything in Python is an object and all variables hold references to the objects. The references values are according to the functions; as a result you cannot change the value of the references. However, you can change the objects if it is mutable.

Q :- How will you reverse a list? Ans :- list.reverse() - Reverses objects of list in place. Q :- How will you remove last object from a list? Ans :- list.pop(obj=list[-1]) - Removes and returns last object or obj from list. Q :- What are negative indexes and why are they used? Ans :- The sequences in Python are indexed and it consists of the positive as well as negative numbers. The numbers that are positive uses ‘0’ that is uses as first index and ‘1’ as the second index and the process goes on like that. The index for the negative number starts from ‘-1’ that represents the last index in the sequence and ‘-2’ as the penultimate index and the sequence carries forward like the positive number. The negative index is used to remove any new-line spaces from the string and allow the string to except the last character that is given as S[:-1]. The negative index is also used to show the index to represent the string in correct order. Q :- Explain split(), sub(), subn() methods of “re” module in Python. Ans :- 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.
Q :- What is the difference between range & xrange? Ans :- For the most part, xrange and range are the exact same in terms of functionality. They both provide a way to generate a list of integers for you to use, however you please. The only difference is that range returns a Python list object and x range returns an xrange object. This means that xrange doesn’t actually generate a static list at run-time like range does. It creates the values as you need them with a special technique called yielding. This technique is used with a type of object known as generators. That means that if you have a really gigantic range you’d like to generate a list for, say one billion, xrange is the function to use. This is especially true if you have a really memory sensitive system such as a cell phone that you are working with, as range will use as much memory as it can to create your array of integers, which can result in a Memory Error and crash your program. It’s a memory hungry beast. Q :- What is pickling and unpickling? Ans :- Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling. Q :- What is map function in Python? Ans :- 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 arguments, then many iterables are given. #Follow the link to know more similar functions Q :- How to get indices of N maximum values in a NumPy array? Ans :- We can get the indices of N maximum values in a NumPy array using the below code: import numpy as np arr = np.array([1, 3, 2, 4, 5]) print(arr.argsort()[-3:][::-1]) Q :- What is a Python module? Ans :- 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 . Q :- Name the File-related modules in Python? Ans :- Python provides libraries / modules with functions that enable you to manipulate text files and binary files on file system. Using them you can create files, update their contents, copy, and delete files. The libraries are : os, os.path, and shutil. Here, os and os.path – modules include functions for accessing the filesystem shutil – module enables you to copy and delete the files. Q :- Explain the use of with statement? Ans :- In python generally “with” statement is used to open a file, process the data present in the file, and also to close the file without calling a close() method. “with” statement makes the exception handling simpler by providing cleanup activities. General form of with: with open(“filename”, “mode”) as file-var: processing statements note: no need to close the file by calling close() upon file-var.close() Q :- Explain all the file processing modes supported by Python? Ans :- Python allows you to open files in one of the three modes. They are: read-only mode, write-only mode, read-write mode, and append mode by specifying the flags “r”, “w”, “rw”, “a” respectively. A text file can be opened in any one of the above said modes by specifying the option “t” along with “r”, “w”, “rw”, and “a”, so that the preceding modes become “rt”, “wt”, “rwt”, and “at”.A binary file can be opened in any one of the above said modes by specifying the option “b” along with “r”, “w”, “rw”, and “a” so that the preceding modes become “rb”, “wb”, “rwb”, “ab”. Q :- How many kinds of sequences are supported by Python? What are they? Ans :- Python supports 7 sequence types. They are str, list, tuple, unicode, byte array, xrange, and buffer. where xrange is deprecated in python 3.5.X. Q :- How do you perform pattern matching in Python? Explain Ans :- Regular Expressions/REs/ regexes enable us to specify expressions that can match specific “parts” of a given string. For instance, we can define a regular expression to match a single character or a digit, a telephone number, or an email address, etc.The Python’s “re” module provides regular expression patterns and was introduce from later versions of Python 2.5. “re” module is providing methods for search text strings, or replacing text strings along with methods for splitting text strings based on the pattern defined. Q :- How to display the contents of text file in reverse order? Ans :- convert the given file into a list. reverse the list by using reversed() Eg: for line in reversed(list(open(“file-name”,”r”))): print(line)
28. What is the difference between NumPy and SciPy? Ans :- In an ideal world, NumPy would contain nothing but the array data type and the most basic operations: indexing, sorting, reshaping, basic element wise functions, et cetera. All numerical code would reside in SciPy. However, one of NumPy’s important goals is compatibility, so NumPy tries to retain all features supported by either of its predecessors. Thus NumPy contains some linear algebra functions, even though these more properly belong in SciPy. In any case, SciPy contains more fully-featured versions of the linear algebra modules, as well as many other numerical algorithms. If you are doing scientific computing with python, you should probably install both NumPy and SciPy. Most new features belong in SciPy rather than NumPy.
Q :- Which of the following is an invalid statement? Ans :-
a) abc = 1,000,000 b) a b c = 1000 2000 3000 c) a,b,c = 1000, 2000, 3000 d) a_b_c = 1,000,000 Answer: b Q :- What is the output of the following? try: if '1' != 1: raise Ans :-
a) some Error has occured b) some Error has not occured c) invalid code d) none of the above Answer: C Q :- Suppose list1 is [2, 33, 222, 14, 25], What is list1[-1] ? Ans :- 25 Q :- To open a file c:\scores.txt for writing? Ans :- fileWriter = open(“c:\\scores.txt”, “w”) Q :- Name few Python modules for Statistical, Numerical and scientific computations ? Ans :- numPy – this module provides an array/matrix type, and it is useful for doing computations on arrays. scipy – this module provides methods for doing numeric integrals, solving differential equations, etc pylab – is a module for generating and saving plots Q :- What is TkInter? Ans :- TkInter is Python library. It is a toolkit for GUI development. It provides support for various GUI tools or widgets (such as buttons, labels, text boxes, radio buttons, etc) that are used in GUI applications. The common attributes of them include Dimensions, Colors, Fonts, Cursors, etc. Q :- Is Python object oriented? what is object oriented programming? Ans :- Yes. Python is Object Oriented Programming language. OOP is the programming paradigm based on classes and instances of those classes called objects. The features of OOP are: Encapsulation, Data Abstraction, Inheritance, Polymorphism. Q :- What is multithreading? Give an example. Ans :- It means running several different programs at the same time concurrently by invoking multiple threads. Multiple threads within a process refer the data space with main thread and they can communicate with each other to share information more easily.Threads are light-weight processes and have less memory overhead. Threads can be used just for quick task like calculating results and also running other processes in the background while the main program is running. Q :- Does Python supports interfaces like in Java? Discuss. Ans :- 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 behaviour. This module was made available from Python 2.7 version onwards. Q :- What are Accessors, mutators, @property? Ans :- Accessors and mutators are often called getters and setters in languages like “Java”. For example, if x is a property of a user-defined class, then the class would have methods called setX() and getX(). Python has an @property “decorator” that allows you to ad getters and setters in order to access the attribute of the class. Q :- Differentiate between append() and extend() methods.? Ans :- Both append() and extend() methods are the methods of list. These methods a re used to add the elements at the end of the list. append(element) – adds the given element at the end of the list which has called this method. extend(another-list) – adds the elements of another-list at the end of the list which is called the extend method. Q :- Name few methods that are used to implement Functionally Ans :- Oriented Programming in Python?
Python supports methods (called iterators in Python3), such as filter(), map(), and reduce(), that are very useful when you need to iterate over the items in a list, create a dictionary, or extract a subset of a list. filter() – enables you to extract a subset of values based on conditional logic. map() – it is a built-in function that applies the function to each item in an iterable. reduce() – repeatedly performs a pair-wise reduction on a sequence until a single value is computed. Q :- What is the output of the following? Ans :- x = [‘ab’, ‘cd’] print(len(map(list, x))) A TypeError occurs as map has no len(). Q :- What is the output of the following? Ans :- x = [‘ab’, ‘cd’] print(len(list(map(list, x)))) Explanation: The length of each string is 2. Q :- Which of the following is not the correct syntax for creating a set? Ans :- a) set([[1,2],[3,4]]) b) set([1,2,2,3,4]) c) set((1,2,3,4)) d) {1,2,3,4} Answer : a Explanation : The argument given for the set must be an iterable. Q :- Explain a few methods to implement Functionally Oriented Programming in Python. Ans :- Sometimes, when we want to iterate over a list, a few methods come in handy. filter() Filter lets us filter in some values based on conditional logic. >>> list(filter(lambda x:x>5,range(8))) [6, 7] map() Map applies a function to every element in an iterable. >>> list(map(lambda x:x**2,range(8))) [0, 1, 4, 9, 16, 25, 36, 49] reduce() Reduce repeatedly reduces a sequence pair-wise until we reach a single value >>> from functools import reduce >>> reduce(lambda x,y:x-y,[1,2,3,4,5]) -13 Q :- Explain database connection in Python Flask? Ans :- Flask supports database powered application (RDBS). Such system requires creating a schema, which requires piping the shema.sql file into a sqlite3 command. So you need to install sqlite3 command in order to create or initiate the database in Flask. Flask allows to request database in three ways before_request() : They are called before a request and pass no arguments after_request() : They are called after a request and pass the response that will be sent to the client teardown_request(): They are called in situation when exception is raised, and response are not guaranteed. They are called after the response been constructed. They are not allowed to modify the request, and their values are ignored.
Q :- Write a Python function that checks whether a passed string is palindrome Or not?
Ans :-
Note: A palindrome is a word, phrase, or sequence that reads the same backward as forward, e.g., madam or nurses run. def isPalindrome(string): left_pos = 0 right_pos = len(string) – 1 while right_pos >= left_pos: if not string[left_pos] == string[right_pos]: return False left_pos += 1 right_pos -= 1 return True print(isPalindrome(‘aza’)) Q :- Write a Python program to calculate the sum of a list of numbers. Ans :-
def list_sum(num_List): if len(num_List) == 1: return num_List[0] else: return num_List[0] + list_sum(num_List[1:]) print(list_sum([2, 4, 5, 6, 7])) Sample Output: 24 Q :- How to retrieve data from a table in MySQL database through Python code? Explain. Ans :-
import MySQLdb module as : import MySQLdb establish a connection to the database. db = MySQLdb.connect(“host”=”local host”, “database-user”=”user-name”, “password”=”password”, “database-name”=”database”)
initialize the cursor variable upon the established connection: c1 = db.cursor() retrieve the information by defining a required query string. s = “Select * from dept” fetch the data using fetch() methods and print it. data = c1.fetch(s) close the database connection. db.close()
Q :- Write a Python program to read a random line from a file. import random Ans :- def random_line(fname): lines = open(fname).read().splitlines() return random.choice(lines) print(random_line(‘test.txt’)) Q :- Write a Python program to count the number of lines in a text file. Ans :- def file_lengthy(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 print(“Number of lines in the file: “,file_lengthy(“test.txt”))
Ans :- list.reverse() - Reverses objects of list in place.

Q :- How will you remove last object from a list?
Ans :- list.pop(obj=list[-1]) - Removes and returns last object or obj from list.

Q :- What are negative indexes and why are they used?
Ans :- The sequences in Python are indexed and it consists of the positive as well as negative numbers. The numbers that are positive uses ‘0’ that is uses as first index and ‘1’ as the second index and the process goes on like that.
The index for the negative number starts from ‘-1’ that represents the last index in the sequence and ‘-2’ as the penultimate index and the sequence carries forward like the positive number.
The negative index is used to remove any new-line spaces from the string and allow the string to except the last character that is given as S[:-1]. The negative index is also used to show the index to represent the string in correct order.

Q :- Explain split(), sub(), subn() methods of “re” module in Python.
Ans :- 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.

Q :- What is the difference between range & xrange?
Ans :- For the most part, xrange and range are the exact same in terms of functionality. They both provide a way to generate a list of integers for you to use, however you please. The only difference is that range returns a Python list object and x range returns an xrange object.
This means that xrange doesn’t actually generate a static list at run-time like range does. It creates the values as you need them with a special technique called yielding. This technique is used with a type of object known as generators. That means that if you have a really gigantic range you’d like to generate a list for, say one billion, xrange is the function to use.
This is especially true if you have a really memory sensitive system such as a cell phone that you are working with, as range will use as much memory as it can to create your array of integers, which can result in a Memory Error and crash your program. It’s a memory hungry beast.

Q :- What is pickling and unpickling?
Ans :- Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.

Q :- What is map function in Python?
Ans :- 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 arguments, then many iterables are given. #Follow the link to know more similar functions

Q :- How to get indices of N maximum values in a NumPy array?
Ans :- We can get the indices of N maximum values in a NumPy array using the below code:
import numpy as np
arr = np.array([1, 3, 2, 4, 5])
print(arr.argsort()[-3:][::-1])

Q :- What is a Python module?
Ans :- 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 .

Q :- Name the File-related modules in Python?
Ans :- Python provides libraries / modules with functions that enable you to manipulate text files and binary files on file system. Using them you can create files, update their contents, copy, and delete files. The libraries are : os, os.path, and shutil.
Here, os and os.path – modules include functions for accessing the filesystem
shutil – module enables you to copy and delete the files.

Q :- Explain the use of with statement?
Ans :- In python generally “with” statement is used to open a file, process the data present in the file, and also to close the file without calling a close() method. “with” statement makes the exception handling simpler by providing cleanup activities.
General form of with:
with open(“filename”, “mode”) as file-var:
processing statements
note: no need to close the file by calling close() upon file-var.close()

Q :- Explain all the file processing modes supported by Python?
Ans :- Python allows you to open files in one of the three modes. They are: 

read-only mode, write-only mode, read-write mode, and append mode by specifying the flags “r”, “w”, “rw”, “a” respectively. 

A text file can be opened in any one of the above said modes by specifying the option “t” along with
“r”, “w”, “rw”, and “a”, so that the preceding modes become “rt”, “wt”, “rwt”, and “at”.A binary file can be opened in any one of the above said modes by specifying the option “b” along with “r”, “w”, “rw”, and “a” so that the preceding modes become “rb”, “wb”, “rwb”, “ab”.

Q :- How many kinds of sequences are supported by Python? What are they?
Ans :- Python supports 7 sequence types. They are str, list, tuple, unicode, byte array, xrange, and buffer. where xrange is deprecated in python 3.5.X.

Q :- How do you perform pattern matching in Python? Explain
Ans :- Regular Expressions/REs/ regexes enable us to specify expressions that can match specific “parts” of a given string. For instance, we can define a regular expression to match a single character or a digit, a telephone number, or an email address, etc.The Python’s “re” module provides regular expression patterns and was introduce from later versions of Python 2.5. “re” module is providing methods for search text strings, or replacing text strings along with methods for splitting text strings based on the pattern defined.

Q :- How to display the contents of text file in reverse order?
Ans :- convert the given file into a list.
reverse the list by using reversed()
Eg: for line in reversed(list(open(“file-name”,”r”))):
print(line)

Q :- What is the output of the following? try: if '1' != 1: raise
b) some Error has not occured
c) invalid code
d) none of the above
Ans :- Answer: C

Q :- Suppose list1 is [2, 33, 222, 14, 25], What is list1[-1] ?
Ans :- 25

Q :- To open a file c:\scores.txt for writing?
Ans :- fileWriter = open(“c:\\scores.txt”, “w”)

Q :- Name few Python modules for Statistical, Numerical and scientific computations ?
Ans :- numPy – this module provides an array/matrix type, and it is useful for doing computations on arrays. scipy – this module provides methods for doing numeric integrals, solving differential equations, etc pylab – is a module for generating and saving plots

Q :- What is TkInter?
Ans :- TkInter is Python library. It is a toolkit for GUI development. It provides support for various GUI tools or widgets (such as buttons, labels, text boxes, radio buttons, etc) that are used in GUI applications. The common attributes of them include Dimensions, Colors, Fonts, Cursors, etc.

Q :- Is Python object oriented? what is object oriented programming?
Ans :- Yes. Python is Object Oriented Programming language. OOP is the programming paradigm based on classes and instances of those classes called objects. The features of OOP are:
Encapsulation, Data Abstraction, Inheritance, Polymorphism.

Q :- What is multithreading? Give an example.
Ans :- It means running several different programs at the same time concurrently by invoking multiple threads. Multiple threads within a process refer the data space with main thread and they can communicate with each other to share information more easily.Threads are light-weight processes and have less memory overhead. 

Threads can be used just for quick task like calculating results and also running other processes in the background while the main program is running.

Q :- Does Python supports interfaces like in Java? Discuss.
Ans :- 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 behaviour. 

This module was made available from Python 2.7 version onwards.

Q :- What are Accessors, mutators, @property?
Ans :- Accessors and mutators are often called getters and setters in languages like “Java”. For example, if x is a property of a user-defined class, then the class would have methods called setX() and getX(). Python has an @property “decorator” that allows you to ad getters and setters in order to access the attribute of the class.

Q :- Differentiate between append() and extend() methods.?
Ans :- Both append() and extend() methods are the methods of list. These methods a re used to add the elements at the end of the list.
append(element) – adds the given element at the end of the list which has called this method.
extend(another-list) – adds the elements of another-list at the end of the list which is called the extend method.

Q :- Name few methods that are used to implement Functionally Ans :- Oriented Programming in Python?
filter() – enables you to extract a subset of values based on conditional logic.
map() – it is a built-in function that applies the function to each item in an iterable.
reduce() – repeatedly performs a pair-wise reduction on a sequence until a single value is computed.

Q :- What is the output of the following?
Ans :- x = [‘ab’, ‘cd’]
print(len(map(list, x)))
A TypeError occurs as map has no len().

Q :- What is the output of the following?
Ans :- x = [‘ab’, ‘cd’]
print(len(list(map(list, x))))
Explanation: The length of each string is 2.

Q :- Which of the following is not the correct syntax for creating a set?
Ans :- a) set([[1,2],[3,4]])
b) set([1,2,2,3,4])
c) set((1,2,3,4))
d) {1,2,3,4}
Answer : a
Explanation : The argument given for the set must be an iterable. 

Q :- Explain a few methods to implement Functionally Oriented Programming in Python.
Ans :- Sometimes, when we want to iterate over a list, a few methods come in handy.
filter()
Filter lets us filter in some values based on conditional logic. 
>>> list(filter(lambda x:x>5,range(8)))
[6, 7]
map()
Map applies a function to every element in an iterable. 
>>> list(map(lambda x:x**2,range(8)))
[0, 1, 4, 9, 16, 25, 36, 49]
reduce()
Reduce repeatedly reduces a sequence pair-wise until we reach a single value 
>>> from functools import reduce
>>> reduce(lambda x,y:x-y,[1,2,3,4,5])
-13 

Q :- Explain database connection in Python Flask?
Ans :- Flask supports database powered application (RDBS). Such system requires creating a schema, which requires piping the shema.sql file into a sqlite3 command. So you need to install sqlite3 command in order to create or initiate the database in Flask.
Flask allows to request database in three ways
  • before_request() : They are called before a request and pass no arguments
  • after_request() : They are called after a request and pass the response that will be sent to the client
  • teardown_request(): They are called in situation when exception is raised, and response are not guaranteed. 
They are called after the response been constructed. They are not allowed to modify the request, and their values are ignored.
def isPalindrome(string):
left_pos = 0
right_pos = len(string) – 1
while right_pos >= left_pos:
if not string[left_pos] == string[right_pos]:
return False
left_pos += 1
right_pos -= 1
return True
print(isPalindrome(‘aza’)) 

Q :- Write a Python program to calculate the sum of a list of numbers.
Ans :- def list_sum(num_List):
if len(num_List) == 1:
return num_List[0]
else:
return num_List[0] + list_sum(num_List[1:])
print(list_sum([2, 4, 5, 6, 7]))
Sample Output:
24 

Q :- How to retrieve data from a table in MySQL database through Python code? Explain.
Ans :- import MySQLdb module as : import MySQLdb
establish a connection to the database.
db = MySQLdb.connect(“host”=”local host”, “database-user”=”user-name”, “password”=”password”, “database-name”=”database”)
initialize the cursor variable upon the established connection: c1 = db.cursor()
retrieve the information by defining a required query string. s = “Select * from dept”
fetch the data using fetch() methods and print it. data = c1.fetch(s)
close the database connection. db.close()
import random

def random_line(fname):
lines = open(fname).read().splitlines()
return random.choice(lines)
print(random_line(‘test.txt’)) 

Q :- Write a Python program to count the number of lines in a text file.
Ans :- def file_lengthy(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
print(“Number of lines in the file: “,file_lengthy(“test.txt”))
x

To view the help related to string datatype, just execute a statement help(str) – it will display the documentation for ‘str, module.

Eg: >>>help(str) or >>>help() – it will open the prompt for help as help>
to view the help for a module, help> module module name In order to view the documentation of ‘str’ at the help>, type help>modules str
to view the help for a keyword, topics, you just need to type, help> “keywords python- keyword” and “topics list”
2.    dir() – will display the defined symbols. Eg: >>>dir(str) – will only display the defined symbols.


Q :- Which command do you use to exit help window or help command prompt?
Ans :- quit
When you type quit at the help’s command prompt, python shell prompt will appear by closing the help window automatically.

Q :- Does the functions help() and dir() list the names of all the built_in functions and variables? If no, how would you list them?
Ans :- No. Built-in functions such as max(), min(), filter(), map(), etc is not apparent immediately as they are
available as part of standard module.To view them, we can pass the module ” builtins ” as an argument to “dir()”. It will display the
built-in functions, exceptions, and other objects as a list.>>>dir(__builtins )
[‘ArithmeticError’, ‘AssertionError’, ‘AttributeError’, ……… ]

Q :- Explain how Python does Compile-time and Run-time code checking?
Ans :- Python performs some amount of compile-time checking, but most of the checks such as type, name, etc are postponed until code execution. Consequently, if the Python code references a user -defined function that does not exist, the code will compile successfully. In fact, the code will fail with an exception only when the code execution path references the function which does not exists.

Q :-  Whenever Python exists Why does all the memory is not de-allocated / freed when Python exits?
Ans :-  Whenever Python exits, especially those python modules which are having circular references to other objects or the objects that are referenced from the global namespaces are not always de – allocated/freed/uncollectable.
It is impossible to deallocate those portions of memory that are reserved by the C library.
On exit, because of having its own efficient clean up mechanism, Python would try to deallocate/
destroy every object.


Q :-  What is Web Scraping? How do you achieve it in Python?

Ans :-  Web Scraping is a way of extracting the large amounts of information which is available on the web sites and saving it onto the local machine or onto the database tables.
In order to scrap the web:load the web page which is interesting to you. To load the web page, use “requests” module.

parse HTML from the web page to find the interesting information.Python has few modules for scraping the web. They are urllib2, scrapy, pyquery, BeautifulSoup, etc.

Q :-  What is PEP 8?
Ans :-  PEP 8 is a coding convention, a set of recommendation, about how to write your Python code more readable.

Q :- In Python what are iterators?
Ans :- In Python, iterators are used to iterate a group of elements, containers like list.

Q :- What is unittest in Python?
Ans :- A unit testing framework in Python is known as unittest. It supports sharing of setups, automation testing, shutdown code for tests, aggregation of tests into collections etc.

Q :- In Python what is slicing?
Ans :- A mechanism to select a range of items from sequence types like list, tuple, strings etc. is known as slicing.

Q :- What are generators in Python?
Ans :- The way of implementing iterators are known as generators. It is a normal function except that it yields expression in the function.

Q :- What is doc-string in Python?
Ans :- A Python documentation string is known as docstring, it is a way of documenting Python functions, modules and classes.

Q :- How can you copy an object in Python?
Ans :- To copy an object in Python, you can try copy.copy () or copy.deepcopy() for the general case. You cannot copy all objects but most of them.

Q :- What is negative index in Python?
Ans :- Python sequences can be index in positive and negative numbers. For positive index, 0 is the first index, 1 is the second index and so forth. For negative index, (-1) is the last index and (-2) is the second last index and so forth.

Q :- How you can convert a number to a string?
Ans :- In order to convert a number into a string, use the inbuilt function str(). If you want a octal or hexadecimal representation, use the inbuilt function oct() or hex().

Q :- What is the difference between Xrange and range?
Ans :- Xrange returns the xrange object while range returns the list, and uses the same memory and no matter what the range size is.

Q :- What is namespace in Python?
Ans :- In Python, every name introduced has a place where it lives and can be hooked for. This is known as namespace. It is like a box where a variable name is mapped to the object placed. Whenever the variable is searched out, this box will be searched, to get corresponding object.

Q :- What is lambda in Python?
Ans :- It is a single expression anonymous function often used as inline function.

Q :- Why lambda forms in python does not have statements?
Ans :- A lambda form in python does not have statements as it is used to make new function object and then return them at runtime.

Q :- What is pass in Python?
Ans :- Pass means, no-operation Python statement, or in other words it is a place holder in compound statement, where there should be a blank left and nothing has to be written there.

Q :- What is Dict and List comprehensions are?
Ans :- They are syntax constructions to ease the creation of a Dictionary or List based on existing iterable.

Q :- What are the built-in type does python provides?
Ans :- There are mutable and Immutable types of Pythons built in types Mutable built-in types

  1. List
  2. Sets
  3. Dictionaries
  4. Immutable built-in types
  5. Strings
  6. Tuples
  7. Numbers
Q :- What are Python decorators?
Ans :- A Python decorator is a specific change that we make in Python syntax to alter functions easily.

Q :- What is the difference between list and tuple?
Ans :- The difference between list and tuple is that list is mutable while tuple is not. Tuple can be hashed for e.g as a key for dictionaries.

Q :- How are arguments passed by value or by reference?
Ans :- Everything in Python is an object and all variables hold references to the objects. The references values are according to the functions; as a result you cannot change the value of the references. However, you can change the objects if it is mutable.

Q :- Write a Python function that checks whether a passed string is palindrome Or not?
Ans :-Note: A palindrome is a word, phrase, or sequence that reads the same backward as forward, e.g., madam or nurses run.