PCBWay

1) What is Python and mention its uses? 

DRex Electronics

Python is a popular programming language. It was created and released in 1991.

It is used for:

  • web development (server-side),
  • software development,
  • maths
  • system scripting.

2) What can Python do?

  • Python can be used on a server to create web applications.
  • Python can be used alongside software to create workflows.
  • Python can connect to database systems. It can also read and modify files.
  • Python can be used to handle big data and perform complex mathematics.
  • Python can be used for rapid prototyping or production-ready software development.

3) Why Python?

  • Python works on different platforms
  • Python has a simple syntax.
  • Python allows developers to write programs with fewer lines than some other programming languages.
  • Python runs on an interpreter system, code can be executed as soon as it is written. This means that prototyping can be very quick.

4) What is PEP 8?

PEP 8 is a coding convention, a set of recommendations, about how to write your Python code more readable.

5) What are the features of python?

  • Python is an interpreted language.
  • Python is dynamically typed
  • Python is well suited to object-orientated programming
  • Writing Python code is quick but running it is often slower than compiled languages.
  • Easy to learn and use

6) What are the applications of python?

  • Web Applications
  • Desktop GUI Applications
  • Software Development
  • Business Applications
  • Audio or Video-based Applications
  • 3D CAD Applications
  • Enterprise Applications
  • Applications for Images

7) What is the difference between python 2 and python 3?

Python 2

More stable and transparent The print syntax is treated as a statement and not a function ASCII string type is used by default to store strings

range function reconstructs the sequence every time It returns an integer to the nearest whole number when dividing two integers

Python 3

It is the future of python

The print is treated as a function Unicode is the implicit string type by default

the range is replaced by range()  function

It makes integer division more intuitive by using true division for integers and floats Installation and Environmental Setup

8) How to install python on UNIX and Linux?

Here are the simple steps to install Python on Unix/Linux machine.

  • Open a Web browser and go to https://www.python.org/downloads/.
  • Follow the link to download the zipped source code available for Unix/Linux.
  • Download and extract files.
  • Editing the Modules/Setup file if you want to customize some options.
  • run ./configure script
  • make
  • make install This installs Python at standard location /usr/local/bin and its libraries at /usr/local/lib/pythonXX where XX is the version of Python.

9) How to install python on Windows?

Here are the steps to install Python on the Windows machine.

  • Open a Web browser and go to https://www.python.org/downloads/.
  • Follow the link for the Windows installer python-XYZ.msi file where XYZ is the version you need to install.
  • To use this installer python-XYZ.msi, the Windows system must support Microsoft Installer 2.0. Save the installer file to your local machine and then run it to find out if your machine supports MSI.
  • Run the downloaded file. This brings up the Python install wizard, which is easy to use. Just accept the default settings, wait until the install is finished, and you are done.

10) How to set path at Unix/Linux?

  • To add Python directory to a path for a particular session in Unix −
  • In the case shell-type pe setenv PATH

“$PATH:/usr/local/bin/python” and press Enter.

  • In the bash shell (Linux) − type export

PATH=”$PATH:/usr/local/bin/python” and press Enter.

  • In the sh or ksh shell-typepe

PATH=”$PATH:/usr/local/bin/python” and press Enter.

  • Note − /usr/local/bin/python is the path of the Python directory

11) How to set path at Windows?

To add Python directory to a path for a particular session in Windows −

At command prompt − type path %path%;C:\Python and press Enter.

Note − C:\Python is the path of the Python directory Identifiers and Keywords

12) What is the identifier?

A Python identifier is a name used to identify a variable or function or class or module or another object.

13) What are the rules to write identifiers?

An identifier should start with letter A -Z or a-z or an underscore (_) followed by zero or more letters, underscores, and digits (0 to 9).

14) Which characters are not allowed in python?

In Python punctuation characters such as @, $, and % within identifiers are not allowed. Python is a case sensitive programming language. Thus, Power and power are two different identifiers in Python.

15) What are naming conventions for python identifiers?

  • Following are the naming conventions in Python for identifiers −
  • Class names should start with an uppercase letter. All other identifiers must start with a lowercase letter.
  • Starting an identifier with a single underscore indicates that identifier is private.
  • Starting an identifier with 2 underscores indicates a strongly private identifier.
  • If an identifier also ends with 2 trailing underscores, an identifier is a language-defined special name.

16) What are Reserved Words? 

Keywords in python are Reserved Words. You cannot use them as constant or variable or any other identifier names. All keywords in python contain lowercase letters only.

17) What are the comments?

Comments are a way to improve the readability of code by explaining what we have done in the code in simple English.

18) What is the use of comments?

By reading the comment one can understand the purpose of the code much faster than by just going through actual code.

19) What are the types of comments in python? 

There are two types of comments in Python.

  1. Single line comment
  2. Multiple line comment

20) What is a single line comment?

The entire comment is written in a single line is called a single-line comment. 21) What is a multiple line comment?

Here the comment is not on a single line, rather it is in multiple lines hence the name Multiple line comments

22) What happens when # characters are encountered inside the quotes?

When # character is encountered inside quotes, it is not considered as comment. Command Line Arguments

23) What are command-line arguments?

  • They are passed to the main() function.
  • They are parameters/arguments supplied to the program when the program is invoked.
  • They are used to control the program from outside instead of

hard coding those values inside code.

24) What is sys.argv?

sys.argv is a list of command-line arguments passed to the Python program. argv represents all the items that come along from command line input, it is an array holding command-line arguments of our program. Counting starts at zero (0), not one (1).

25) How to use sys.argv?

To use sys.argv, you will have to import sys. The first argument, sys.argv[0], is name of program as it was invoked, and sys.argv[1] is first argument you pass to the program.

import sys

program_name=sys.argv[0]

arguments=sys.argv[1:]

count=len(arguments) Taking Input  26) How to take input in python?

Python provides two inbuilt functions to read input from the keyboard.

  • raw_input ( prompt )
  • input ( prompt )

27) What is raw_input() function?

raw_input() function works in older version (like Python 2.x). It takes exactly what is typed from the keyboard, converts it to string and then returns it to variable in which we want to store.

28) What is input() function?

input() function first takes the input from the user and then evaluates the expression, which means Python automatically identifies whether the user entered a string or number or a list. If input provided is not correct then either syntax error or exception is raised by python.

29) Explain the working of input() function 

  • When input() function executes program flow will be stopped until and unless the user has given input.
  • The text or message display on the output screen to ask a user to enter an input value is optional i.e. prompt, will be printed on screen is optional.
  • Whatever you enter as input, the input function will convert it into a string. If you enter an integer value still input() function convert it into a string. You need to explicitly convert it into an integer in your code using typecasting. Data Types In Python

30) What are the data types in python? Following are the data types in python

  • Integer
  • Float
  • Complex
  • String
  • List
  • Tuple
  • Dictionary

31) Explain integer

These are the whole numbers.

e.g 1,3,4 etc

In Python 3, there is no limit on the value of an integer.

32) Tell something about float

The float data type in Python represents a floating-point number. float values have a decimal point. Optionally, the character e or E followed by a positive(+) or negative(-) integer may be appended to specify scientific notation.

33) What are the complex numbers?

Complex numbers are the numbers that have a real and imaginary part.

Complex numbers are specified as <real part>+<imaginary part>j.

34) What is a string?

Strings are sequences of character data. String data type in Python is called str.

String literals can be delimited using either single or doublequotes. All the characters between the quotes are part of the string.

35) What is a list?

Lists are similar to the arrays in C. In addition to that, the list can contain data of different types. The items stored in the list are separated with a comma (,) and enclosed within square brackets [].

36) What is a tuple?

A tuple is the same as the list in many ways. Like lists, tuples also have a collection of items of different data types. The items of a tuple are separated with a comma (,) and enclosed in parentheses (). A tuple is a read-only data structure. We can’t modify the size and value of the items of a tuple.

37) What is a dictionary?

Dictionary is an ordered set of key-value pairs of items. It is like an associative array or a hash table where each key has a specific value. Key can hold any primitive data type and value is an arbitrary Python object. Items in the dictionary are separated with a comma and enclosed in curly braces {}. Variables

38) What is a variable?

A variable is a reserved memory location to store the values. A variable in the python program gives data to the computer for processing.

39) How to create a variable?

Unlike other programming languages, Python has no command for declaring a variable.A variable is created the moment you first assign a value to it.

40) What are the rules for python variables?

Rules for Python variables are as follows:

  • A variable name must start with a letter or underscore character
  • A variable name cannot start with a number
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • Variable names are case-sensitive (age, Age, and AGE are three

different variables)

41) What are the global variables?

Variables that are created outside a function are known as global variables. Global variables can be used by everyone, both inside of functions and outside.

42) What are the rules for local and global variables in Python?

Local variables: If a variable is assigned a new value anywhere within the function’s body, it’s assumed to be local.

Global variables: Those variables that are only referenced inside a function are global.

43) How can you share global variables across modules?

To share global variables across modules within a single program, create a special module. Import the config module in all modules of your application. The module will be available as a global variable across modules. Number and Maths

44) What is ceil()?

ceil() :- It is a function that returns the smallest integral value greater than the number. If the number is already an integer, the same number is returned.

45) What is the floor()?

floor() :- It is a function that returns the greatest integral value

smaller than the number. If the number is already an integer, the

same number is returned.

46) What is factorial()?

It is a function that is used to return the factorial of any number.

An error message is displayed if a number is not integral.

47) What is gcd()?

gcd() :- It is a function that is used to compute the greatest common divisor of 2 numbers mentioned in its arguments. This function works in python 3.5 and above.

48) Explain how can you generate random numbers in Python?

To generate random numbers in Python, you need to import command as

import random

random.random()

This returns a random floating-point number in the range [0,1) Lists

49) What is a list?

A list is a collection that is ordered and changeable. In Python, lists are written with square brackets.

50) How to access items in a list?

Items in the list can be accessed by referring to the index number.

51) What is negative indexing?

Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second-last item and so on.

52) What is the range of indexes?

You can specify a range of indexes by specifying where to start and where to end the range.

When specifying a range, the return value will be a new list with the specified items.

53) How to change the value in a list?

To change the value of a specific item, refer to the index number:

thislist = [“guava”, “mango”, “cherry”]

thislist[2] = “blackcurrent”

print(thislist)

54) How to loop through a list?

You can loop through list items by using for loop:

thislist = [“a”, “b”, “c”]

for x in thislist: print(x)

55) How to find the length of the list?

To determine how many items a list has, use the len() method: thislist = [“a”, “b”, “c”]

print(len(thislist))

56) How to add an item to the list?

To add an item at the end of the list, use append() method: thislist = [“a”, “b”, “c”]

thislist.append(“d”)

print(thislist) To add an item at any specified index, use insert() method: thislist = [“a”, “b”, “c”]

thislist.insert(1, “d”)

print(thislist)

57) How to remove an item from the list?

There are many methods to remove an item from a list: The remove() method removes the item that is specified The pop() method removes index specified,

The del keyword removes the specified index The del keyword can also delete list completely The clear() method can empty the list

58) How to copy a list?

You cannot copy a list simply by typing list2 = list1, because: list2 will be a reference to list1, and changes made in list1 will be directly made in list2.

There are ways to make a copy, one way is to use List method copy().

this list = [“a”, “b”, “c”]

mylist = thislist.copy()

print(mylist)

59) How to join two lists? 

There are many ways to join or concatenate lists in Python. One of the easiest ways is by using the + operator. list1 = [“a”, “b” , “c”]

list2 = [1, 2, 3]

list3 = list1 + list2

print(list3)

60) What is the use of the list() constructor?

It is also possible to use the list() constructor to make a new list. thislist = list((“a”, “b”, “c”)) # please note double round-brackets print(thislist)

61) What are the methods of the list?

Following are the methods of the list:

append(): Used to append and add elements to the List. It is used to add elements at the last position of the List.

list. append(element)

insert(): Inserts an element at the specified position.

list.insert(position,element) extend(): Adds contents to List2 to the end of List1. list.extend(list2)

sum() : Calculates the sum of all the elements of the List. Sum(list)

count(): Calculates the total occurrence of a given element of List. list.count(element)

length: Calculates the total length of the List.

Len(list_name)  index(): Returns index of the first occurrence. Start and End index are not necessary parameters.

List.index(element[,start[,end]]) min() : Calculates the minimum element of the List. min(list)

max(): Calculates the maximum element of the List. max(list) Iterators

62) What is an iterator?

An iterator is an object that contains a countable number of values. An iterator is an object that can be iterated upon, you can traverse through all the values that are present.

In Python iterator is an object which implements iterator protocol that consists of methods __iter__() and __next__().

63) What is the difference between iterator and iterable?

Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable containers from where you can get an iterator. All these objects have a iter() method which is used to get an iterator

mytuple = (“a”, “b”, “c”)

myit = iter(mytuple)

print(next(myit))

print(next(myit))

print(next(myit))

64) How to loop through an iterator?

We can use a for loop to iterate through an iterable object:

mytuple = (“a”, “b”, “c”)

for x in mytuple: print(x)

65) How to create an iterator?

To create an iterator you have to implement the methods __iter__() and __next__(). The __iter__() method acts similarly, you can do operations (initializing, etc.), but must always return iterator object itself.

The __next__() method also allows us to do operations and must return the next item in the sequence.

66) How to stop iteration?

To prevent iteration from going on forever, one can use the StopIteration statement.

In __next__() method, one can add a terminating condition to raise an error if the iteration is done a specified number of times Generator

67) What is the generator?

Generators are used to create iterators, but with a slightly different approach. Generators are the simple functions that return an iterable set of items, one at a time, in a very special way.

68) What is the generator function?

A generator function is a normal function but whenever a generation of value is needed, it does that with yield keyword. If the body of a def contains yield, then the function automatically becomes a generator function.

69) What is a generator object?

Generator functions return a generator object. Generator objects are used either by calling the next method on the generator object or using a generator object in a “for in” loop.

70) How to create a generator in python?

It is very simple to create a generator in Python. It is just like defining a normal function with a yield statement instead of a return statement.

71) What is the difference between generator function and normal function?

Here is how a generator function differs from a normal function.

  • The generator function has a yield statement.
  • When called, it returns an object that is an iterator but does not start execution immediately.
  • Methods like __iter__() and __next__() are implemented automatically. So iteration through items using next() is possible.
  • Finally, when the function ends, the StopIteration method is raised automatically on further calls.

72) Why generators are used in python?

Generators are used in python for the following reasons: Can be implemented easily

Saves memory

Can be used for a series of operations Comprehensions and Lambda Expressions

73) What is list comprehension?

List comprehensions give a way to create the list. It will always return a list.

74) What is the syntax of list comprehension?

The list comprehension is enclosed between ‘[‘ and ‘]’, to help you remember that result is going to be a list.

75) What is lambda?

A lambda function is a small anonymous function.

A lambda function is a function that can take any number of arguments, but the limitation is that it can only have one expression.

76) What is the syntax of lambda?

lambda arguments: expression

77) Give an e.g of lambda

y = lambda g: g + 50

print(y(7))

78) How many arguments can a lambda function take?

Lambda functions can take any number of arguments.

79) Write a lambda function to multiply 2 arguments

y = lambda a, b : a * b

print(y(8, 9))

80) Why use lambda functions?

The power of lambda is better shown when you use them as an anonymous function inside another function.

If you have a function definition that takes one argument, and that argument will be multiplied with an unknown number: def myfunc(n): return lambda a : a * n

Next()

81) What is next()?

It is a function that returns the next item from the iterator. There are many items present in an iterator. This function provides the user with the next item that is present in the iterator.

82) What is the syntax of next()

Syntax of next is as follows :

next(iterator , default)

83) What are the parameters of the next()?

next() has two parameters and they are as follows

  • iterator – next() gives the next item that is present in the iterator
  • default (optional) – this value is returned if the iterator is empty

84) How to return value from next()?

The next() method returns the next item that is present in the iterator.

If the iterator is empty then it returns the default value (if provided).

If the default parameter is omitted and the iterator is exhausted, it raises StopIteration. Python Ranges

85) What is the range()?

The range() is a function in Python that accepts an integer value as an argument and returns a range object, which is nothing but a sequence of integers till the specified value.

86) What is the syntax of range()?

Following is the syntax of range() :

range( start , stop[ , step])

87) How many arguments range() function has?

range() function has three arguments.

Out of the total three arguments, two arguments are optional. Start and step are optional arguments.

88) What is the start argument?

A start argument is the starting number of the sequence. i.e., lower limit. By default, it starts with 0 if not specified.

89) What is the stop argument?

A stop argument is an upper limit. i.e. generate the numbers up to this number, The range() function does not include this number in the result. Python Tuples

90) What is tuple?

A tuple is a collection in which items are ordered and unchangeable. In Python, tuples are written with round brackets.

this tuple = (“a”, “b”, “c”)

print(thistuple) 91) How to access tuple items?

You can access items in the tuple by referring to an index number, inside square brackets:

thistuple = (“a”, “b”, “c”)

print(thistuple[1])

92) How to change tuple values?

Once a tuple is created, you cannot change its values. Tuples are unchangeable or also called as immutable.

One thing can be done: Convert the tuple into a list, change the list, and convert the list back into a tuple.

93) How to calculate tuple length?

To calculate the length of the tuple, use the len() method:

thistuple = (“a”, “b”, “c”)

print(len(thistuple))

94) How to add items to a tuple?

Once a tuple is created, you cannot add items to it. Tuples are unchangeable.

thistuple = (“a”, “b”, “c”)

thistuple[3] = “o” # error

print(thistuple)

95) How to remove items from tuple?

Tuples are unchangeable, so items cannot be removed from the tuple, but you can delete the tuple completely

The del keyword can delete the tuple completely:

thistuple = (“a”, “b”, “c”)

del thistuple

print(thistuple) # error because the tuple no longer exists

96) How to join 2 tuples?

You can join two or more tuples by using the + operator: tuple1 = (“a”, “b” , “c”)

tuple2 = (4, 5, 6 ) tuple3 = tuple1 + tuple2 print(tuple3)

97) How to loop through a tuple?

One can loop through a tuple by using a for loop. thistuple = (“a”, “b”, “c”)

for x in thistuple: print(x)

Python Dictionaries:

98) What is a python dictionary?

A dictionary is a collection that is unordered, changeable and indexed. In Python, dictionaries are written within curly brackets, and they include keys and values in them.

99) How to access items in a dictionary?

You can access the items of a dictionary in the following ways: x = thisdict[“name”]

There is also one method named get() that will give you the items in a dictionary:

x = thisdict.get(“name”)

100) How to change items in a dictionary?

One can change the value of an item in a dictionary by referring to its key name:

thisdict = { “brand”: “BMW”,

“model”: “X5”,

“year”: 1969 }

thisdict[“year”] = 1998

101) How to loop through a dictionary?

One can loop through a dictionary using a for a loop.

When looping through a dictionary, the return value is the keys of the dictionary, but there are methods to return the values as well. for x in thisdict: print(x)

102) How to find the length of the dictionary?

To determine how many items are there in a dictionary we can use the len() method. print(len(thisdict))

103) How to add an item in a dictionary?

Adding an item to the dictionary is possible by using a new index key and assigning a value to it:

thisdict = { “brand”: “BMW”,

“model”: “X5”,

“year”: 1969 }

thisdict[“color”] = “white”

print(thisdict)

104) How to remove items from a dictionary?

There are many ways to remove items from a dictionary: The pop() method removes item with the specified key name: thisdict = { “brand”: “BMW”,

“model”: “X5”,

“year”: 1969 }

thisdict.pop(“model”)

print(thisdict)

The del keyword removes the item with the specified key name: thisdict = { “brand”: “BMW”,

“model”: “X5”,

“year”: 1969 }

del thisdict[“model”]

print(thisdict)

105) How to copy a dictionary?

You cannot copy a dictionary directly by typing dict2 = dict1, because: dict2 will be a reference to dict1, and changes that will be made in dict1 will also be made in dict2.

There are ways to copy, one way is to use method copy(). thisdict = {

“brand”: “BMW”,

“model”: “X5”,

“year”: 1969 }

mydict = thisdict.copy()

print(mydict)

106) What is a nested dictionary?

A dictionary can also contain many dictionaries, this is called nested dictionaries.

A nested dictionary is a dictionary inside another dictionary.

myparent = { “child1” : {

“name” : “Sam”,

“year” : 1969 },

“child2” : {

“name” : “Ram”,

“year” : 1975

},

“child3” : {

“name” : “Tommy”,

“year” : 1977

}

} Python Sets :

107) What is a set?

A set is a collection in which items are unordered and unindexed. In Python, sets are written within curly brackets.

108) How to create a set?

thisset = {“a”, “b”, “c”} print(thisset)

109) How to access items in a set? 

You cannot access items in a set by referring to an index of any item, as the sets are do not have any order the items have no index. But you can loop through items present in a set using a for loop, or ask if a specified value is present in a set, by using the in the keyword.

thisset = {“a”, “b”, “c”}

for x in thisset: print(x)

110) Can you change items in a set?

No, It is not possible to change the items in the set.

111) How to add items in a set?

To add an item to an existing set use the add() method. To add more than one item to an existing set use the update() method.

thisset = {“a”, “b”, “c”}

thisset.add(“d”)

print(thisset)

 112) How to determine the length of a set? 

To determine the length of any set , use the len() method. thisset = {“a”, “b”, “c”}

print(len(thisset))

113) How to remove an item in a set?

To remove an item in a set, use the remove(), or the discard() method.

thisset = {“a”, “b”, “c”}

thisset.remove(“b”)

print(thisset)

114) How to join two sets?

You can use the union() method that returns a new set which contains all items that were there in both sets, or the update() method that inserts all the items from one set into another: set1 = {“a”, “b” , “c”}

set2 = {1, 2, 3}

set3 = set1.union(set2)

print(set3) File Handling

115) What is open() function in python file handling?

It is a very important function for working with files in python. It takes 2 parameters namely, filename and mode.

116) What are the different methods for opening a file?

There are 4 different methods for opening a file: “r”: Read (default mode)- Open a file only for reading “a ”: Append- Open a file for appending

“w”: Write- Open a file for writing

“x”: Create- Create a new file

117) What are the types of modes of file?

There are two types of modes of any file: “t”:text(default) – Text Mode

“b”: binary- Binary Mode

118) What is the syntax to open a file?

Following is the syntax to open a file f = open(“file.txt”)

119) How to close any file?

It is good to close a file once done working with it. It can be done as follows: f = open(“file.txt”, “r”)

print(f.readline())

f.close()

120) How to write to an existing file? 

Writing to an existing file, you must add a parameter to open() function:

“a” – Append – will append at the end of the file

“w” – Write – will overwrite any existing content

121) How to delete a file?

os.remove() function is used to delete a file. It must be imported first before using import os

os.remove(“demofile.txt”)

122) How to delete a folder?

os.rmdir() function is used to delete a folder. import os

os.rmdir(“folder”) Functions

123) What are user-defined functions?

User-defined functions are a reusable block of code; they only need to be written once, and then they can be used multiple times.

124) What are the types of function arguments?

  1. Default arguments:

It means this value will be taken as an argument if no value is passed to the function.

  1. Required arguments:

This means they are a must for the function.

  1. Keyword arguments:

They are mentioned along with their value during the function call.

  1. Variable number of arguments

Used when the exact number of arguments is not known

125) What are rules to define a function? 

  • The function must start with the keyword def followed by name and parentheses ( ( ) ).
  • Any input parameters or arguments should be placed within parentheses.
  • The first statement of a function can be optional
  • The code block within every function starts with a colon (:) and is indented.
  • The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None. Python If Else

126) Which logical conditions are supported by python?

Python supports the following logical conditions from mathematics:

  • Equals: a == b
  • Not Equals: a != b
  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b

127) Give an e.g of if statement

a = 333

b = 2015

if b > a:

print(“b is greater than a”)

128) What is elif?

The elif is a keyword in python to say “if the previous conditions were not true, then try this condition”.

129) Give an e.g. of elif

a = 96

b = 96

if b > a:

print(“b is greater than a”) elif a == b:

print(“a and b are equal”)

130) Tell something about else keyword with e.g 

The else keyword catches anything which is not caught by the conditions before that.

a = 2015

b = 369

if b > a: print(“b is greater than a”)

elif a == b:

print(“a and b are equal”)

else:

print(“a is greater than b”)

131) What is a short hand if?

If you have only one statement to execute, you can put it on the same line as the if statement.

if a > b: print(“a is greater than b”)

132) What is a short hand if..else?

If you have only one statement to execute, one for if, and one for else, you can put it on the same line:

a = 20

b = 3305

print(“A”) if a > b else print(“B”)

133) Explain and keyword.

The keyword and is a logical operator, it is used to combine conditional statements:

a = 2000

b = 335

c = 5000

if a > b and c > a: print(“Both conditions are True”)  134) Explain or keyword.

The keyword or is a logical operator, and it is used to combine conditional statements:

a = 200

b = 33

c = 500

if a > b or a > c: print(“At least one of the conditions is True”)

135) What is nested if?

You can have if statements inside if statements, this is called nested if statements.

x = 40

if x > 10: print(“Above ten,”)

if x > 25:

print(“above 25!”)

else:

print(“not above 25.”)

Python Loops :

136) What are the types of loops in python?

Python has two types of loops:

  • while loops
  • for loops

137) Explain while loop

With the help of a while loop, we can execute a set of statements as long as a condition is true or as long as we want to execute before terminating. 138) Give an e.g of while loop i = 1

while i < 5:

print(i)

i ++

139) Tell the use of break statement

With the use of the break statement, the loop can be stopped even if the while condition is true

i = 1

while i <5: print(i)

if i == 3:

break i ++

140) What is continue statement

By using the continue statement we can stop the current iteration, and continue with the next:

i = 0

while i < : i ++

if i == 2: continue print(i)

141) What is else statement?

With the else statement we can run a block of code once when the condition no longer is true:

i = 1

while i < 5: print(i)

i ++

else:

print(“i is no longer less than 5”)

142) What is for loop?

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).

This is less like for keyword in other programming languages and works more like an iterator method as found in other objectorientated programming languages.

With the for loop, we can execute a set of statements, once per item in a list, tuple, set, etc.

143) Coming soon

144) What is else in for loop?

The else keyword in a for loop specifies a block of code to be executed when the loop is finished:

for y in range(6): print(y)

else:

print(“Finally finished!”)

145) What are nested loops?

A nested loop is a loop inside a loop.

The “inner loop” will be executed one time for each iteration of the “outer loop”:

adj = [“red”, “big”, “tasty”]

fruits = [“apple”, “banana”, “cherry”] for x in adj:

for y in fruits: print(x, y)

146) What is a module?

A module is a piece of software that has a specific functionality.

Big tasks are divided into smaller ones and given to each module.

147) How to write a module?

It is easy to write a module in python.

Modules are python files with .py extension. The name of the module will be the name of the file.

148) How to initialize a module?

The first time a module is loaded into a running Python program, it is initialized by executing the code that is there in the module once.

149) How to write a package?

Packages are nothing but namespaces that have other packages and modules.

Each package in Python is a directory which should necessarily contain a file called __init__.py. This file can be empty, and it indicates that the directory it contains is a Python package, so it can be imported in the same way a module can be imported. Python Object-Oriented Programming

150) What are the major principles of OOP?

The major principles of object-oriented programming systems are as follows.

  • Object
  • Class
  • Method
  • Inheritance
  • Polymorphism
  • Data Abstraction
  • Encapsulation

151) What is an object?

The object is an entity that has state and behavior. It may be any real-world object like the laptop, keyboard, chair, phone, pencil, etc.

152) What is a class?

A class is a blueprint to create objects. All objects are associated with a particular class. The class can be defined as a collection of objects.

153) How to create a class?

To create a class, we have to use the keyword class: class MyClass: x = 50

154) How to create an object?

Now we can use the class named myClass to create objects: p1 = MyClass()

print(p1.x)

155) What is the method?

The method is a function that is associated with an object. In Python, a method is not unique to class instances. Any object can have methods.

156) What are object methods?

Objects can also contain methods. Methods in objects are functions that belong to the object.

Let us create a method in the Person class:

class Person: def __init__(self, name, age):

self.name = name

self.age = age def myfunc(self):

print(“Hello my name is ” + self.name)

p1 = Person(“Rocky”, 16) p1.myfunc()

157) How to delete object properties?

You can delete properties on objects by using the del keyword: del p1.age 158) How to delete objects?

You can delete objects by using the del keyword: del p1

159) What is inheritance?

Inheritance allows us to define a class in such a way that inherits all the methods and properties of another class.

The parent class is the class being inherited from, and it is also called a base class.

The child class is the class that inherits from another class, and it is also called the derived class.

160) How to create a parent class?

Any class can be a parent class, so the syntax is the same as creating any other class

class Person:

def __init__(self, fname, lname):

self.firstname = fname

self.lastname = lname def printname(self):

print(self.firstname, self.lastname)

#Use the Person class to create an object, and then execute the printname method:

x = Person(“Johnny”, “Deo”) x.printname()

161) How to create child class?

To create a class that inherits the functionality from another class, send the parent class as a parameter when creating the child class: class Student(Person): pass

162) What is super function?

super() function is a function that will make the child class inherit all the methods and properties from it’s parent class Student(Person):

def __init__(self, fname, lname):

super().__init__(fname, lname)

163) How to add properties? Properties can be added as follows: class Student(Person):

def __init__(self, fname, lname): super().__init__(fname, lname) self.graduationyear = 2017

164) How to add methods?

Methods can be added in following way: class Student(Person): def __init__(self, fname, lname, year): super().__init__(fname, lname) self.graduationyear = year def welcome(self):

print(“Welcome”, self.firstname, self.lastname, “to class of”, self.graduationyear)

165) What is polymorphism?

The word polymorphism means having many forms. In programming, polymorphism means the function name is the same but different signatures being used for different types.

166) Give e.g of polymorphism

You have a class animal, and all animals walk. But they walk differently. Here, the “walk” behavior is polymorphic and depends on that particcular animal. So, the abstract “animal” concept does not actually “walk”, but specific animals (like dogs and cats) have a concrete implementation of the action “walk”.

167) What is encapsulation?

Encapsulation is an important pillar of object oriented programming. It is used to restrict the access to methods and variables. In encapsulation, code and data are wrapped together within a single unit and protected from being modified by accident.

168) What is data abstraction? 

Data abstraction and encapsulation both are often used as synonyms. Both are nearly the same because data abstraction is achieved through encapsulation.

Abstraction is used to hide internal details and show only functionalities. Abstracting something means to give names to things so that name captures the core of what a function or a whole program does.

169) What is the difference between object-oriented and procedural programming? 

Index Object-oriented Programming Procedural Programming

  1. Object-oriented programming is the problem-solving approach and used where computation is done by using objects.

Procedural programming uses a list of instructions to do computation step by step.

  1. It makes development and maintenance easier. In procedural programming, It is not easy to maintain the codes when the project becomes lengthy.
  2. It simulates the realworld entity. So realworld problems can be easily solved through oops.

It doesn’t simulate the real world. It works on step by step instructions divided into small parts called functions.

  1. It provides data hiding. So it is more secure than procedural languages. You cannot access private Procedural language doesn’t provide any proper way for data binding, so it is less data from anywhere. secure.
  2. Example of objectoriented programming languages is C++, Java, .Net, Python, C#, etc.

170) How to create an instance of a class?

A class needs to be instantiated if we want to use the attributes of the class in another class or method. A class can be instantiated by calling the class using the class name.

The syntax to create the instance of the class is as follows. <object-name> = <class-name>(<arguments>)

Examples of procedural languages are: C, Fortran, Pascal, VB, etc.

171) What is multiple inheritance?

One class can inherit from multiple base classes. This is called as multiple inheritance.

172) What is multi-level inheritance

Multi-level inheritance is means a derived class inherits another derived class. There is no limit on the number of levels up to which, the multi-level inheritance is archived in python.

173) How to delete an object in python?

An object will be deleted as soon as all references to that object get removed. The __del__() method is a destructor method in Python. It is called when all references to the object have been deleted Exception Handling

174) What are exceptions?

Exception forces your program to give an error as output when something has gone wrong in the program.

When these exceptions occur, it causes the current process to stop and passes it to the calling process until it is handled. If not handled, our program will crash.

175) How to handle exceptions?

In Python, exceptions can be handled with the help of a try statement.

A critical operation that can raise an exception is placed inside the try clause and the code that can handle the exception is written inside the except clause.

176) How are exceptions raised?

In Python programming, exceptions are raised when the errors occur at run time, but we can forcefully raise it using the keyword raise.

We can also optionally specify to clarify why that exception was raised.

177) What is try …finally?

The try statement in Python can have an optional finally clause. This clause is executed no matter what and is generally used to release external resources.

178) What are user-defined exceptions?

Programs may create and name their own exceptions by creating a new exception class.

Exceptions should be typically derived from Exception class, either directly or indirectly.

179) How to write except clause with no exceptions?

We can write. except for clause with no exceptions as follows try: You do your operations here;  ………………….

except:

If there is any exception, then execute this block.

………………….

else:

If there is no exception then execute this block.

180) How to write except clause with multiple exceptions?

try:

You do your operations here;

………………….

except(Exception1[, Exception2[,…ExceptionN]]]):

If there is any exception from the given exception list,

then execute this block.

………………….

else:

If there is no exception then execute this block.

181) What is the argument of an exception?

An exception can have an argument, which is a value that gives additional information about the problem. The contents of the argument vary by exception. You capture an exception’s argument by supplying a variable in the except clause as follows − try:

You do your operations here;

…………………. except for ExceptionType, Argument: You can print the value of Argument here…

182) What are the standard exceptions in python?

Here is a list all the standard Exceptions available in Python − Exception Name & Description

  1. Exception Base class for all exceptions
  2. StopIteration

Raised when the next() method of an iterator does not point to any object.

  1. SystemExit

Raised by the sys.exit() function.  4. StandardError

Base class for all built-in exceptions except StopIteration and

SystemExit. 5. ArithmeticError

Base class for all errors that occur for numeric calculation.

  1. OverflowError

Raised when a calculation exceeds maximum limit for a numeric type.

  1. FloatingPointError

Raised when a floating point calculation fails.

  1. ZeroDivisionError

Raised when division or modulo by zero takes place for all numeric types.

  1. AssertionError

Raised in case of failure of the Assert statement.

  1. AttributeError

Raised in case of failure of attribute reference or assignment.

  1. EOFError Raised when there is no input from either the raw_input() or input() function and the end of file is reached.
  2. ImportError

Raised when an import statement fails.

  1. KeyboardInterrupt

Raised when the user interrupts program execution, usually by pressing Ctrl+c.

  1. LookupError

Base class for all lookup errors.

  1. IndexError

Raised when an index is not found in a sequence.

  1. KeyError

Raised when the specified key is not found in the dictionary.

  1. NameError

Raised when an identifier is not found in the local or global namespace.

  1. UnboundLocalError

Raised when trying to access a local variable in a function or method but no value has been assigned to it.

  1. EnvironmentError

Base class for all exceptions that occur outside the Python environment.

  1. IOError Raised when an input/ output operation fails, such as the print statement or the open() function when trying to open a file that does not exist. 21. OSError

Raised for operating system-related errors.

  1. SyntaxError Raised when there is an error in Python syntax.
  2. IndentationError

Raised when indentation is not specified properly.

  1. SystemError

Raised when the interpreter finds an internal problem, but when this error is encountered the Python interpreter does not exit.

  1. SystemExit

Raised when Python interpreter is quit by using the sys.exit() function. If not handled in the code, it causes the interpreter to exit.

  1. TypeError

Raised when an operation or function is attempted that is invalid for the specified data type.

  1. ValueError

Raised when the built-in function for a data type has the valid type of arguments, but the arguments have invalid values specified.

  1. RuntimeError

Raised when a generated error does not fall into any category.

  1. NotImplementedError

Raised when an abstract method that needs to be implemented in an inherited class is not actually implemented.

183) What is a regular expression?

A RegEx, or Regular Expression, is a sequence of characters that forms a search pattern.

RegEx can be used to check if a string contains the specified search pattern.

184) What is a Regular Expression module?

Python has a built-in package called re, which can be used to work with Regular Expressions.

Import the re module:

import re

185) What is the use of findall() function?

The findall() function returns a list containing all matches. import re

str = “Hi all How are you all?”

x = re.findall(“al”, str)

print(x)

186) Explain search() function.

The search() function searches the string for a match, and returns a match object if there is a match.

If there is more than one match, only the first occurrence of the match will be returned:

import re

str = “The rain in Spain”

x = re.search(“\s”, str)

print(“The first white-space character is located in position:”, x.start())

187) Explain use of split() function

The split() function returns a list where string has been split at each match:

import re

str = “The rain in Spain”

x = re.split

(“\s”, str)

print(x) 188) What is the sub() function?

The sub() function replaces matches with the text of your choice: import re

str = “The rain in Spain”

x = re.sub(“\s”, “9”, str)

print(x)

189) What is a match object?

A Match Object is an object containing information about search and result.

If there is no match, the value None will be returned, instead of the match object.

190) What are the properties and methods of match object?

The Match object has properties and methods used to retrieve information about the search, and the result:

.span() returns a tuple containing the start-, and end positions of the match .string returns the string passed into the function .group() returns the part of the string where there was a match

191) Give syntax of match() function

The syntax is as follows:

re.match(pattern, string, flags=0)

Description of the parameters −

pattern- This is the regular expression to be matched. string- This is the string, which would be searched to match the pattern at the beginning of the string.

flags-You can specify different flags using bitwise OR (|).

192) Give the syntax of the search function

Here is the syntax for this function −

re.search(pattern, string, flags=0)

Here is the description of the parameters −

pattern-This is the regular expression to be matched. string-This is the string, which would be searched to match the pattern anywhere in the string.

flags-You can specify different flags using bitwise OR (|). Python Multithreaded Programming

193) What is multithreading?

Multithreading is defined as the ability of a processor to execute multiple threads concurrently.

194) What is a thread?

A thread is an entity inside a process that can be scheduled for execution. It is the smallest unit of processing that can be performed in an OS. A thread is a sequence of instructions within a program that can be executed independently of other codes. It can be assumed that a thread is simply a subset of a process!

195) What information a thread has?

A thread contains all this information in a Thread Control Block (TCB):

  • Thread Identifier: Unique id is assigned to every thread
  • Stack pointer: Points to thread’s stack in the process.
  • Program counter: a register that stores the address of the instruction currently being executed by the thread.
  • Thread state: can be running, ready, waiting, start or do.
  • Thread’s register set: registers assigned to thread for computations.
  • Parent process Pointer: A pointer to the Process control block

(PCB) of the process that the thread lives on.

196) What is context switching?

In a simple, single-core CPU, multithreading is achieved by using frequent switching between the threads. This is termed as context switching. In context switching, the state of a thread is saved and the state of another thread is loaded whenever an interrupt takes place. Context switching takes place so frequently that all the threads appear to be running parallelly.

197) How to create a new thread?

To create a new thread, we have to create an object of Thread class. It takes the following arguments:

  • target: the function to be executed by the thread
  • args: the arguments to be passed to the target function

198) How to synchronize threads?

The threading module provided with Python includes a simple-toimplement locking mechanism that allows you to synchronize threads.

199) What is a multithreaded priority queue?

The Queue module allows the user to create a new queue object that can hold a specific number of items. Methods to control the Queue are as follows−

  • get() − It removes and returns an item from the queue.
  • put() − The put adds the item to a queue.
  • qsize() – It returns the number of items that are currently in the queue.
  • empty() − It returns True if queue is empty; otherwise, False.
  • full() − It returns True if queue is full; otherwise, False.

200) What is pyspread?

Pyspread is a non-traditional spreadsheet which is based on and written in the programming language Python.

The goal of pyspread is to be the most pythonic spreadsheet. It is a free software.

201) Which are the XML handling sub modules?

The XML handling sub modules are:

  • xml.etree.ElementTree: the ElementTree API, a simple and lightweight XML processor
  • xml.dom: the DOM API definition
  • xml.dom.minidom: a minimal DOM implementation
  • xml.dom.pulldom: support for building partial DOM trees
  • xml.sax: SAX2 base classes and convenience functions
  • xml.parsers.expat: the Expat parser binding Arrays

202) What is numpy?

Numpy is a general-purpose array-processing package. It provides a high-performance multidimensional array object, and tools for working with the arrays.

203) How to create arrays in numpy?

Arrays in Numpy can be created in various ways, with different number of Ranks, defining size of the Array. Arrays can also be created with the use of various data types such as lists, tuples, etc.

204) What is an array?

Arrays are used to store multiple values in one single variable.They can be of same or different types.

205) Give an e.g of array

cars = [“Figo”, “Polo”, “Beat”]s

206) How to access elements in an array?

You refer to an array element by referring to the index number. x = cars[0]

207) How to calculate length of an array?

Use the len() method to return the length of an array (the number of elements in an array)

x = len(cars)

208) How to use loop in array? 

You can use the for in loop to loop through all the elements of an array.

for x in cars: print(x)

209) How to add elements in an array?

You can use the append() method to add an element to an array. cars. append(“Honda”)

210) How to remove elements from array?

You can use the pop() method to remove an element from the array. cars.pop (1)

211) What are the universal array functions?

Universal functions in Numpy are simple mathematical functions. It is just a term that we gave to mathematical functions in the Numpy library. Numpy provides various universal functions that cover a wide range of operations. Strings:

212) What is a string?

String literals in python are surrounded by either single quotes , or double quotes.

‘hello’ is the same as “hello”.

213) How to display a string?

You can display a string literal with the print() function  214) Give an e.g of string print(“Hello”)

print(‘Hello’)

215) How to assign string to a variable?

Assigning a string to a variable is done with the variable name followed by an equal sign and the string:

a = “Hello”

print(a)

216) How to get length of the string?

To get the length of a string, use the len() function.

217) What are the different string methods?

The strip() method removes any whitespace from the beginning or the end

The lower() method returns the string in lower case

The upper() method returns the string in upper case

The replace() method replaces a string with another string The split() method splits the string into substrings if it finds instances of the separator

218) How to concatenate 2 strings?

To concatenate, or combine, two strings you can use the + operator. a = “Hello”

b = “World”

c = a + b

print(c)

219) Mention the use of the split function in Python?

The use of the split function in Python is that it breaks a string into smaller and smaller strings using the defined separator. It gives a list of all words present in the string.

220) How you can convert a number to a string?

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().

221) Is python case sensitive?

Yes. Python is a case sensitive language.

Python Modules

222) What is a module?

Consider a module to be the same as a code library. A file containing a set of functions you want to include in your application

223) How to create a module?

To create a module just save the code you want in a file with the file extension .py:

def greeting(name): print(“Hello, ” + name)

224) How to use a module?

We can use the module created, by using the import statement: import mymodule

mymodule.greeting(“Jonathan”)

225) How to name a module?

You can name the module file whatever you like, but it must have the file extension .py 226) How to rename a module?

You can create an alias when you import a module, by using the as keyword

227) Give e.g of renaming a module?

import mymodule as mx

a = mx.person1[“age”]

print(a) 228) What are built in modules?

There are several built-in modules in Python, which you can import whenever you like.

import platform

x = platform.system()

print(x)

229) What is dir() function?

There is a built-in function to list all the function names (or variable names) in a module. The dir() function:

import platform

x = dir(platform)

print(x)

230) What is import from module?

You can choose to import only parts from a module, by using the from keyword.

def greeting(name): print(“Hello, ” + name)  person1 = {

“name”: “John”,

“age”: 36,

“country”: “Norway” }

Python JSON

231) What is JSON?

JSON is a syntax for storing and exchanging data. JSON is text, written with JavaScript object notation.

232) How to convert from JSON to python?

If you have a JSON string, you can parse it by using the json.loads() method.

import json # some JSON:

x = ‘{ “name”:”John”, “age”:30, “city”:”New York”}’

# parse x:

y = json.loads(x)

# the result is a Python dictionary: print(y[“age”])

233) How to convert from python to JSON?

If you have a Python object, you can convert it into a JSON string by using the json.dumps() method.

import json # a Python object (dict): x = {

“name”: “Johnny”,

“age”: 25,

“city”: “New Zealand” } # convert into JSON: y = json.dumps(x) # the result is a JSON string: print(y)

234) Which types of python objects can be converted into JSON strings?

You can convert Python objects of the following types, into JSON strings:

  • dict
  • list
  • tuple
  • string
  • int
  • float
  • True
  • False
  • None

235) How to format the result in JSON?

The json.dumps() method has parameters to make it easier to read the result:

Use indent parameter to define number of indents

json.dumps(x, indent=4)

Use separators parameter to change the default separator json.dumps(x, indent=4, separators=(“. “, ” = “)) 236) How to order the result ?

The json.dumps() method has parameters to order the keys in the result:

Use the sort_keys parameter to specify if the result should be sorted or not:json.dumps(x, indent=4, sort_keys=True) Python PIP

237) What is PIP?

PIP is a package manager for Python packages, or modules if you like.

238) What is a package?

A package contains all the files that you need for a module. Modules are Python code libraries you can include in your project.

239) How to download a package?

Downloading a package is easy.

Open the command line interface and tell PIP to download the package that you want.

Navigate your command line to the location of Python’s script directory, and type the following:

Download a package named “camelcase”:

Download a package named “camelcase”:

32\Scripts>pip install camelcase

240) How to use a package?

Once the package is installed, it is ready to use. Import the “camelcase” package into your project. import camelcase c = camelcase.CamelCase() txt = “hello world”

print(c.hump(txt))

241) How to remove a package? 

Use the uninstall command to remove a package. Use the uninstall command to remove a package. 32\Scripts>pip uninstall camelcase

242) How to list all packages?

Use the list command to list all the packages installed on your system:

C:\Users\Your NameYour Name 32\Scripts>pip list Pandas

243) What is pandas?

Pandas is the most popular library in python that is used for data analysis. It provides highly optimized performance with back-end source code is purely written in C or Python.

We can analyze data in pandas with:

1)Series

2)DataFrames

244) What is series?

Series is one dimensional(1-D) array defined in pandas that can be used to store any data type.

245) What is data frames?

DataFrames is two-dimensional (2-D) data structure defined in pandas which consists of rows and columns.

246) Where is pandas used?

The pandas module is invaluable for manipulating all manner of data sets.

It is also used to filter the data.

Pandas is the most widely used for data munging.

247) What is pandas series?

Pandas Series is a one-dimensional labeled array which is capable of holding data of any type (integer, string, float, python objects, etc.). The axis labels are called index. Pandas Series is nothing but a column in an excel sheet. Web Scraping

248) What is web scraping?

Web scraping, web harvesting, or web data extraction is data scraping used for extracting data from websites. Web scraping software may access the World Wide Web directly using the Hypertext Transfer Protocol, or through a web browser. While web scraping can be done manually by a software user, the term typically refers to automated processes implemented using a bot or web crawler. It is a form of copying, in which specific data is gathered and copied from the web, typically into a central local database or spreadsheet, for later retrieval or analysis.

249) Why scrape the web?

There are many specific reasons why businesses may want to scrape a website; one of the vital reason being the unavailability of APIs. Some of the other major reasons which may lead a company into scraping website are: Expand Market Share Due to the lack of availability of APIs the possibility of collaborating with business partners is limited. By exposing the data available in their website as APIs enterprises can open up new channels, possibilities to expand the market share and increase sales. Enter New Markets with Early go-to Market Strategy API being the long time strategy, Web Scraping solution can potentially enable organizations to build an early go-to market strategy. Access to Renewed and Structured Data Scraping the website of the organization through a Web Scraping solution gives an organization the chance to access renewed, structured and up to date data through the scraped APIs.

250) What can I do with data scraping?

Web scraping is used for contact scraping, and as a component of applications used for web indexing, web mining and data mining, online price change monitoring and price comparison, product review scraping (to watch the competition), gathering real estate listings, weather data monitoring, website change detection, research, tracking online presence and reputation, web mashup and, web data integration. Using data scraping you can build sitemaps that will navigate the site and extract the data. Using different type selectors you will navigate the site and extract multiple types of data – text, tables, images, links and more.

251) Which language should be preferred for web scraping and why?

When you are going to crawl large-scale websites, then efficiency, scalability and maintainability are the factors that you must consider. Crawling large-scale websites involve many problems: multi-threading, I/O mechanism, distributed crawling, communication, duplication checking, task schedule, etc. And then the language used and the frame selected play a significant role at this moment. PHP: The support for multithreading and async is quite weak and therefore is not recommended. Node.js: It can crawl some vertical websites. But due to the support for distributed crawling and communications, it is relatively weaker than the other two. So you need to make a judgment. Python: It’s Strongly recommended and has better support for the requirements mentioned above, especially the scrapy framework. Scrapy framework has many advantages: Support for XPath, Good performance, Has debugging tools

252) Is web scraping legal?

Web crawling is as legal as viewing a webpage using your browser and is not different in any way as far as the target server is concerned. Most websites on the surface web (the part of web accessible to search engines) allow web crawling and this means you can fetch data from them using an automated crawler. The only thing to make sure is if the site allows bots via the directives in their robots.txt file.

253) Can you use web scraping for lead generation?

Using web scraping to generate leads is a fruitless activity since the email lists you can build by crawling random websites would be less targeted and highly exploited. Most publicly available emails are either the ones that people don’t check often, were abandoned, and is definitely being spammed by others who are on the same path as you. Although technically possible, using web scraping for lead generation is not a recommended practice. You can check out our detailed blog on why scraping emails isn’t worth it. Python MySQL

254) How to install MySQL driver?

Python needs a MySQL driver to access the MySQL database. Navigate your command line to the location of PIP, and type the following:

following:

32\Scripts>python -m pip install mysql-connector

255) How to create a database?

To create a database in MySQL, use the “CREATE DATABASE” statement:

Example

create a database named “mydatabase”: import mysql.connector  mydb = mysql.connector.connect( host=”localhost”,

user=”username”,

passwd=”password” )

mycursor = mydb.cursor()

mycursor.execute(“CREATE DATABASE mydatabase”)

256) How to create a connection?

Connection can be created as follows: import mysql.connector mydb = mysql.connector.connect( host=”localhost”,

user=”yourusername”,

passwd=”yourpassword” )

print(mydb)

257) How to create a table?

To create a table in MySQL, use the “CREATE TABLE” statement. import mysql.connector mydb = mysql.connector.connect( host=”localhost”,

user=”yourusername”,

passwd=”yourpassword”,

database=”mydatabase” )

mycursor = mydb.cursor()

mycursor.execute(“CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))”)

258) How to insert into table?

To fill a table in MySQL, use the “INSERT INTO” statement. import mysql.connector mydb = mysql.connector.connect( host=”localhost”,

user=”yourusername”,

passwd=”yourpassword”,

database=”mydatabase” )

mycursor = mydb.cursor()  sql = “INSERT INTO customers (name, address) VALUES (%s, %s)” val = (“John”, “Highway 21”)

mycursor.execute(sql, val) mydb.commit()

print(mycursor.rowcount, “record inserted.”)

259) How to update a table?

You can update existing records in a table by using the “UPDATE” statement:

import mysql.connector mydb = mysql.connector.connect( host=”localhost”,

user=”yourusername”,

passwd=”yourpassword”,

database=”mydatabase” )

mycursor = mydb.cursor()

sql = “UPDATE customers SET address = ‘Canyon 123’ WHERE address = ‘Valley 345′”

mycursor.execute(sql)

mydb.commit()

print(mycursor.rowcount, “record(s) affected”)

260) How to delete a record?

You can delete records from an existing table by using the “DELETE FROM” statement:

import mysql.connector mydb = mysql.connector.connect( host=”localhost”,

user=”yourusername”,

passwd=”yourpassword”,

database=”mydatabase” )

mycursor = mydb.cursor()

sql = “DELETE FROM customers WHERE address = ‘Mountain 21′” mycursor.execute(sql)

mydb.commit()

print(mycursor.rowcount, “record(s) deleted”)

261) Explain Django.

Django is a free and open source web application framework, written in Python. It is a server-side web framework that provides rapid development of secure and maintainable websites.

262) Which architectural pattern does Django follow?

Django follows Model-View-Template (MVT) architectural pattern.

263) Explain Django architecture.

Django follows MVT (Model View Template) pattern. It is slightly different from MVC.

Model: It is the data access layer. It contains everything about the data, i.e., how to access it, how to validate it, its behaviors and the relationships between the data.

View: It is the business logic layer. This layer contains the logic that accesses the model and defers to the appropriate template. It is like a bridge between the model and the template.

Template: It is a presentation layer. This layer contains presentation-related decisions, i.e., how something should be displayed on a Web page or other type of document.

264) What are the features available in the Django web framework?

Features available in Django web framework are:

  • Admin Interface (CRUD)
  • Templating
  • Form handling
  • Internationalization
  • A Session, user management, role-based permissions
  • Object-relational mapping (ORM)
  • Testing Framework
  • Fantastic Documentation

265) Explain the advantages of Django?

Advantages of Django:

  • Django is a Python framework that is easy to learn. • It is clear and readable.
  • It is versatile.
  • It is fast to write.
  • No loopholes in design.
  • It is secure.
  • It is scalable.
  • It is versatile.

266) What are the disadvantages of Django?

Following is the list of disadvantages of Django: • Django’s modules are bulky.

  • It is completely based on Django ORM. • Components are deployed together.
  • You must know the full system to work with it.

267) What are the inheritance styles in Django?

There are three possible inheritance styles in Django:

1) Abstract base classes: This style is used when you only want a parent’s class to hold information that you don’t want to type out for each child model.

2) Multi-table Inheritance: This style is used if you are subclassing an existing model and need each model to have its database table.

3) Proxy models: This style is used, if you only want to modify the Python level behavior of the model, without changing the model’s fields.

268) What are the two important parameters in signals?

Two important parameters in signals are:

  • Receiver: It specifies the callback function which connected to the signal.
  • Sender: It specifies a particular sender from where a signal is received.

269) What is Django Exception?

An exception is an abnormal event that leads to program failure. To deal with this situation, Django uses its exception classes and supports all core Python exceptions as well. Django core exceptions classes are defined in django.core.exceptions module.

270) What is Django Session?

A session is a mechanism to store information on the server-side during interaction with the web application. By default, session stores in the database and also allows file-based and cache-based sessions. FAQs

271) What is pickling and unpickling?

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

272) How Python is interpreted?

Python language is an interpreted language. Python program runs directly from the source code. It converts source code that is written by the programmer into an intermediate language, which is again translated into machine language that has to be executed.

273) How memory is managed in Python?

  • Python memory is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have an access to this private heap and interpreter takes care of this Python private heap.
  • The allocation of Python heap space for Python objects is done by Python memory manager. The core API gives access to some tools for the programmer to code.
  • Python also have an inbuilt garbage collector, which recycle all the unused memory and frees the memory and makes it available to the heap space.

274) What are the tools that help to find bugs or perform static analysis?

PyChecker is a static analysis tool that detects the bugs in Python source code and warns about the style and complexity of the bug. Pylint is another tool that verifies whether the module meets the coding standard.

275) What is the difference between list and tuple?

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.

276) What is pass in Python?

Pass means, no-operation Python statement, 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.

277) What is unittest in Python?

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.

278) ) What is docstring in Python?

A Python documentation string is known as docstring, it is a way of documenting Python functions, modules and classes.

279) What is the difference between Xrange and range?

Xrange returns the xrange object while range returns list, and uses same memory and no matter what the range size is.

280) What is module and package in Python?

In Python, module is way to structure the program. Each Python program file is a module, which imports other modules like objects and attributes.

The folder of Python program is a package of modules. A package can have modules or subfolders.

281) Mention the use of // operator in Python? 

It is a Floor Division operator, which is used for dividing two operands with the result as quotient showing only digits before the decimal point. For instance, 10//5 = 2 and 10.0//5.0 = 2.0.

282) 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 is executed (i.e., the indenting) not by any explicit keyword.

283) Name some of the built-in modules in Python? 

The built-in modules in Python are:

  • sys module
  • OS module
  • random module
  • collection module
  • JSON
  • Math module

284) What is Dogpile effect?

This is defined as an occurrence of event when the cache expires and also when the websites are hit with more number of requests by the client at a time. This dogpile effect can be averted by the use of semaphore lock. If in the particular system the value expires then, first of all, the particular process receives the lock and begin generating new value.

285) What are the OOPS concepts available in Python?

Python is also object-oriented programming language like other programming languages. It also contains different OOPS concepts, and they are

  • Object
  • Class
  • Method
  • Encapsulation
  • Abstraction • Inheritance • Polymorphism 286) Does Python make use of access specifiers?

Python does not make use of access specifiers and also it does not provide a way to access an instance variable. Python introduced a concept of prefixing the name of the method, function, or variable by using a double or single underscore to act like the behaviour of private and protected access specifiers.

287) What is the best Python IDE for beginners? 

There are many IDE’s to execute Python code. But, as a beginner, the following two IDE’s will be helpful

  • PyCharm
  • Spyder 288) Does Python replace Java?

Python alone can’t replace Java, whereas a group of programming languages can replace Java but JVM can’t be replaced. 289) Explain what is Flask & its benefits?

Flask is a web microframework for Python based on “Werkzeug, Jinja 2 and good intentions” BSD licensed. Werkzeug and jingja are two of its dependencies.

Flask is part of the micro-framework. Which means it will have little to no dependencies on external libraries. It makes the framework light while there is little dependency to update and fewer security bugs.

290) Mention what is Flask-WTF and what are their features?

Flask-WTF offers simple integration with WTForms. Features include for Flask WTF are

  • Integration with wtforms
  • Secure form with csrf token
  • Global csrf protection
  • Internationalization integration
  • Recaptcha supporting
  • File upload that works with Flask Uploads 291) Explain what is the common way for the Flask script to work? The common way for the flask script to work is
  • Either it should be the import path for your application • Or the path to a Python file 292) Explain how you can access sessions in Flask?

A session allows you to remember information from one request to another. In a flask, it uses a signed cookie so the user can look at the session contents and modify them. The user can modify the session if only it has the secret key Flask.secret_key.

293) What is the purpose of PYTHONPATH environment variable?

PYTHONPATH – It has a role similar to PATH. This variable tells the Python interpreter where to locate the module files imported into a program. It should include the Python source library directory and the directories containing Python source code. PYTHONPATH is sometimes preset by the Python installer.

294) What is the purpose of PYTHONSTARTUP environment variable?

PYTHONSTARTUP – It contains the path of an initialization file containing Python source code. It is executed every time you start the interpreter. It is named as .pythonrc.py in Unix and it contains commands that load utilities or modify PYTHONPATH.

295) What is the purpose of PYTHONCASEOK environment variable?

PYTHONCASEOK − It is used in Windows to instruct Python to find the first case-insensitive match in an import statement. Set this variable to any value to activate it.

296) What is the purpose of PYTHONHOME environment variable?

PYTHONHOME − It is an alternative module search path. It is usually embedded in the PYTHONSTARTUP or PYTHONPATH directories to make switching module libraries easy. 297) What is the purpose of ** operator?

** Exponent − Performs exponential (power) calculation on operators. a**b = 10 to the power 20 if a = 10 and b = 20.

298) Is the Python platform independent?

No, There are some modules and functions in python that can only run on certain platforms.

299) What do file-related modules in Python do? Can you name some file-related modules in Python?

Python comes with some file-related modules that have functions to manipulate text files and binary files on a file system. These modules can be used to create text or binary files, update their content, copy, delete, and more.

Some file-related modules are os, os.path, and shutil.os. The os.path module has functions to access the file system, while the shutil.os module can be used to copy or delete files.

300) Is indentation optional in Python?

Indentation in Python is compulsory and is part of its syntax. All programming languages have some way of defining the scope and extent of the block of codes; in Python, it is indentation. Indentation provides better readability to the code, which is probably why Python has made it compulsory.