Q-1: What Is Python, What Are The Benefits of Using It, and What Do You Understand of PEP 8?
Q-1: What Is Python, What Are The Benefits of Using It, and What Do You Understand of PEP 8?
Q-1: What Is Python, What Are The Benefits of Using It, and What Do You Understand of PEP 8?
me/ajPlacementMaterials
Q-1: What Is Python, What Are The Benefits Of Using It, And
What Do You Understand Of PEP 8?
Python is one of the most successful interpreted languages. When you write a Python
script, it doesn’t need to get compiled before execution. Few other interpreted
languages are PHP and Javascript.
list1 = extendList(10)
list2 = extendList(123,[])
list3 = extendList('a')
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
However, the flow is like that a new list gets created once after the function is defined.
And the same get used whenever someone calls the extendList method without a list
argument. It works like this because the calculation of expressions (in default
arguments) occurs at the time of function definition, not during its invocation.
The list1 and list3 are hence operating on the same default list, whereas list2 is running
on a separate object that it has created on its own (by passing an empty list as the value
of the list parameter).
The definition of the extendList function can get changed in the following manner.
list1 = [10]
list2 = [123]
list3 = ['a']
Q-3: What Is The Statement That Can Be Used In Python If
The Program Requires No Action But Requires It Syntactically?
The pass statement is a null operation. Nothing happens when it executes. You should
use “pass” keyword in lowercase. If you write “Pass,” you’ll face an error like
“NameError: name Pass is not defined.” Python statements are case sensitive.
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Q-4: What’s The Process To Get The Home Directory Using ‘~’
In Python?
You need to import the os module, and then just a single line would do the rest.
import os
print (os.path.expanduser('~'))
Output:
/home/runner
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
https://imojo.in/ajGuideAlgoDS
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Check out the “re” expression that can check the email id for .com and .co.in subdomain.
import re
print(re.search(r"[0-9a-zA-Z.]+@[a-zA-Z]+\.(com|co\.in)$","micheal.pages@mp.com"))
Q-12: What Do You Think Is The Output Of The Following
Code Fragment? Is There Any Error In The Code?
list = ['a', 'b', 'c', 'd', 'e']
print (list[10:])
The result of the above lines of code is []. There won’t be any error like an IndexError.
You should know that trying to fetch a member from the list using an index that exceeds
the member count (for example, attempting to access list[10] as given in the question)
would yield an IndexError. By the way, retrieving only a slice at the starting index that
surpasses the no. of items in the list won’t result in an IndexError. It will just return an
empty list.
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
for i in range(5):
print(i)
The range() function accompanies two sets of parameters.
▪ range(stop)
▪ stop: It is the no. of integers to generate and starts from zero. eg. range(3) ==
[0, 1, 2].
▪ range([start], stop[, step])
▪ Start: It is the starting no. of the sequence.
▪ Stop: It specifies the upper limit of the sequence.
▪ Step: It is the incrementing factor for generating the sequence.
▪ Points to note:
▪ Only integer arguments are allowed.
▪ Parameters can be positive or negative.
▪ The range() function in Python starts from the zeroth index.
Q-15: What Are The Optional Statements Possible Inside A
Try-Except Block In Python?
There are two optional clauses you can use in the try-except block.
▪ The “else” clause
▪ It is useful if you want to run a piece of code when the try block doesn’t create
an exception.
▪ The “finally” clause
▪ It is useful when you want to execute some steps which run, irrespective of
whether there occurs an exception or not.
Q-16: What Is A String In Python?
A string in Python is a sequence of alpha-numeric characters. They are immutable
objects. It means that they don’t allow modification once they get assigned a value.
Python provides several methods, such as join(), replace(), or split() to alter strings. But
none of these change the original object.
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Python has support for formatting any value into a string. It may contain quite complex
expressions.
One of the common usages is to push values into a string with the %s format specifier.
The formatting operation in Python has the comparable syntax as the C function printf()
has.
Let’s take an example. We have an “str” variable holding a string value. We can’t mutate
the container, i.e., the string, but can modify what it contains that means the value of the
variable.
In Python, strings are also lists of characters. We can access them using the index which
begins from zero and goes to the length minus one.
For example, in the string “Program,” the indexing happens like this:
Program 0 1 2 3 4 5
Q-21: What Is Docstring In Python?
A docstring is a unique text that happens to be the first statement in the following
Python constructs:
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Python has given us many built-in functions such as print() and provides the ability to
create user-defined functions.
1. Built-in, and
2. User-defined.
The built-in functions happen to be part of the Python language. Some of these are
print(), dir(), len(), and abs() etc.
Step-1: to begin the function, start writing with the keyword def and then mention the
function name.
Step-2: We can now pass the arguments and enclose them using the parentheses. A
colon, in the end, marks the end of the function header.
Step-3: After pressing an enter, we can add the desired Python statements for execution.
The return is a Python statement which we can use in a function for sending a value
back to its caller.
Python will treat that variable as local in the function-level scope. Any changes made to
that variable will remain local and will not reflect outside the function.
This scheme also has the advantage of bringing more time and space efficiency because
it leaves the need for creating local copies.
On the contrary, the disadvantage could be that a variable can get changed accidentally
during a function call. Hence, the programmers need to handle in the code to avoid such
uncertainty.
The continue statement is applicable for both the “while” and “for” loops.
Signature: id(object)
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
It accepts one parameter and returns a unique identifier associated with the input
object.
Please note that this type of argument syntax doesn’t allow passing a named argument
to the function.
I
am
Learning
Python
Q-34: What Does The **Kwargs Do In Python?
We can also use the **kwargs syntax in a Python function declaration. It let us pass N
(variable) number of arguments which can be named or keyworded.
Since Python is interpreter-based, so it sequentially executes the lines of the code one-
by-one.
Python also does have a Main() method. But it gets executed whenever we run our
Python script either by directly clicking it or starts it from the command line.
We can also override the Python default main() function using the Python if statement.
Please see the below code.
print("Welcome")
print("__name__ contains: ", __name__)
def main():
print("Testing the main function")
if __name__ == '__main__':
main()
The output:
Welcome
__name__ contains: __main__
Testing the main function
Q-36: What Does The __ Name __ Do In Python?
The __name__ is a unique variable. Since Python doesn’t expose the main() function, so
when its interpreter gets to run the script, it first executes the code which is at level 0
indentation.
To see whether the main() gets called, we can use the __name__ variable in an if clause
compares with the value “__main__.”
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
The break statement in a nested loop causes the control to exit from the inner iterative
block.
On the contrary, the pass statement instructs to do nothing, and the remainder of the
code executes as usual.
It returns the string denoting a character whose Unicode code point is an integer.
For example, the chr(122) returns the string ‘z’ whereas the chr(1212) returns the
string ‘Ҽ’.
>>> ord("z")
122
Q-43: What Is Rstrip() In Python?
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Python provides the rstrip() method which duplicates the string but leaves out the
whitespace characters from the end.
The rstrip() escapes the characters from the right end based on the argument value, i.e.,
a string mentioning the group of characters to get excluded.
str.rstrip([char sequence/pre>
#Example
test_str = 'Programming '
# The trailing whitespaces are excluded
print(test_str.rstrip())
Q-44: What Is Whitespace In Python?
Whitespace represents the characters that we use for spacing and separation.
It returns True if all characters in the string are of alphabet type, else it returns False.
#Example
str = 'pdf csv json'
print(str.split(" "))
print(str.split())
The output:
#Example
str = 'lEaRn pYtHoN'
print(str.title())
The output:
Learn Python
Now, check out some general purpose Python interview questions.
The tests confirmed that PyPy is nearly five times faster than the CPython. It currently
supports Python 2.7.
For example, many of the Python operations execute as atomic such as calling the sort()
method on a list.
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Python implements a heap manager internally which holds all of its objects and data
structures.
This heap manager does the allocation/de-allocation of heap space for objects.
They are similar to sequences, just like the lists. However, There are some differences
between a tuple and list; the former doesn’t allow modifications whereas the list does.
Also, the tuples use parentheses for enclosing, but the lists have square brackets in their
syntax.
The collection is a set of keys having a single associated value. We can call it a hash, a
map, or a hashmap as it gets called in other programming languages.
They are mutable and hence will not change. The values associated with the keys can be
of any Python types.
Internally, it has a contiguous array for referencing to other objects and stores a pointer
to the array variable and its length in the list head structure.
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
A Python class is a blueprint for creating the objects. It defines member variables and
gets their behavior associated with them.
We can make it by using the keyword “class.” An object gets created from the
constructor. This object represents the instance of the class.
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
The common code rests with the base class, and the child class objects can access it via
inheritance. Check out the below example.
desk = Desktop()
print(desk.processor, desk.os, desk.ram)
lap = Laptop()
print(lap.processor, lap.os, lap.ram)
The output:
To demonstrate composition, we need to instantiate other objects in the class and then
make use of those instances.
self.ram = ram
def get_PC(self):
return "%s cpu & %s ram" % (self.processor, self.ram)
class Tablet():
make = "Intel"
def __init__(self, processor, ram, make):
self.PC = PC(processor, ram) # Composition
self.make = make
def get_Tablet(self):
return "Tablet with %s CPU & %s ram by %s" % (self.PC.processor, self.PC.ram, self.make)
if __name__ == "__main__":
tab = Tablet("i7", "16 GB", "Intel")
print(tab.get_Tablet())
The output is:
On the contrary, exceptions happen due to the occurrence of an external event which
interrupts the normal flow of the program.
try:
print("Executing code in the try block")
print(exception)
except:
print("Entering in the except block")
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
finally:
print("Reached to the final block")
The output is:
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
For example, if we want the user to enter only odd numbers, else will raise an exception.
Python library has a no. of iterators. For example, a list is also an iterator and we can
start a for loop over it.
A Generator is a kind of function which lets us specify a function that acts like an
iterator and hence can get used in a “for” loop.
print(next(generate()))
The output is:
In the example below, we’ve written a simple closure for multiplying numbers.
def multiply_number(num):
def product(number):
'product() here is a closure'
return num * number
return product
num_2 = multiply_number(2)
print(num_2(11))
print(num_2(24))
num_6 = multiply_number(6)
print(num_6(1))
The output is:
22
48
6
Q-71: What Are Decorators In Python?
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Python decorator gives us the ability to add new behavior to the given objects
dynamically. In the example below, we’ve written a simple example to display a
message pre and post the execution of a function.
def decorator_sample(func):
def decorator_hook(*args, **kwargs):
print("Before the function call")
result = func(*args, **kwargs)
print("After the function call")
return result
return decorator_hook
@decorator_sample
def product(x, y):
"Function to multiply two numbers."
return x * y
print(product(3, 3))
The output is:
However, we can take values of any kind. For distinguishing the data pairs, we can use a
comma(“,”) and keep the whole stuff inside curly braces({…}).
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
For example, the below code will return all the numbers from 10 to 20 and store them
in a list.
While using the iterators, sometimes we might have a use case to store the count of
iterations. Python gets this task quite easy for us by giving a built-in method known as
the enumerate().
The enumerate() function attaches a counter variable to an iterable and returns it as the
“enumerated” object.
We can use this object directly in the “for” loops or transform it into a list of tuples by
calling the list() method. It has the following signature:
enumerate(iterable, to_begin=0)
Arguments:
iterable: array type object which enables iteration
to_begin: the base index for the counter is to get started, its default value is 0
# Example - enumerate function
alist = ["apple","mango", "orange"]
astr = "banana"
print(list(enumerate(alist)) )
# Move the starting index to two from zero
print(list(enumerate(astr, 2)))
The output is:
Python maintains a symbol table to keep all necessary information about a program.
This info includes the names of variables, methods, and classes used by the program.
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
All the information in this table remains in the global scope of the program and Python
allows us to retrieve it using the globals() method.
Signature: globals()
Arguments: None
# Example: globals() function
x=9
def fn():
y=3
z=y+x
# Calling the globals() method
z = globals()['x'] = z
return z
# Test Code
ret = fn()
print(ret)
The output is:
12
Q-84: Why Do You Use The Zip() Method In Python?
The zip method lets us map the corresponding index of multiple containers so that we
can use them using as a single unit.
Signature:
zip(*iterators)
Arguments:
Python iterables or collections (e.g., list, string, etc.)
Returns:
A single iterator object with combined mapped values
# Example: zip() function
The output of zip() is : {('jerry', 33, 'R&D'), ('jake', 44, 'IT'), ('john', 28, 'Accounts'), ('tom', 32, 'HR')}
Q-85: What Are Class Or Static Variables In Python
Programming?
In Python, all the objects share common class or static variables.
But the instance or non-static variables are altogether different for different objects.
The programming languages like C++ and Java need to use the static keyword to make a
variable as the class variable. However, Python has a unique way to declare a static
variable.
All names initialized with a value in the class declaration becomes the class variables.
And those which get assigned values in the class methods becomes the instance
variables.
# Example
class Test:
aclass = 'programming' # A class variable
def __init__(self, ainst):
self.ainst = ainst # An instance variable
print(test1.aclass)
print(test2.aclass)
print(test1.ainst)
print(test2.ainst)
programming
programming
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
1
2
programming
Let’s now answer some advanced-level Python interview questions.
Q-86: How Does The Ternary Operator Work In Python?
The ternary operator is an alternative for the conditional statements. It combines true
or false values with a statement that you need to test.
▪ copy.copy() function
▪ It makes a copy of the file from source to destination.
▪ It’ll return a shallow copy of the parameter.
▪ copy.deepcopy() function
▪ It also produces the copy of an object from the source to destination.
▪ It’ll return a deep copy of the parameter that you can pass to the function.
Q-89: What Is The Purpose Of Docstrings In Python?
In Python, the docstring is what we call as the docstrings. It sets a process of recording
Python functions, modules, and classes.
def demo2():
print 'in demo2()'
def demo1():
print 'in demo1()'
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
demo2()
sys.settrace(trace_calls)
demo1()
Q-95: Why And When Do You Use Generators In Python?
A generator in Python is a function which returns an iterable object. We can iterate on
the generator object using the yield keyword. But we can only do that once because
their values don’t persist in memory, they get the values on the fly.
Generators give us the ability to hold the execution of a function or a step as long as we
want to keep it. However, here are a few examples where it is beneficial to use
generators.
▪ We can replace loops with generators for efficiently calculating results involving
large data sets.
▪ Generators are useful when we don’t want all the results and wish to hold back for
some time.
▪ Instead of using a callback function, we can replace it with a generator. We can
write a loop inside the function doing the same thing as the callback and turns it
into a generator.
Q-96: What Does The Yield Keyword Do In Python?
The yield keyword can turn any function into a generator. It works like a standard
return keyword. But it’ll always return a generator object. Also, a method can have
multiple calls to the yield keyword.
See the example below.
def testgen(index):
weekdays = ['sun','mon','tue','wed','thu','fri','sat']
yield weekdays[index]
yield weekdays[index+1]
day = testgen(0)
print next(day), next(day)
But remember, we can’t change the list after turning it into a tuple because it becomes
immutable.
weekdays = ['sun','mon','tue','wed','thu','fri','sat']
listAsTuple = tuple(weekdays)
print(listAsTuple)
▪ Set doesn’t allow duplicate entries so that the conversion will remove any such
item.
▪ A set is an ordered collection, so the order of list items would also change.
However, we can use the set() function to convert a list into a Set.
weekdays = ['sun','mon','tue','wed','thu','fri','sat','sun','tue']
listAsSet = set(weekdays)
print(listAsSet)
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
However, we can achieve the conversion by breaking the list into a set of pairs and then
call the zip() function to return them as tuples.
Passing the tuples into the dict() function would finally turn them into a dictionary.
weekdays = ['sun','mon','tue','wed','thu','fri']
listAsDict = dict(zip(weekdays[0::2], weekdays[1::2]))
print(listAsDict)
In Python, the list has a count() function which returns the occurrences of a particular
item.
Count The Occurrences Of An Individual Item.
weekdays = ['sun','mon','tue','wed','thu','fri','sun','mon','mon']
print(weekdays.count('mon'))
#output: 3
Count The Occurrences Of Each Item In The List.
We’ll use the list comprehension along with the count() method. It’ll print
the frequency of each of the items.
weekdays = ['sun','mon','tue','wed','thu','fri','sun','mon','mon']
print([[x,weekdays.count(x)] for x in set(weekdays)])
#output: [['wed', 1], ['sun', 2], ['thu', 1], ['tue', 1], ['mon', 3], ['fri', 1]]
Q-99: What Is NumPy And How Is It Better Than A List In
Python?
NumPy is a Python package for scientific computing which can deal with large data
sizes. It includes a powerful N-dimensional array object and a set of advanced functions.
Also, the NumPy arrays are superior to the built-in lists. There are a no. of reasons for
this.
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Q #1) Can Python be used for web client and web server side programming? And
which one is best suited to Python?
Answer: Python is best suited for web server-side application development due to its
vast set of features for creating business logic, database interactions, web server
hosting etc.
However, Python can be used as a web client-side application which needs some
conversions for a browser to interpret the client side logic. Also, note that Python can be
used to create desktop applications which can run as a standalone application such as
utilities for test automation.
Q #2) Mention at least 3-4 benefits of using Python over the other scripting
languages such as Javascript.
Answer: Enlisted below are some of the benefits of using Python.
1. Application development is faster and easy.
2. Extensive support of modules for any kind of application development including
data analytics/machine learning/math-intensive applications.
3. An excellent support community to get your answers.
Q #3) Explain List, Tuple, Set, and Dictionary and provide at least one instance
where each of these collection types can be used.
Answer:
• List: Collection of items of different data types which can be changed at run time.
• Tuple: Collection of items of different data types which cannot be changed. It
only has read-only access to the collection. This can be used when you want to
secure your data collection set and does not need any modification.
• Set: Collection of items of a similar data type.
• Dictionary: Collection of items with key-value pairs.
Generally, List and Dictionary are extensively used by programmers as both of them
provide flexibility in data collection.
Q #7) What tools can be used to unit test your Python code?
Answer: The best and easiest way is to use ‘unittest' python standard library to test
units/classes. The features supported are very similar to the other unit testing tools such
as JUnit, TestNG.
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Q #8) How does For loop and While loop differ in Python and when do you choose
to use them?
Answer: For loop is generally used to iterate through the elements of various collection
types such as List, Tuple, Set, and Dictionary.
While loop is the actual looping feature that is used in any other programming language.
This is how Python differs in handling loops from the other programming languages.
Q #9) How are data types defined in Python and how much bytes do integer and
decimal data types hold?
Answer: In Python, there is no need to define a variable's data type explicitly.
Based on the value assigned to a variable, Python stores the appropriate data type. In
the case of numbers such as Integer, Float, etc, the length of data is unlimited.
Q #12) What is the best way to parse strings and find patterns in Python?
Answer: Python has built-in support to parse strings using Regular expression module.
Import the module and use the functions to find a sub-string, replace a part of a string,
etc.
Q #13) Which databases are supported by Python?
Answer: MySQL (Structured) and MongoDB (Unstructured) are the prominent
databases that are supported natively in Python. Import the module and start using the
functions to interact with the database.
Q #14) What is the purpose of _init_() function in Python?
Answer: It is the first function that gets executed when an object of a class is
instantiated. This is equivalent to the constructor concept in C++.
Q #15) What is the significance of ‘self' parameter in an object method? Should we
always name this parameter as ‘self'?
Answer: Parameter ‘self' is used to refer to the object properties of a class.
‘self' parameter is supposed to be prefixed to the class object properties. The answer to
the second part of the question is No. ‘self' parameter can have any name.
Q #16) How does Lambda function differ from a normal function in Python?
Answer: Lambda is similar to the inline function in C programming. It returns a function
object. It contains only one expression and can accept any number of arguments.
In case of a normal function, you can define a function name, pass the parameter and
mandatorily have a return statement. The Lambda function can be typically used for
simple operations without the use of function names. It can also be used in the place of
a variable.
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Answer: There are 3 main keywords i.e. try, except and finally which are used to catch
exceptions and handle the recovering mechanism accordingly. Try is the block of a code
which is monitored for errors. Except block gets executed when an error occurs.
The beauty of the final block is to execute the code after trying for error. This block gets
executed irrespective of whether an error occurred or not. Finally block is used to do the
required cleanup activities of objects/variables.
Q #24) Does the same Python code work on multiple platforms without any
changes?
Answer: Yes. As long as you have the Python environment on your target platform
(Linux, Windows, Mac), you can run the same code.
Q #25) How can you create a GUI based application in Python for client-side
functionality?
Answer: Python along with standard library Tkinter can be used to create GUI based
applications. Tkinter library supports various widgets which can create and handle
events which are widget specific.
Q #26) What are the different environment variables identified by Python?
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Answer:
PYTHONPATH: This environment variable helps the interpreter as to where to locate
the module files imported in the program.
PYTHONSTARTUP: This environment variable contains the path of the Initialization file
containing source code.
PYTHONCASEOK: This variable is used to find the first case-insensitive match in the
import statement
Q #27) What is Python Tuples and how is it different from Lists?
Answer: Tuples is basically a sequence of elements which are separated by commas
and are enclosed in parenthesis.
Lists whereas is a sequence of elements which are separated by commas and are
enclosed in brackets. Also, Tuples cannot be updated whereas, in lists, elements can be
updated along with their sizes.
Output:
I am a beginner in Python
print(‘%. 6s’ % a)
File text:
Python is a powerful high-level, object-oriented programming language created by Guido
van Rossum.
It has simple easy-to-use syntax, making it the perfect language for someone trying to
learn computer programming for the first time.
Answer:
f = open ("softwaretestinghelp.txt ", "r")
Output:
Python
It has simple easy-to-use syntax, making it the perfect language for someone trying to
learn computer programming for the first time.
b is available is list
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Q #35) Write the command to get all keys from the dictionary.
Answer: print dict.keys()
Q #36) Write a command to convert a string into an int in python.
Answer: int(x [,base])
Q #37) What are a help () and dir() in python?
Answer: help () is a built-in function that can be used to return the Python
documentation of a particular object, method, attributes, etc.
dir () displays a list of attributes for the objects which are passed as an argument. If dir()
is without the argument then it returns a list of names in current local space.
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Suite
Else
Suite
Print (var)
print (str.isalnum())
print (str.isalnum())
Answer: False
True
Q #43) What is a from import statement and write the syntax for it?
Answer: From statement allows specific attributes to be imported from a module in a
current namespace.
Syntax: from modname import name1[, name2[, … nameN]]
Q #44) What is the difference between locals() and globals ()?
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Answer: locals() is accessed within the function and it returns all names that can be
accessed locally from that function.
globals() returns all names that can be accessed globally from that function.
print(“Python”)
else
pass
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
The package has something called the GIL or Global Interpreter Lock, which is a construct. It
ensures that one and only one of the threads execute at any given time. A thread acquires the
GIL and then do some work before passing it to the next thread.
This happens so fast that to a user it seems that threads are executing in parallel. Obviously,
this is not the case as they are just taking turns while using the same CPU core. Moreover, GIL
passing adds to the overall overhead to the execution.
Hence, if you intend to use the threading package for speeding up the execution, using the
package is not recommended.
Xrange is not able to generate a static list at runtime the way range does. On the contrary, it
creates values along with the requirements via a special technique called yielding. It is used
with a type of object known as generators.
If you have a very enormous range for which you need to generate a list, then xrange is the
function to opt for. This is especially relevant for scenarios dealing with a memory-sensitive
system, such as a smartphone.
The range is a memory beast. Using it requires much more memory, especially if the
requirement is gigantic. Hence, in creating an array of integers to suit the needs, it can result
in a Memory Error and ultimately lead to crashing the program.
The class which acquires is known as the child class or the derived class. The one that it
acquires from is known as the superclass or base class or the parent class. There are 4 forms
of inheritance supported by Python:
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
http://webcache.googleusercontent.com/search?q=cache:URLGOESHERE
Simply replace URLGOESHERE with the web address of the website or webpage whose cache
you need to retrieve and see in Python.
SQLite stores data as a single file in the filesystem. Now, you need to tell Django how to use
the database. For this, the project’s setting.py file needs to be used. Following code must be
added to the file for making the database workable with the Django project:
DATABASES = {
'default': {
'ENGINE' : 'django.db.backends.sqlite3',
If you need to use a database server other than the SQLite, such as MS SQL, MySQL, and
PostgreSQL, then you need to use the database’s administration tools to create a brand new
database for your Django project.
You have to modify the following keys in the DATABASE ‘default’ item to make the new
database work with the Django project:
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Question: How will you differentiate between deep copy and shallow copy?
Answer: We use shallow copy when a new instance type gets created. It keeps the values that
are copied in the new instance. Just like it copies the values, the shallow copy also copies the
reference pointers.
Reference points copied in the shallow copy reference to the original objects. Any changes
made in any member of the class affects the original copy of the same. Shallow copy enables
faster execution of the program.
Deep copy is used for storing values that are already copied. Unlike shallow copy, it doesn’t
copy the reference pointers to the objects. Deep copy makes the reference to an object in
addition to storing the new object that is pointed by some other object.
Changes made to the original copy will not affect any other copy that makes use of the
referenced or stored object. Contrary to the shallow copy, deep copy makes execution of a
program slower. This is due to the fact that it makes some copies for each object that is called.
As one of NumPy’s most important goals is compatibility, the library tries to retain all features
supported by either of its predecessors. Hence, NumPy contains a few linear algebra
functions despite the fact that these more appropriately belong to the SciPy library.
SciPy contains fully-featured versions of the linear algebra modules available to NumPy in
addition to several other numerical algorithms.
A0 = dict(zip(('a','b','c','d','e'),(1,2,3,4,5)))
A4 = [i for i in A1 if i in A3]
print(A0,A1,A2,A3,A4,A5,A6)
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Question: Python has something called the dictionary. Explain using an example.
Answer: A dictionary in Python programming language is an unordered collection of data
values such as a map. Dictionary holds key:value pair. It helps in defining a one-to-one
relationship between keys and values. Indexed by keys, a typical dictionary contains a pair of
keys and corresponding values.
Let us take an example with three keys, namely Website, Language, and Offering. Their
corresponding values are hackr.io, Python, and Tutorials. The code for the example will be:
dict={‘Website’:‘hackr.io’,‘Language’:‘Python’:‘Offering’:‘Tutorials’}
Question: Python supports negative indexes. What are they and why are they used?
Answer: The sequences in Python are indexed. It consists of the positive and negative
numbers. Positive numbers use 0 as the first index, 1 as the second index, and so on. Hence,
any index for a positive number n is n-1.
Unlike positive numbers, index numbering for the negative numbers start from -1 and it
represents the last index in the sequence. Likewise, -2 represents the penultimate index.
These are known as negative indexes. Negative indexes are used for:
• Removing any new-line spaces from the string, thus allowing the string to except the
last character, represented as S[:-1]
• Showing the index to representing the string in the correct order
Question: Suppose you need to collect and print data from IMDb top 250 Movies page.
Write a program in Python for doing so. (NOTE: – You can limit the displayed
information for 3 fields; namely movie name, release year, and rating.)
Answer:
import requests
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
import sys
url = 'http://www.imdb.com/chart/top'
response = requests.get(url)
soup = BeautifulSoup(response.text)
tr = soup.findChildren("tr")
tr = iter(tr)
next(tr)
row = title + ' - ' + year + ' ' + ' ' + rating
print(row)
try:
if '1' != 1:
raise "someError"
else:
except "someError":
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
# m.py
class MyClass:
def f(self):
print "f()"
import m
def monkey_f(self):
print "monkey_f()"
m.MyClass.f = monkey_f
obj = m.MyClass()
obj.f()
The examples demonstrate changes made in the behavior of f() in MyClass using the function
we defined i.e. monkey_f() outside of the module m.
In the case of dynamic loading, the process of compilation and linking depends on the style
that is provided with the concerned system. In order to provide dynamic loading of the
configuration setup files and rebuilding the interpreter, the Python interpreter is used.
Question: What is Flask and what are the benefits of using it?
Answer: Flask is a web microframework for Python with Jinja2 and Werkzeug as its
dependencies. As such, it has some notable advantages:
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Typically, the given function is the first argument and the iterable is available as the second
argument to a map() function. Several tables are given if the function takes in more than one
arguments.
The reverse process of pickling is known as unpickling i.e. retrieving original Python objects
from a stored string representation.
Question: Whenever Python exits, all the memory isn’t deallocated. Why is it so?
Answer: Upon exiting, Python’s built-in effective cleanup mechanism comes into play and try
to deallocate or destroy every other object.
However, Python modules that are having circular references to other objects or the objects
that are referenced from the global namespaces aren’t always deallocated or destroyed.
This is because it is not possible to deallocate those portions of the memory that are reserved
by the C library.
import numpy as np
print(arr.argsort()[-3:][::-1])
Output:
[4 3 1]
Question: Write code to show randomizing the items of a list in place in Python along
with the output.
Answer:
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
shuffle(x)
print(x)
Output:
That’s All!
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
1. What is Python?
Python is a high-level, interpreted, general-purpose programming language. Being a
general-purpose language, it can be used to build almost any type of application with the
right tools/libraries. Additionally, python supports objects, modules, threads, exception-
handling and automatic memory management which help in modelling real-world
problems and building applications to solve these problems.
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
PEP stands for Python Enhancement Proposal. A PEP is an official design document
providing information to the Python Community, or describing a new feature for Python or
its processes. PEP 8 is especially important since it documents the style guidelines for
Python Code. Apparently contributing in the Python open-source community requires you
to follow these style guidelines sincerely and strictly.
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
def func():
temp = 20 # local-scope variable
print(temp)
def func():
global temp
temp = 20 # local-scope variable
print(temp)
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
func = function()
string_split = func.split()
return string_split
return wrapper
@names_decorator
def say_hello(name1, name2):
return 'Hello ' + name1 + '! Hello ' + name2 + '!'
means that lists can be modified, appended or sliced on-the-go but tuples remain constant
and cannot be modified in any manner. You can run the following example on Python
IDLE to confirm the difference:
my_tuple = ('sara', 6, 5, 0.97)
my_list = ['sara', 6, 5, 0.97]
▪ a = [1, 2, 3]
▪ b = [7, 8, 9]
▪
▪ [(x + y) for (x,y) in zip(a,b)] # parallel iterators
▪ # output => [8, 10, 12]
▪
▪ [(x,y) for x in a for y in b]# nested iterators
▪ # output => [(1, 7), (1, 8), (1, 9), (2, 7), (2, 8), (2, 9), (3, 7), (3, 8), (3, 9)]
▪ Flattening a multi-dimensional list
A similar approach of nested iterators (as above) can be applied to flatten a multi-
dimensional list or work upon its inner elements.
▪ my_list = [[10,20,30],[40,50,60],[70,80,90]]
▪
▪ flattened = [x for temp in my_list for x in temp]
▪ # output => [10, 20, 30, 40, 50, 60, 70, 80, 90]
Note: List comprehensions have the same effect as the map method in other languages. They
follow the mathematical set builder notation rather than map and filterfunctions in Python.
complex Stores complex number in the form (A + Bj) and has attributes: real and im
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
▪ Sequence Types
According to Python Docs, there are three basic Sequence Types - lists, tuples, and range
objects. Sequence types have the in and not in operators defined for their traversing their
elements. These operators share the same priority as the comparison operations.
Class Name Description
list Mutable sequence used to store collection of items.
tuple Immutable sequence used to store collection of items.
range Represents an immutable sequence of numbers generated during exec
str Immutable sequence of Unicode code points to store textual data.
▪ Note: The standard library also includes additional types for processing:
1. Binary data such as bytearray bytes memoryview , and
2. Text strings such as str .
▪ Mapping Types
A mapping object can map hashable values to random objects in Python. Mappings objects
are mutable and there is currently only one standard mapping type, the dictionary.
Class Name Description
dict Stores comma-separated list of key: value pairs
▪
▪ Set Types
Currently, Python has two built-in set types - set and frozenset. set type is mutable and
supports methods like add() and remove(). frozenset type is immutable and can't be
modified after creation.
Class Name Description
set Mutable unordered collection of distinct hashable objects
frozenset Immutable collection of distinct hashable objects
▪ Note: set is mutable and thus cannot be used as key for a dictionary. On the other
hand, frozenset is immutable and thus, hashable, and can be used as a dictionary key or as an
element of another set.
▪ Modules
Module is an additional built-in type supported by the Python Interpreter. It supports one
special operation, i.e., attribute access: mymod.myobj, where mymod is a module
and myobj references a name defined in m's symbol table. The module's symbol table
resides in a very special attribute of the module __dict__, but direct assignment to this
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
▪ Callable Types
Callable types are the types to which function call can be applied. They can be user-
defined functions, instance methods, generator functions, and some other built-in
functions, methods and classes.
Refer the documentation at docs.python.org for a detailed view into the callable types.
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
## shallow copy
list_2 = copy(list_1)
list_2[3] = 7
list_2[2].append(6)
## deep copy
list_3 = deepcopy(list_1)
list_3[3] = 8
list_3[2].append(7)
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
So how does that make a difference? It sure does, because unlike range(), xrange()
doesn't generate a static list, it creates the value on the go. This technique is commonly
used with an object type generators and has been termed as "yielding".
Yielding is crucial in applications where memory is a constraint. Creating a static list as
in range() can lead to a Memory Error in such conditions, while, xrange() can handle it
optimally by using just enough memory for the generator (significantly less in comparison).
for i in xrange(10): # numbers from o to 9
print i # output => 0 1 2 3 4 5 6 7 8 9
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
pat = [1, 3, 2, 1, 2, 3, 1, 0, 1, 3]
for p in pat:
pass
if (p == 0):
current = p
break
elif (p % 2 == 0):
continue
print(p) # output => 1 3 1 3 1
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
You are right place, If you are looking for python interview questions and answers, get more
confidence to crack interview by reading this questions and answers we will update more and more
latest questions for you…
1. What is Python?
Python tends to be utilized as a scripting language or can be aggregated to byte-code for structure
enormous applications.
It gives high-level dynamic data types and supports dynamic type checking.
Python tends to be effectively integrated with C, C++, COM, ActiveX, CORBA, and Java.
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
PYTHONPATH – It has a job like PATH. This variable advises the Python interpreter where to
find the module records brought into a program. It should incorporate the Python source library
registry and the indexes containing Python source code. PYTHONPATH is some times preset by
the Python installer.
Numbers
String
List
Tuple
Dictionary
An interpreted language is any programming language which isn’t in machine level code before
runtime. So, Python is a translated language.
A namespace is a naming system used to ensure that names are extraordinary to avoid naming
clashes.
7. What is PYTHONPATH?
A function is the block of code which is executed just when it is called. To define the function in
Python, the def keyword is utilized.
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Ex:
def Newfunc():
An anonymous function is known as a lambda function. This function can have any number of
parameters at the same time, but only one statement.
Example:
2.print(a(5, 6))
Result: 11
The self is an example or an object of a class. In Python, this is explicitly included as the principal
parameter. Be that as it may, this isn’t the situation in Java where it’s optional. It separates between
the techniques and characteristics of a class with local variables
The self-variable in the init technique refers to the recently made object while in different methods,
it refers to the object whose method is called.
12. In what capacity will you capitalize the first letter of string?
In Python, the capitalize () method capitalizes the first letter of a string. if the string now comprises
of a capital letter toward the start, at that point, it restores the original string.
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Multi-line comments show up in more than one line. Every one of the lines to be commented is to
be prefixed by a #. You can likewise an excellent easy route technique to comment on different
lines. You should simply hold the Ctrl key and left snap in each spot any place you need to
incorporate a # character and type a # just once. This will comment on each line where you
presented your cursor.
Docstrings are not really comments, at the same time, they are documentation strings. These
docstrings are inside triple statements. They are not assigned to any factor and considered as
comments as well.
Example:
1."""
4."""
x=8
y=4
z=x/y
print(z)
Result: 2.0
Operators are specifical functions. They take at least one value and produce a comparing result.
Is: returns genuine when 2 operands are valid (Example: “a” will be ‘a’)
Help() and dir() the two functions are available from the Python interpreter and utilized for survey
a united dump of built-in functions
Help() function: The assistance() work is utilized to show the documentation string and
furthermore encourages you to see the assistance identified with modules, watchwords, qualities,
and so on.
Dir() function: The dir() function is utilized to show the defined symbols.
PyChecker, which is a static analyser is the best tool to find bugs (or) to perform static analysis. It
distinguishes the bugs in Python project and furthermore uncovers the style and complexity related
bugs. Another tool is Pylint, which checks whether the Python module fulfills the coding standard.
Python decorator is a relative change that you do in Python programming structure to alter the
functions rapidly.
19. What Is The Main Difference Between A List And The Tuple?
The vital contrast between a list and the tuple is that the list is alterable while the tuple isn’t.
Python utilizes private heaps to keep up its memory. So the data holds all the Python objects and
the data structures. This area is just open to the Python translator; developers can’t utilize it.
Additionally, it’s the Python memory chief that handles the Private heap. It does the required
designation of the memory for Python objects. Python utilizes a built – in garbage collector, which
rescues all the unused memory and offloads it to the heap space.
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Slicing is a string activity for separating a piece of the string or some piece of a list. In Python, a
string (say data) starts at list 0, and the nth character stores at position text[n-1]. Python can likewise
perform invert ordering, i.e., in the regressive heading, with the assistance of negative numbers. In
Python, the Slice() is additionally a constructor function which produces a slice object. The
outcome is a lot of files referenced by range(start, stop, step). The Slice() strategy permits three
parameters. 1. Start – beginning number for the slice to start. 2. stop – the number which
demonstrates the finish of slice. 3. step – the value to augment after each record (default = 1).
The Index is an integer data type which indicates a position inside an ordered list or a string. In
Python, strings are likewise list of characters. We can get to them utilizing the file which starts
from zero and goes to the length short one.
For instance, in the string "Program," the ordering happens this way:
Program 0 1 2 3 4 5
A docstring is one of a kind content that happens to be the first statements in the accompanying
Python constructs:
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
A function is an object which describes to a piece of code and is a reusable element. It carries
measured quality to a program and a higher level of code re usability. Python has given us many
built-in capacities, for example, print () and gives the ability to create user-defined functions.
The Python trunc() work plays out mathematical operations to expel the decimal qualities from a
particular expression and gives integer value as the output.
It isn’t at all essential for a function to restore any value. In any case, if necessary, we can utilize
none as the incoming value.
The continue is a jump in Python which moves the control to execute the next cycle in a loop
leaving all the rest of the guidelines in the block unexecuted.
syntax: id(object)
Python provides a break statement to exit from a circle. At any point, if the break hits in the code,
the control of the program promptly exits from the body of the circle. The break statement in the
nested loop causes the controlled exit from the inner iterative square.
The continue statement makes the loop to continue from the next cycle. And the pass statement
instructs to do nothing, and the rest of the code executes obviously.
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
PHP is a recursive acronym for PHP Hypertext Preprocessor. It is a widely used open-source
programming language especially suited for creating dynamic websites and mobile API's.
Below PHP interview questions are helpful for 1 year, 2 years, 5 years experience PHP developer
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
You can add 301 redirect in PHP by adding below code snippet in your file.
In PHP Type hinting is used to specify the excepted data type of functions
argument.
Type hinting is introduced in PHP 5.
Example usage:-
//send Email function argument $email Type hinted of Email Class. It means to call
this function you must have to pass an email object otherwise an error is generated.
<?php
function sendEmail (Email $email)
{
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
$email->send();
}
?>
Default session time in PHP is 1440 seconds (24 minutes) and the Default session
storage path is temporary folder/tmp on server.
<?php
// server should keep session data for AT LEAST 1 hour
ini_set('session.gc_maxlifetime', 3600);
7. What is T_PAAMAYIM_NEKUDOTAYIM ?
Example usage:-
$Cache::getConfig($key);
In Overriding, a method of the parent class is defined in the child or derived class
with the same name and parameters. Overriding comes in inheritance.
<?php
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
class A {
function showName() {
return "Ajay";
}
}
class B extends A {
function showName() {
return "Anil";
}
}
$foo = new A;
$bar = new B;
echo($foo->myFoo()); //"Ajay"
echo($bar->myFoo()); //"Anil"
?>
In Overloading, there are multiple methods with the same name with different
signatures or parameters. Overloading is done within the same class. Overloading is
also called early binding or compile time polymorphism or static binding.
<?php
class A{
function sum($a,$b){
return $a+$b;
function sum($a,$b,$c){
return $a+$b+$c;
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
$obj= new A;
$obj->sum(1,3); // 4
$obj->sum(1,3,5); // 9
?>
cURL is a library in PHP that allows you to make HTTP requests from the server.
You can use library function array_unique() for removing duplicated values for an
array. Here is syntax to use it.
<?php
$a=array("a"=>"home","b"=>"town","c"=>"town","php");
print_r(array_unique($a));
?>
Example :
if(function_exists('curl_version') ){
echo "Curl is enabled";
}else{
Static method is a member of class that is called directly by class name without
creating an instance.In PHP uou can create a static method by using static keyword.
Example:
class A {
public static function sayHello() {
echo 'hello Static';
}
}
A::sayHello();
14. How can you get web browser’s details using PHP?
get_browser() function is used to retrieve the client browser details in PHP. This is a
library function is PHP which looks up the browscap.ini file of the user and returns
the capabilities of its browser.
Syntax:
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
get_browser(user_agent,return_array)
Example Usage:
array_combine is used to create a new array having keys of one array and values of
another array that are combined with each other whereas array_merge is used to
create a new array in such a way that values of the second array append at the end
of the first array.
Example of array_combine
<?php
$arr1 = array("sub1","sub2","sub3");
$arr2 = array(("php","html","css");
$new_arr = array_combine($arr1, $arr2);
print_r($new_arr);
?>
OUTPUT:
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Example of array_merge
<?php
$arr1 = array("sub1" => "node", "sub2" => "sql");
$arr2 = array("s1"=>"jQuery", "s3"=>"xml", "sub4"=>"Css");
$result = array_merge($arr1, $arr2);
print_r($result);
?>
OUTPUT:
Array ([s1] => jquery [sub2] => sql [s3] => xml [sub4] =>Css )
Both are used to make the changes to your PHP setting. These are explained below:
php.ini: It is a special file in PHP where you make changes to your PHP settings. It
works when you run PHP as CGI. It depends on you whether you want to use the
default settings or changes the setting by editing a php.ini file or, making a new text
file and save it as php.ini.
.htaccess: It is a special file that you can use to manage/change the behavior of
your site. It works when PHP is installed as an Apache module. These changes
include such as redirecting your domain’s page to https or www, directing all users to
one page, etc.
To terminate the script in PHP, exit() function is used. It is an inbuilt function which
outputs a message and then terminates the current script. The message which is
you want to display is passed as a parameter to the exit () function and this function
terminates the script after displaying the message. It is an alias function of die ()
function. It doesn’t return any value.
Syntax: exit(message)
Exceptions of exit():
• If a passed status is an integer then the value will not be printed but used as
the exit status.
• The range of exit status is from 0 to 254 where 255 is reserved in PHP.
Both MD5 and SHA256 are used as hashing algorithms. They take an input file and
generate an output which can be of 256/128-bit size. This output represents a
checksum or hash value. As, collisions are very rare between hash values, so no
encryption takes place.
• The difference between MD5 and SHA256 is that the former takes less time to
calculate than later one.
• SHA256 is difficult to handle than MD5 because of its size.
• SHA256 is less secure than MD5
• MD5 result in an output of 128 bits whereas SHA256 result output of 256 bits.
Concluding all points, it will be better to use MDA5 if you want to secure your files
otherwise you can use SHA256.
Heredoc and nowdoc are the methods to define the string in PHP in different ways.
• Heredoc process the $variable and special character while nowdoc doesn't do
the same.
• Heredoc string uses double quotes "" while nowdoc string uses single quote ''
• Parsing is done in heredoc but not in nowdoc.
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Path traversal basically implements by an attacker when he/she wants to gain secret
passwords, access token or other information stored in the files. Path traversal
attack allows the attacker to exploit vulnerabilities present in web file.
Floyd’s triangle is the right-angled triangle which starts with 1 and filled its rows with
a consecutive number. The count of elements in next row will increment by one and
the first row contains only one element.
<?php
$key = 1;
for ($i = 1; $i <= 4; $i++) {
for ($j = 1; $j <= $i; $j++) {
echo $key;
$key++;
if ($j == $i) {
echo "<br/>";
}
}
}
echo "";
?>
Output:
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
23
456
7 8 9 10
<?php
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
There are many differences between PHP 5 and 7. Some of the main points are:
• Performance: it is obvious that later versions are always better than the
previous versions if they are stable. So, if you execute code in both versions,
you will find the performance of PHP 7 is better than PHP5. This is because
PHP 5 use Zend II and PHP & uses the latest model PHP-NG or Next
Generation.
• Return Type: In PHP 5, the programmer is not allowed to define the type of
return value of a function which is the major drawback. But in PHP 7, this
limitation is overcome and a programmer is allowed to define the return type
of any function.
• Error handling: In PHP 5, there is high difficulty to manage fatal errors but in
PHP 7, some major errors are replaced by exceptions which can be managed
effortlessly. In PHP 7, the new engine Exception Objects has been
introduced.
• 64-bit support: PHP 5 doesn’t support 64-bit integer while PHP 7 supports
native 64-bit integers as well as large files.
• Anonymous Class: Anonymous class is not present n PHP 5 but present in
PHP 7. It is basically used when you need to execute the class only once to
increase the execution time.
• New Operators: Some new operators have added in PHP 7 such as <=>
which is called a three-way comparison operator. Another operator has added
is a null coalescing operator which symbol as?? and use to find whether
something exists or not.
• Group Use declaration: PHP 7 includes this feature whereas PHP 5 doesn’t
have this feature.
• ksort() function is used to sort an array according to its key values whereas
asort() function is used to sort an array according to its values.
• They both used to sort an associative array in PHP.
Example of asort():
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
<?php
$age = array("Peter"=>"37", "Ben"=>"27", "Joe"=>"43");
asort($age);
?>
Example of ksort():
<?php
$age = array("Peter"=>"37", "Ben"=>"27", "Joe"=>"43");
ksort($age);
?>
Output: Key=Ben, Value=37
Key=Joe, Value=43
Key=Peter, Value=35
It is clear from the name SHA256 that the length is of 256 bits long. If you are using
hexadecimal representation, then you require 64 digits to replace 256 bits, as one
digit represents four bits. Or if you are using a binary representation which means
one byte equals to eight bits, then you need 32 digits.
MIME stands for Multipurpose Internet Mail Extensions is an extension of the email
protocol. It supports exchanging of various data files such as audio, video,
application programs, and many others on the internet. It can also handle ASCII
texts and Simple Mail Transport Protocol on the internet.
An access specifier is a code element that is used to determine which part of the
program is allowed to access a particular variable or other information. Different
programming languages have different syntax to declare access specifiers. There
are three types of access specifiers in PHP which are:
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
The explode() and split() functions are used in PHP to split the strings. Both are
defined here:
Example of split():
Output: Array ([0] => this,[1] => is,[2] => a,[3] => split)
Example of explode():
explode ("take", "take a explode example "); //returns an array which have value "a
explode example"
It is easy and simple to execute PHP scripts from the windows command prompt.
You just follow the below steps:
2. In the Command Prompt, write the full path to the PHP executable(php.exe) which
is followed by the full path of a script that you want to execute. You must add space
in between each component. It means to navigate the command to your script
location.
For example,
let you have placed PHP in C:\PHP, and your script is in C:\PHP\sample-php-script.php,
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
C:\PHP\php.exe C:\PHP\sample-php-script.php
3. Press the enter key and your script will execute.
You can use a .htaccess file to block the direct access of directory in PHP. It would
be best if you add all the files in one directory, to which you want to deny access.
These are the commonly used regular expressions in PHP. These are an inbuilt
function that is used to work with other regular functions.
preg-Match: This is the function used to match a pattern in a defined string. If the
patterns match with string, it returns true otherwise it returns false.
The mail function is used in PHP to send emails directly from script or website. It
takes five parameters as an argument.
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
PHP count function is used to get the length or numbers of elements in an array
<?php
// initializing an array in PHP
$array=['a','b','c'];
// Outputs 3
echo count($array);
?>
Zend Engine is used by PHP. The current stable version of Zend Engine is 3.0. It is
developed by Andi Gutmans and Zeev Suraski at Technion – Israel Institute of
Technology.
47. What is the difference between runtime exception and compile time
exception?
You can open a file download dialog in PHP by setting Content-Disposition in the
header.
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
function getTrueIpAddr(){
if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}
51. How will you calculate days between two dates in PHP?
<?Php
$date1 = date('Y-m-d');
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
$date2 = '2015-10-2';
$days = (strtotime($date1)-strtotime($date2))/(60*60*24);
echo $days;
?>
Sample Usage:
function foo() {
return func_get_args();
}
echo foo(1,5,7,3);//output 4;
echo foo(a,b);//output 2;
echo foo();//output 0;
$url='https://www.onlineinterviewquestions.com/get_details';
$jsonData='{"name":"phpScots",
"email":"phpscots@onlineinterviewquestions.com"
,'age':36
}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_close($ch);
In PHP == is equal operator and returns TRUE if $a is equal to $b after type juggling
and === is Identical operator and return TRUE if $a is equal to $b, and they are of
the same data type.
Example Usages:
<?php
$a=true ;
$b=1;
// Below condition returns true and prints a and b are equal
if($a==$b){
echo "a and b are equal";
}else{
echo "a and b are not equal";
}
//Below condition returns false and prints a and b are not equal because $a and $b are of
different data types.
if($a===$b){
echo "a and b are equal";
}else{
echo "a and b are not equal";
}
?>
Example usage:
<?php
// Starting session
session_start();
// Use of session_register() is deprecated
$username = "PhpScots";
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
session_register("username");
// Use of $_SESSION is preferred
$_SESSION["username"] = "PhpScots";
?>
As HTTP is a stateless protocol. To maintain states on the server and share data
across multiple pages PHP session are used. PHP sessions are the simple way to
store data for individual users/client against a unique session ID. Session IDs are
normally sent to the browser via session cookies and the ID is used to retrieve
existing session data, if session id is not present on server PHP creates a new
session, and generate a new session ID.
Example Usage:-
<?php
// starting a session
session_start();
// Creating a session
// checking session
if (isset($_SESSION['user_info']))
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
{
echo "logged In";
}
unset($_SESSION['user_info']['first_name']);
session_destroy();
?>
if($_FILES['photo']['name'])
{
//if no errors...
if(!$_FILES['file']['error'])
{
//now is the time to modify the future file name and validate the file
$new_file_name = strtolower($_FILES['file']['tmp_name']); //rename file
if($_FILES['file']['size'] > (1024000)) //can't be larger than 1 MB
{
$valid_file = false;
$message = 'Oops! Your file\'s size is to large.';
}
{
//move it to where we want it to be
move_uploaded_file($_FILES['file']['tmp_name'],
'uploads/'.$new_file_name);
$message = 'File uploaded successfully.';
}
}
//if there is an error...
else
{
//set that to be the returned message
$message = 'Something got wrong while uploading file:
'.$_FILES['file']['error'];
}
}
In PHP both functions are used to find the first occurrence of substring in a string
except
stristr() is case-insensitive and strstr is case-sensitive,if no match is found then
FALSE will be returned.
Sample Usage:
<?php
$email = ‘abc@xyz.com’;
$hostname = strstr($email, ‘@’);
echo $hostname;
output: @xyz.com
stristr() does the same thing in Case-insensitive manner
?>
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
PHP constructor and a destructor are special type functions which are automatically
called when a PHP class object is created and destroyed.
Generally Constructor are used to intializes the private variables for class and
Destructors to free the resources created /used by class .
<?php
class Foo {
private $name;
private $link;
PECL is an online directory or repository for all known PHP extensions. It also
provides hosting facilities for downloading and development of PHP extensions.
<?php
header("Content-type: image/png");
$string = $_GET['text'];
$im = imagecreatefrompng("images/button1.png");
$mongo = imagecolorallocate($im, 220, 210, 60);
$px = (imagesx($im) - 7.5 * strlen($string)) / 2;
imagestring($im, 3, $px, 9, $string, $mongo);
imagepng($im);
imagedestroy($im);
?>
define('CONSTANT_NAME',value);
Mbstring
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
65. How to get number of days between two given dates using PHP ?
<?php
$tomorrow = mktime(0, 0, 0, date(“m”) , date(“d”)+1, date(“Y”));
$lastmonth = mktime(0, 0, 0, date(“m”)-1, date(“d”), date(“Y”));
echo ($tomorrow-$lastmonth)/86400;
?>
66. What are the differences between GET and POST methods in form
submitting, give the case where we can use get and we can use post
methods?
In PHP, one can specify two different submission methods for a form. The method is
specified inside a FORM element, using the METHOD attribute. The difference
between METHOD=”GET” (the default) and METHOD=”POST” is primarily defined in
terms of form data encoding. According to the technical HTML specifications, GET
means that form data is to be encoded (by a browser) into a URL while POST means
that the form data is to appear within the message body of the HTTP request.
Get Post
History: Parameters remain in browser history Parameters are not saved in
because they are part of the URL browser history.
Bookmarked: Can be bookmarked. Can not be bookmarked.
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Get Post
BACK button/re- GET requests are re-executed but The browser usually alerts the
submit may not be re-submitted to the user that data will need to be
behavior: server if the HTML is stored in re-submitted.
the browser cache.
Encoding type application/x-www-form-urlencoded multipart/form-data or
(enctype application/x-www-form-
attribute): urlencoded Use multipart
encoding for binary data.
Parameters: can send but the parameter data is Can send parameters,
limited to what we can stuff into the including uploading files, to
request line (URL). Safest to use less the server.
than 2K of parameters, some servers
handle up to 64K
Hacked: Easier to hack for script kiddies More difficult to hack
Restrictions on Yes, only ASCII characters allowed. No restrictions. Binary data is
form data type: also allowed.
Security: GET is less secure compared to POST POST is a little safer than GET
because data sent is part of the URL. because the parameters are
So it’s saved in browser history and not stored in browser history
server logs in plaintext. or in web server logs.
Restrictions on Yes, since form data is in the URL and No restrictions
form data URL length is restricted. A safe URL
length: length limit is often 2048 characters
but varies by browser and web
server.
Usability: GET method should not be used when POST method used when
sending passwords or other sensitive sending passwords or other
information. sensitive information.
Visibility: GET method is visible to everyone (it POST method variables are not
will be displayed in the browsers displayed in the URL.
address bar) and has limits on the
amount of information to send.
Cached: Can be cached Not Cached
Large variable 7607 characters maximum size. 8 Mb max size for the POST
values: method.
In PHP all functions starting with __ names are magical functions/methods. Magical
methods always lives in a PHP class.The definition of magical function are defined
by programmer itself.
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
A database provides more flexibility and reliability than does logging to a file. It is
easy to run queries on databases and generate statistics than it is for flat files.
Writing to a file has more overhead and will cause your code to block or fail in the
event that a file is unavailable. Inconsistencies caused by slow replication in AFS
may also pose a problem to errors logged to files. If you have access to MySQL, use
a database for logs, and when the database is unreachable, have your script
automatically send an e-mail to the site administrator.
PHP is a server side scripting language for creating dynamic web pages. There are
so many functions available for displaying output in PHP. Here, I will explain some
basic functions for displaying output in PHP. The basic functions for displaying
output in PHP are as follows:
• print() Function
• echo() Function
• printf() Function
• sprintf() Function
• Var_dump() Function
• print_r() Function
You can access standard error stream in PHP by using following code snippet:
$stderr = fwrite("php://stderr");
$stderr = STDERR;
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
The web pages can be designed using HTML and the execution of the code is done
on the user’s browser.
And, with PHP server-side scripting language, the code is executed on the server
before being executed on the web browser of the user.
• Command line scripting In this area of web development, with just the use
of PHP parser, the PHP script is executed with no requirement of any server
program or browser. This type of use of the PHP script is normally employed
for simple and easy processing tasks.
• Server-side scripting Server-side scripting is the main area of operation of
PHP scripts in PHP. The following are involved in Server-side scripting:
o Web server – It is a program that executes the files from web pages,
from user requests.
o Web browser – It is an application that is used to display the content on
WWW (World Wide Web).
o PHP parser – It is a program that converts the human-readable code
into a format that is easier to understand by the computer.
• Desktop Application Development PHP is also used to create the client-
side application such as desktop applications. They are usually characterized
by the GUI (Graphic User Interface). The client-side applications can be
developed with knowledge of using the advanced features like PHP-GTK.
Advantages of PHP
Now, let's have a quick look at why PHP is used; that is the advantages of PHP.
• Open Source
PHP is an open source software, which means that it is freely available for
modifications and redistribution, unlike any other programming language.
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
There is also an active team of PHP developers who are ready to provide any
kind of technical support when needed.
• Cross Platform
The PHP programming language is easy to use and modify and is also highly
compatible with the leading operating systems as well as the web browsers.
And, that made the deployment of the applications across a wide range of
operating systems and browsers much easier than before.
PHP not only supports the platforms like Linux, Windows, Mac OS, Solaris but
is also applied to web servers like Apache, IIS and many others.
• Suits Web Development
PHP programming language perfectly suits the web development and can be
directly embedded into the HTML code.
echo in PHP
Print in PHP
The default max execution time for PHP scripts is set to 30 seconds. If a php script
runs longer than 30 seconds then PHP stops the script and reports an error.
You can increase the execution time by changing max_execution_time directive in
your php.ini file or calling ini_set(‘max_execution_time’, 300); //300 seconds = 5
minutes function at the top of your php script.
4 scalar types:
• integer
• boolean
• float
• string
3 compound types:
• array
• object
• callable
• resource
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
• NULL
Include :-Include is used to include files more than once in single PHP script.You
can include a file as many times you want.
Syntax:- include(“file_name.php”);
Include Once:-Include once include a file only one time in php script.Second
attempt to include is ignored.
Syntax:- include_once(“file_name.php”);
Require:-Require is also used to include files more than once in single PHP
script.Require generates a Fatal error and halts the script execution,if file is not
found on specified location or path.You can require a file as many time you want in a
single script.
Syntax:- require(“file_name.php”);
Require Once :-Require once include a file only one time in php script.Second
attempt to include is ignored. Require Once also generates a Fatal error and halts
the script execution ,if file is not found on specified location or path.
Syntax:- require_once(“file_name.php”);
PHP sessions are stored on server generally in text files in a temp directory of
server.
That file is not accessible from outside word. When we create a session PHP create
a unique session id that is shared by client by creating cookie on clients
browser.That session id is sent by client browser to server each time when a request
is made and session is identified.
The default session name is “PHPSESSID”.
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
PHP is a loosely typed language , we didn’t have to tell PHP which kind of Datatype
a Variable is. PHP automatically converts the variable to the correct datatype ,
depending on its value.
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
• Numbers
• String
• List
• Tuple
• Dictionary
What is the output of print str if str = 'Hello World!'?
It will print complete string. Output would be Hello World!.
What is the output of print str[0] if str = 'Hello World!'?
It will print first character of the string. Output would be H.
What is the output of print str[2:5] if str = 'Hello World!'?
It will print characters starting from 3rd to 5th. Output would be llo.
What is the output of print str[2:] if str = 'Hello World!'?
It will print characters starting from 3rd character. Output would be llo World!.
What is the output of print str * 2 if str = 'Hello World!'?
It will print string two times. Output would be Hello World!Hello World!.
What is the output of print str + "TEST" if str = 'Hello World!'?
It will print concatenated string. Output would be Hello World!TEST.
What is the output of print list if list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]?
It will print complete list. Output would be ['abcd', 786, 2.23, 'john', 70.200000000000003].
What is the output of print list[0] if list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]?
It will print first element of the list. Output would be abcd.
What is the output of print list[1:3] if list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]?
It will print elements starting from 2nd till 3rd. Output would be [786, 2.23].
What is the output of print list[2:] if list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]?
It will print elements starting from 3rd element. Output would be [2.23, 'john',
70.200000000000003].
What is the output of print tinylist * 2 if tinylist = [123, 'john']?
It will print list two times. Output would be [123, 'john', 123, 'john'].
What is the output of print list1 + list2, if list1 = [ 'abcd', 786 , 2.23, 'john', 70.2 ] and ist2 =
[123, 'john']?
It will print concatenated lists. Output would be ['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
What are tuples in Python?
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
A tuple is another sequence data type that is similar to the list. A tuple consists of a number
of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.
What is the difference between tuples and lists in Python?
The main differences between lists and tuples are − Lists are enclosed in brackets ( [ ] ) and
their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and
cannot be updated. Tuples can be thought of as read-only lists.
What is the output of print tuple if tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )?
It will print complete tuple. Output would be ('abcd', 786, 2.23, 'john', 70.200000000000003).
What is the output of print tuple[0] if tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )?
It will print first element of the tuple. Output would be abcd.
What is the output of print tuple[1:3] if tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )?
It will print elements starting from 2nd till 3rd. Output would be (786, 2.23).
What is the output of print tuple[2:] if tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )?
It will print elements starting from 3rd element. Output would be (2.23, 'john',
70.200000000000003).
What is the output of print tinytuple * 2 if tinytuple = (123, 'john')?
It will print tuple two times. Output would be (123, 'john', 123, 'john').
What is the output of print tuple + tinytuple if tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) and
tinytuple = (123, 'john')?
It will print concatenated tuples. Output would be ('abcd', 786, 2.23, 'john',
70.200000000000003, 123, 'john').
What are Python's dictionaries?
Python's dictionaries are kind of hash table type. They work like associative arrays or hashes
found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type,
but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python
object.
How will you create a dictionary in python?
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using
square braces ([]).
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
How will you get all the keys from the dictionary?
Using dictionary.keys() function, we can get all the keys from the dictionary object.
print dict.keys() # Prints all the keys
How will you get all the values from the dictionary?
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Using dictionary.values() function, we can get all the values from the dictionary object.
print dict.values() # Prints all the values
How will you convert a string to an int in python?
int(x [,base]) - Converts x to an integer. base specifies the base if x is a string.
How will you convert a string to a long in python?
long(x [,base] ) - Converts x to a long integer. base specifies the base if x is a string.
How will you convert a string to a float in python?
float(x) − Converts x to a floating-point number.
How will you convert a object to a string in python?
str(x) − Converts object x to a string representation.
How will you convert a object to a regular expression in python?
repr(x) − Converts object x to an expression string.
How will you convert a String to an object in python?
eval(str) − Evaluates a string and returns an object.
How will you convert a string to a tuple in python?
tuple(s) − Converts s to a tuple.
How will you convert a string to a list in python?
list(s) − Converts s to a list.
How will you convert a string to a set in python?
set(s) − Converts s to a set.
How will you create a dictionary using tuples in python?
dict(d) − Creates a dictionary. d must be a sequence of (key,value) tuples.
How will you convert a string to a frozen set in python?
frozenset(s) − Converts s to a frozen set.
How will you convert an integer to a character in python?
chr(x) − Converts an integer to a character.
How will you convert an integer to an unicode character in python?
unichr(x) − Converts an integer to a Unicode character.
How will you convert a single character to its integer value in python?
ord(x) − Converts a single character to its integer value.
How will you convert an integer to hexadecimal string in python?
hex(x) − Converts an integer to a hexadecimal string.
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
How will you get the min alphabetical character from the string?
min(str) − Returns the min alphabetical character from the string str.
How will you replaces all occurrences of old substring in string with new string?
replace(old, new [, max]) − Replaces all occurrences of old in string with new or at most max
occurrences if max given.
How will you remove all leading and trailing whitespace in string?
strip([chars]) − Performs both lstrip() and rstrip() on string.
How will you change case for all letters in string?
swapcase() − Inverts case for all letters in string.
How will you get titlecased version of string?
title() − Returns "titlecased" version of string, that is, all words begin with uppercase and the
rest are lowercase.
How will you convert a string to all uppercase?
upper() − Converts all lowercase letters in string to uppercase.
How will you check in a string that all characters are decimal?
isdecimal() − Returns true if a unicode string contains only decimal characters and false
otherwise.
What is the difference between del() and remove() methods of list?
To remove a list element, you can use either the del statement if you know exactly which
element(s) you are deleting or the remove() method if you do not know.
What is the output of len([1, 2, 3])?
3.
What is the output of [1, 2, 3] + [4, 5, 6]?
[1, 2, 3, 4, 5, 6]
What is the output of ['Hi!'] * 4?
['Hi!', 'Hi!', 'Hi!', 'Hi!']
What is the output of 3 in [1, 2, 3]?
True
What is the output of for x in [1, 2, 3]: print x?
1
2
3
What is the output of L[2] if L = [1,2,3]?
3, Offsets start at zero.
What is the output of L[-2] if L = [1,2,3]?
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
1. Print Function Print command can be used Python 3 needs parentheses to print
without parentheses. any string. It will raise error without
parentheses.
2. Unicode ASCII str() types and separate Unicode (utf-8) and it has two byte
Unicode() but there is no byte classes −
type code in Python 2.
• Byte
• Bytearray S.
3. Exceptions
Python 2 accepts both new Python 3 raises a SyntaxError in turn
and old notations of syntax. when we don’t enclose the exception
argument in parentheses.
No
Is String in Python are immutable? (Yes/No)
Yes.
Can True = False be possible in Python?
No.
Which module of python is used to apply the methods related to OS.?
OS.
When does a new block begin in python?
A block begins when the line is intended by 4 spaces.
Write a function in python which detects whether the given two strings are anagrams or
not.
def check(a,b):
if(len(a)!=len(b)):
return False
else:
if(sorted(list(a)) == sorted(list(b))):
return True
else:
return False
Name the python Library used for Machine learning.
Scikit-learn python Library used for Machine learning
What does pass operation do?
Pass indicates that nothing is to be done i.e. it signifies a no operation.
Name the tools which python uses to find bugs (if any).
Pylint and pychecker.
Write a function to give the sum of all the numbers in list?
Sample list − (100, 200, 300, 400, 0, 500)
Expected output − 1500
Program for sum of all the numbers in list is −
def sum(numbers):
total = 0
for num in numbers:
total+=num
print(''Sum of the numbers: '', total)
sum((100, 200, 300, 400, 0, 500))
We define a function ‘sum’ with numbers as parameter. The in for loop we store the sum of
all the values of list.
Write a program in Python to reverse a string without using inbuilt function reverse string?
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
print(string_reverse('1tniop'))
First we declare a variable to store the reverse string. Then using while loop and indexing of
string (index is calculated by string length) we reverse the string. While loop starts when index
is greater than zero. Index is reduced to value 1 each time. When index reaches zero we obtain
the reverse of string.
Write a program to test whether the number is in the defined range or not?
Program is −
def test_range(num):
if num in range(0, 101):
print(''%s is in range''%str(num))
else:
print(''%s is not in range''%str(num))
Output −
test_range(101)
101 is not in the range
To test any number in a particular range we make use of the method ‘if..in’ and else condition.
Write a program to calculate number of upper case letters and number of lower case
letters?
Test on String: ''Tutorials POINT''
Program is −
def string_test(s):
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Output −
string_test(''Tutorials POINT'')
String in testing is: Tutorials POINT
Number of Lower Case characters in String: 8
Number of Upper Case characters in String: 6
We make use of the methods .islower() and .isupper(). We initialise the count for lower and
upper. Using if and else condition we calculate total number of lower and upper case
characters.
What is Next?
Further you can go through your past assignments you have done with the subject
and make sure you are able to speak confidently on them. If you are fresher then
interviewer does not expect you will answer very complex questions, rather you have
to make your basics concepts very strong.
Second it really doesn't matter much if you could not answer few questions but it
matters that whatever you answered, you must have answered with confidence. So
just feel confident during your interview. We at tutorialspoint wish you best luck to
have a good interviewer and all the very best for your future endeavor. Cheers :-)
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Question 1:
Question: Reverse the String “ “the fox jumps over the lazy dog”
Answer:
a = "the fox jumps over the lazy dog"
a[::-1]
Assessment:
Question 2:
Question: identity all words that are palindromes in the following sentence
“Lol, this is a gag, I didn’t laugh so much in a long time”
Answer:
def isPalindrome(word: str) -> bool:
if(word == word[::-1]):
return True
return Falsedef getPalindromesFromStr(inputStr: str) -> list:
cleanStr = inputStr.replace(",","").lower()
words = set(cleanStr.split(" "))
wPalindromes = [
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Assessment:
• Does the candidate know the basic or word processing in python such as
replace / split / lower?
FizzBuzz
FizzBuzz is a traditional programming screening question, that allows to
test if a candidate can think through a problem that is not a simple if else
statement. The approach that they take can also shed some light to their
understanding of the language.
Question: Write a program that prints the number for 1 to 50, for number
multiple of 2 print fizz instead of a number, for numbers multiple of 3 print
buzz, for numbers which are multiple of both 2 and 3 fizzbuzz.
Answer:
def fizzbuzzfn(num) -> str:
mod_2 = (num % 2 == 0)
mod_3 = (num % 3 == 0)
if (mod_2 or mod_3):
return (mod_2 * 'Fizz') + (mod_3 * 'Buzz')
return str(num)print('\n'.join([fizzbuzzfn(x) for x in range(1,51)]))
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Assessment:
• Do they know the modulo operator and are able to apply it?
• Are they storing the result of the modulo operators in variables for re-
use?
Question 1
Question: Given a string find the first duplicate word, example string: “this
is just a wonder, wonder why do I have this in mind”
Answer:
string = "this is just a wonder, wonder why do I have this in mind"def firstduplicate(string:
str) -> str:
import re
cleanStr = re.sub("[^a-zA-Z -]", "", string)
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
seen_words.add(word)
return Nonefirstduplicate(string)
Assessment:
Question 2:
Question: What if we wanted to find the first word with more than 2
duplicates in a string?
Answer:
string = "this is just a wonder, wonder why do I have this in mind. This is all that
matters."def first2timesduplicate(string: str) -> str:
import re
cleanStr = re.sub("[^a-zA-Z -]", "", string)
Assessment:
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Question 1:
Question: Replicate the sum for any number of variables, eg
sum(1,2,3,4,5..)
Answer
def sum(*args):
val = 0
for arg in args:
val += arg
return val
Assessment:
Question 2:
Questions around the Fibonacci series is a classic of programming
interviews and candidates should in general be at least familiar with them.
They allow to test recursive thinking.
Write a function that gives the sum of all fibonacci numbers from 0 to n.
Answer:
def fibonacci(n: int) -> int:
# fib series don't exist < 0
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Assessment:
Wrap up
These questions are just meant to be a first screener for data-scientist and
should be combined with statistical and data manipulation types of
questions. They are meant to give a quick glimpse on whether a candidate
has the basic minimum knowledge to go through a full interview rounds.
More advanced programming questions for Python would tend to cover the
use of generators, decorators, cython or the efficient use of libraries such as
pandas/numpy.
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS
Join the telegram channel: https://t.me/ajPlacementMaterials
Buy data structure book90+ chapters covering Stack, Queue, Graph, Trees, Dynamic
Programming useful to clear interview : https://imojo.in/ajGuideAlgoDS