String

String

String variables are enclosed with quotes.
Python uses single quotes ” double quotes “” and triple quotes “””

Program illustration on String :
firstName = ‘Asish’
lastName = “Samantaray”
app = “””Python Tutorial”””
print firstName
print lastName
print app
Copy
Note: Copy and Paste Code into Compiler
Open Compiler 

Strings can be used as a whole string, or a part of the variable using brackets [].

Updating Strings :
We can update an existing string by reassigning a variable to another string.Program Illustration :
var = ‘Java’
print(var)
var = ‘Python’  # Reassigning the variable var..
print(var)
Copy
Note: Copy and Paste Code into Compiler
Open Compiler

Escape Characters :
Backslash notation Description
\a Bell or alert
\b Backspace
\cx Control-x
\C-x Control-x
\e Escape
\f Formfeed
\M-\C-x Meta-Control-x
\n Newline
\nnn Octal notation, where n is in the range 0.7
\r Carriage return
\s Space
\t Tab
\ Vertical tab
\x Character x
\xnn Hexadecimal notation, where n is in the range 0.9, a.f, or A.F
Formatting Operator :
%c character
%s string conversion via str
%i decimal integer
%d decimal integerBell
%u unsigned decimal integer
%o octal integer
%x hexadecimal int(lowercase letters)
%X hexadecimal int(UPPERcase letters)
%e exponential notation (with lowercase )
%E exponential notation (with UPPERcase )
%f floating point real number
%g the shorter of %f and %e
%G the shorter of %f and %E
Special Operators :
Assume string variable X holds ‘Tech’ and variable Y holds ‘pro’, then −

Operator Description Example
+ Concatenation – Adds values X + Y will give Techpro
* Repetition – Creates new strings X*2 will give -TechproTechpro
[] Slice – Gives the character from the given index X[1] will give T
[ : ] Range Slice – Gives the characters from the given range X[1:4] will give Thh
in Membership – Returns true if a character exists in the given string T in a will give 1
not in Membership – Returns true if a character does not exist in the given string Z not in a will give 1

PreviousNext

Basic String Operations

Basic String Operations

Strings are bits of text. They can be defined as anything between quotes:
astring = “Hello world!”
astring2 = ‘Hello world!’

Below code will prints out 12, because “Hello world!” is 12 characters long, including punctuation and spaces.
astring = “Hello world!”
print len(astring)
Copy
Note: Copy and Paste Code into Compiler
Open Compiler 

Below code will prints out 4, because the location of the first occurrence of the letter “o” is 4 characters away from the first character. Notice how there are actually two o’s in the phrase – this method only recognizes the first.
astring = “Hello world!”
print astring.index(“o”)
Copy
Note: Copy and Paste Code into Compiler
Open Compiler 

These make a new string with all letters converted to uppercase and lowercase, respectively.
astring = “Hello world!”
print astring.upper()
print astring.lower()
Copy
Note: Copy and Paste Code into Compiler
Open Compiler

PreviousNext

Conditions

Conditions

Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
For Example:
x = 2
print x == 2 # prints out True
print x == 3 # prints out False
print x < 3  # prints out True
Copy
Note: Copy and Paste Code into Compiler
Open Compiler 

Boolean Operators

The “and” and “or” boolean operators allow building complex boolean expressions,
For Example:
name = “John”
age = 23
if name == “John” and age == 23:
    print “Your name is John, and you are also 23 years old.”

if name == “John” or name == “Rick”:
    print “Your name is either John or Rick.”
Copy
Note: Copy and Paste Code into Compiler
Open Compiler 

True or False
Unfortunately it is not as easy in real life as it is in Python to differentiate between true and false: The following objects are evaluated by Python as False:

numerical zero values (0, 0L, 0.0, 0.0+0.0j),
the Boolean value False,
empty strings,
empty lists and empty tuples,
empty dictionaries.
plus the special value None.

All other values are considered to be True.

“In” Operator

The “in” operator could be used to check if a specified object exists within an iterable object container, such as a list:

name = “Rick”
if name in [“John”, “Rick”]:
    print “Your name is either John or Rick.”

Copy
Note: Copy and Paste Code into Compiler
Open Compiler 

Python uses indentation to define code blocks, instead of brackets. The standard Python indentation is 4 spaces, although tabs and any other space size will work, as long as it is consistent. Notice that code blocks do not need any termination.

Here is an example for using Python’s “if” statement using code blocks:

if (statement is true):
  (do something)
   ….
   ….
elif (another statement is true): # else if
  (do something else)
   ….
   ….
else:
  (do another thing)
   ….
   ….
     

     
PreviousNext

Loops

There are two types of loops in Python, for and while.
“For” Loop

For loops iterate over a given sequence. Here is an example:
primes = [2, 3, 5, 7]
for prime in primes:
        print prime
Copy
Note: Copy and Paste Code into Compiler
Open Compiler 

The range() Function
The built-in function range() is the right function to iterate over a sequence of numbers. It generates lists of arithmetic progressions:
Example:

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

range(n) generates the progression of integer numbers starting with 0 and ending with (n -1)
range() can also be called with two arguments:

range(begin,end)

The above call produces the list of numbers starting with begin (inclusive) and ending with one less than the number “end”.
So far the increment of range() has been 1. We can specify a different increment with a third argument. The increment is called the “step”. It can be both negative and positive, but not zero:

range(begin,end, step)

for x in range(5): # or range(5)
    print x
# Prints out 3,4,5
for x in range(3, 6): # or range(3, 6)
    print x

# Prints out 3,5,7
for x in range(3, 8, 2): # or range(3, 8, 2)
    print x
Copy
Note: Copy and Paste Code into Compiler
Open Compiler 

“While” Loops

While loops repeat as long as a certain boolean condition is met.
For example:
count = 0
while count < 5:
    print count
    count += 1  # This is the same as count = count + 1
Copy
Note: Copy and Paste Code into Compiler
Open Compiler 

Similar to the if statement, the while loop of Python has also an optional else part. This is an unfamiliar construct for many programmers of traditional programming languages.
The statements in the else part are executed, when the condition is not fulfilled anymore. Some might ask themselves now, where the possible benefit of this extra branch is. If the statements of the additional else part were placed right after the while loop without an else, they would have been executed anyway, wouldn’t they. We need to understand a new language construct, i.e. the break statement, to obtain a benefit from the additional else branch of the while loop.
The general syntax of a while loop looks like this:

while condition:
  statement_1
  …
  statement_n
else:
  statement_1
  …
  statement_n

“Break” and “Continue”
Break is used to exit a for loop or a while loop, whereas continue is used to skip the current block, and return to the “for” or “while” statement. A few examples:
count = 0
while True:
    print count
    count += 1
    if count >= 5:
        break

# Prints out only odd numbers – 1,3,5,7,9
for x in range(10):
    # Check if x is even
    if x % 2 == 0:
        continue
    print x
Copy
Note: Copy and Paste Code into Compiler
Open Compiler 

Can we use “else” clause for loops?
Unlike languages like C,C++. we can use else for loops. When the loop condition of “for” or “while” statement fails then code part in “else” is executed. If break statement is executed inside for loop then the “else” part is skipped. Note that “else” part is executed even if there is a continue statement.
Here are a few examples:
count=0
while(count<5):
    print count
    count +=1
else:

    print “count value reached %d” %(count)

# Prints out 1,2,3,4
for i in range(1,10):
    if(i%5==0):
          break
    print i
else:<
    print “this is not printed because for loop is terminated because of break but not due to fail in condition”
Copy
Note: Copy and Paste Code into Compiler
Open Compiler

PreviousNext

Lists

Lists

Lists are very similar to arrays. They can contain any type of variable, and they can contain as many variables as you wish. Lists can also be iterated over in a very simple manner.
This section will give you a more deeper insight on lists

Here is an example of how to build a list.

Two common operations are indexing and assigning to an index position. Both of these operations take the same amount of time no matter how large the list becomes. When an operation like this is independent of the size of the list they are O(1)O(1).

Another very common programming task is to grow a list. There are two ways to create a longer list. You can use the append method or the concatenation operator. The append method is O(1)O(1). However, the concatenation operator is O(k)O(k) where kk is the size of the list that is being concatenated. This is important for you to know because it can help you make your own programs more efficient by choosing the right tool for the job.

Let’s look at four different ways we might generate a list of n numbers starting with 0. First we’ll try a for loop and create the list by concatenation, then we’ll use append rather than concatenation. Next, we’ll try creating the list using list comprehension and finally, and perhaps the most obvious way, using the range function wrapped by a call to the list constructor.

       

def test1():
    l = []
    for i in range(1000):
        l = l + [i]

def test2():
    l = []
    for i in range(1000):
        l.append(i)

def test3():
    l = [i for i in range(1000)]

def test4():
    l = list(range(1000))

list=[1,’abc’,2]
         

Copy Note: Copy and Paste Code into Compiler
Open Compiler 

Basic List Operations

Lists respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new list, not a string.

In fact, lists respond to all of the general sequence operations we used on strings in the prior chapter.

Python Expression Results Description
len([1, 2, 3]) 3 Length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
[‘Hi!’] * 4 [‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’] Repetition
3 in [1, 2, 3] True Membership
for x in [1, 2, 3]: print x, 1 2 3 Iteration
Updating Lists

You can update single or multiple elements of lists by giving the slice on the left-hand side of the assignment operator, and you can add to elements in a list with the append() method. For example –

       

list = [‘physics’, ‘chemistry’, 1997, 2000];
print “Value available at index 2 : “
print list[2]
list[2] = 2001;
print “New value available at index 2 : “
print list[2]
         

Copy Note: Copy and Paste Code into Compiler
Open Compiler

Deleting List Elements

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. For example –

list1 = [‘physics’, ‘chemistry’, 1997, 2000];
print list1
del list1[2];
print “After deleting value at index 2 : “
print list1

Copy
Note: Copy and Paste Code into Compiler
Open Compiler 

Indexing, Slicing, and Matrixes

Because lists are sequences, indexing and slicing work the same way for lists as they do for strings.

Assuming following input −

L = [‘spam’, ‘Spam’, ‘SPAM!’]
Python Expression Results Description
L[2] ‘SPAM!’ Offsets start at zero
L[-2] ‘Spam’ Negative: count from the right
L[1:] [‘Spam’, ‘SPAM!’] Slicing fetches sections
Built-in List Functions & Methods

Python includes the following list functions −

Sr.No. Function with Description
1 cmp(list1, list2)
Compares elements of both lists.

2 len(list)
Gives the total length of the list.

3 max(list)
Returns item from the list with max value.

4 min(list)
Returns item from the list with min value.

5 list(seq)
Converts a tuple into list.

PreviousNext

Basic Operators

Basic Operators

This section explains how to use basic operators in Python.
Arithmetic Operators

Just as any other programming languages, the addition, subtraction, multiplication, and division operators can be used with numbers.
Try to predict what the answer will be. Does python follow order of operations?

       
number = 1 + 2 * 3 / 4.0
print number
Copy
Note: Copy and Paste Code into Compiler
Open Compiler 

Another operator available is the modulo (%) operator, which returns the integer remainder of the division. dividend % divisor = remainder.
remainder = 11 % 3
print remainder
Copy
Note: Copy and Paste Code into Compiler
Open Compiler 

Using two multiplication symbols makes a power relationship.
         

squared = 7 ** 2
cubed = 2 ** 3
print squared
print cubed

Copy
Note: Copy and Paste Code into Compiler
Open Compiler 

Using Operators with Strings

Python supports concatenating strings using the addition operator:
helloworld = “hello” + ” ” + “world”
print helloworld
lotsofhellos = “hello” * 10
print lotsofhellos
Copy
Note: Copy and Paste Code into Compiler
Open Compiler 

Operator Description Example
+, – Addition, Subtraction 10 -3
*, % Multiplication, Modulo 27 % 7
Result: 6
/ Division
This operation results in different results for Python 2.x (like floor division) and Python 3.x Python3:
>>> 10  / 3
3.3333333333333335
and in Python 2.x:
>>> 10  / 3
3
// Truncation Division (also known as floordivision or floor division)
The result of this division is the integral part of the result, i.e. the fractional part is truncated, if there is any.
It works both for integers and floating-point numbers, but there is a difference in the type of the results: If both the divident and the divisor are integers, the result will be also an integer. If either the divident or the divisor is a float, the result will be the truncated result as a float.
>>> 10 // 3
3
If at least one of the operands is a float value, we get a truncated float value as the result.
>>> 10.0 // 3
3.0
>>>
A note about efficiency:
The results of int(10 / 3) and 10 // 3 are equal. But the “//” division is more than two times as fast! You can see this here:
In [9]: %%timeit
for x in range(1, 100):
    y = int(100 / x)
   …:
100000 loops, best of 3: 11.1 μs per loop

In [10]: %%timeit
for x in range(1, 100):
    y = 100 // x
   ….:
100000 loops, best of 3: 4.48 μs per loop
+x, -x Unary minus and Unary plus (Algebraic signs) -3
~x Bitwise negation ~3 – 4
Result: -8
** Exponentiation 10 ** 3
Result: 1000
or, and, not Boolean Or, Boolean And, Boolean Not (a or b) and c
in “Element of” 1 in [3, 2, 1]
<, , >=, !=, == The usual comparison operators 2 <= 3
|, &, ^ Bitwise Or, Bitwise And, Bitwise XOR 6 ^ 3
<> Shift Operators 6 << 3

PreviousNext

Dictionaries

Dictionaries

A dictionary is a data type similar to arrays, but works with keys and values instead of indexes. Each value stored in a dictionary can be accessed using a key, which is any type of object (a string, a number, a list, etc.) instead of using its index to address it.

For example, a database of phone numbers could be stored using a dictionary like this:
phonebook = {}
phonebook[“John”] = 938477566
phonebook[“Jack”] = 938377264
phonebook[“Jill”] = 947662781

Alternatively, a dictionary can be initialized with the same values in the following notation:
phonebook = {
    “John” : 9384xxx66,
    “Jack” : 9383xxx64,
    “Jill” : 9476xxx81
        }
Removing a value

To remove a specified index, use either one of the following notations:
del phonebook[“John”]
#OR
phonebook.pop(“John”)
Iterating over dictionaries

Dictionaries can be iterated over, just like a list. However, a dictionary, unlike a list, does not keep the order of the values stored in it. To iterate over key value pairs, use the following syntax:
phonebook = {}

phonebook[“John”] = 9384xxx66
phonebook[“Jack”] = 9383xxx64
phonebook[“Jill”] = 9476xxx81
for name, number in phonebook.iteritems():
    print “Phone number of %s is %d” % (name, number)

           

     
PreviousNext

Classes and Objects

Classes and Objects

Objects are an encapsulation of variables and functions into a single entity. Objects get their variables and functions from classes. Classes are essentially a template to create your objects.
A very basic class would look something like this:
class MyClass:

    variable = “blah”

def function(self):
    print “This is a message inside the class.”

We’ll explain why you have to include that “self” as a parameter a little bit later. First, to assign the above class(template) to an object you would do the following:
myobjectx = MyClass()

Now the variable “myobjectx” holds an object of the class “MyClass” that contains the variable and the function defined within the class called “MyClass”.
Accessing Object Variables

To access the variable inside of the newly created object “myobjectx” you would do the following:
myobjectx.variable

So for instance the below would output the string “blah”:
print myobjectx.variable
Accessing Object Functions

To access a function inside of an object you use notation similar to accessing a variable:
myobjectx.function()

class MyClass:
    variable = “blah”
    def function(self):
        print “This is a message inside the class.”
myobjectx = MyClass()
print myobjectx.variable
myobjectx.function()

     
Copy
Note: Copy and Paste Code into Compiler
Open Compiler

PreviousNext

Modules and Packages

Modules and Packages

Modules in Python are simply Python files with the .py extension, which implement a set of functions. Modules are imported from other modules using the import command.

To import a module, we use the import command. Check out the full list of built-in modules in the Python standard library here.

The first time a module is loaded into a running Python script, it is initialized by executing the code in the module once. If another module in your code imports the same module again, it will not be loaded twice but once only – so local variables inside the module act as a “singleton” – they are initialized only once.

If we want to import the module urllib, which enables us to create read data from URLs, we simply import the module:
# import the library
import urllib
# use it
urllib.urlopen(…)
Exploring built-in modules

Two very important functions come in handy when exploring modules in Python – the dir and help functions.

We can look for which functions are implemented in each module by using the dir function:

>>> import urllib
>>> dir(urllib)
[‘ContentTooShortError’, ‘FancyURLopener’, ‘MAXFTPCACHE’, ‘URLopener’, ‘__all__’, ‘__builtins__’, ‘__doc__’, ‘__file__’, ‘__name__’, ‘__package__’, ‘__version__’, ‘_ftperrors’, ‘_get_proxies’, ‘_get_proxy_settings’, ‘_have_ssl’, ‘_hexdig’, ‘_hextochr’, ‘_hostprog’, ‘_is_unicode’, ‘_localhost’, ‘_noheaders’, ‘_nportprog’, ‘_passwdprog’, ‘_portprog’, ‘_queryprog’, ‘_safe_map’, ‘_safe_quoters’, ‘_tagprog’, ‘_thishost’, ‘_typeprog’, ‘_urlopener’, ‘_userprog’, ‘_valueprog’, ‘addbase’, ‘addclosehook’, ‘addinfo’, ‘addinfourl’, ‘always_safe’, ‘basejoin’, ‘c’, ‘ftpcache’, ‘ftperrors’, ‘ftpwrapper’, ‘getproxies’, ‘getproxies_environment’, ‘getproxies_macosx_sysconf’, ‘i’, ‘localhost’, ‘main’, ‘noheaders’, ‘os’, ‘pathname2url’, ‘proxy_bypass’, ‘proxy_bypass_environment’, ‘proxy_bypass_macosx_sysconf’, ‘quote’, ‘quote_plus’, ‘reporthook’, ‘socket’, ‘splitattr’, ‘splithost’, ‘splitnport’, ‘splitpasswd’, ‘splitport’, ‘splitquery’, ‘splittag’, ‘splittype’, ‘splituser’, ‘splitvalue’, ‘ssl’, ‘string’, ‘sys’, ‘test’, ‘test1’, ‘thishost’, ‘time’, ‘toBytes’, ‘unquote’, ‘unquote_plus’, ‘unwrap’, ‘url2pathname’, ‘urlcleanup’, ‘urlencode’, ‘urlopen’, ‘urlretrieve’]

Writing modules

Writing Python modules is very simple. To create a module of your own, simply create a new .py file with the module name, and then import it using the Python file name (without the .py extension) using the import command.
Writing packages

Packages are namespaces which contain multiple packages and modules themselves. They are simply directories, but with a twist.

Each package in Python is a directory which MUST contain a special file called __init__.py. This file can be empty, and it indicates that the directory it contains is a Python package, so it can be imported the same way a module can be imported.

If we create a directory called foo, which marks the package name, we can then create a module inside that package called bar. We also must not forget to add the __init__.py file inside the foo directory.

To use the module bar, we can import it in two ways:
import foo.bar
#OR
from foo import bar

Previous

interview Questions

interview Questions
1) What is Python? What are the benefits of using Python?

Python is a programming language with objects, modules, threads, exceptions and automatic memory management. The benefits of pythons are that it is simple and easy, portable, extensible, build-in data structure and it is an open source.

2)  What is PEP 8?

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

3) What is pickling and unpickling?

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

4) How Python is interpreted?

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

5) How memory is managed in Python?

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

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

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

7) What are Python decorators?

A Python decorator is a specific change that we make in Python syntax to alter functions easily.

8) What is the difference between list and tuple?

The difference between list and tuple is that list is mutable while tuple is not. Tuple can be hashed for e.g as a key for dictionaries.

9) How are arguments passed by value or by reference?

Everything in Python is an object and all variables hold references to the objects. The references values are according to the functions; as a result you cannot change the value of the references. However, you can change the objects if it is mutable.

10) What is Dict and List comprehensions are?

They are syntax constructions to ease the creation of a Dictionary or List based on existing iterable.

11) What are the built-in type does python provides?

There are mutable and Immutable types of Pythons built in types Mutable built-in types

List
Sets
Dictionaries
Immutable built-in types

Strings
Tuples
Numbers
12) What is namespace in Python?

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

13) What is lambda in Python?

It is a single expression anonymous function often used as inline function.

14) Why lambda forms in python does not have statements?

A lambda form in python does not have statements as it is used to make new function object and then return them at runtime.

15) What is pass in Python?

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

16) In Python what are iterators?

In Python, iterators are used to iterate a group of elements, containers like list.

17) What is unittest in Python?

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

18) In Python what is slicing?

A mechanism to select a range of items from sequence types like list, tuple, strings etc. is known as slicing.

19) What are generators in Python?

The way of implementing iterators are known as generators.  It is a normal function except that it yields expression in the function.

20) What is docstring in Python?

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

21)  How can you copy an object in Python?

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

22) What is negative index in Python?

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

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

In order to convert a number into a string, use the inbuilt function str().  If you want a octal or hexadecimal representation, use the inbuilt function oct() or hex().

24) What is the difference between Xrange and range?

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

25) What is module and package in Python?

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

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

26) Mention what are the rules for local and global variables in Python?

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

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

27) How can you share global variables across modules?

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

28) Explain how can you make a Python Script executable on Unix?

To make a Python Script executable on Unix, you need to do two things,

Script file’s mode must be executable and
the first line must begin with # ( #!/usr/local/bin/python)
29) Explain how to delete a file in Python?

By using a command os.remove (filename) or os.unlink(filename)

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

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

import random

random.random()

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

31) Explain how can you access a module written in Python from C?

You can access a module written in Python from C by following method,

Module =  =PyImport_ImportModule(“<modulename>”);

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

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

33) Mention five benefits of using Python?

Python comprises of a huge standard library for most Internet platforms like Email, HTML, etc.
Python does not require explicit memory management as the interpreter itself allocates the memory to new variables and free them automatically
Provide easy readability due to use of square brackets
Easy-to-learn for beginners
Having the built-in data types saves programming time and effort from declaring variables
34) Mention the use of the split function in Python?

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

35) Explain what is Flask & its benefits?

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

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

36) Mention what is the difference between Django, Pyramid, and Flask?

Flask is a “microframework” primarily build for a small application with simpler requirements.  In flask, you have to use external libraries.  Flask is ready to use.

Pyramid are build for larger applications.  It provides flexibility and lets the developer use the right tools for their project. The developer can choose the database, URL structure, templating style and more. Pyramid is heavy configurable.

Like Pyramid, Django can also used for larger applications.  It includes an ORM.

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

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

Integration with wtforms
Secure form with csrf token
Global csrf protection
Internationalization integration
Recaptcha supporting
File upload that works with Flask Uploads
38) Explain what is the common way for the Flask script to work?

The common way for the flask script to work is

Either it should be the import path for your application
Or the path to a Python file
39) Explain how you can access sessions in Flask?

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

40) Is Flask an MVC model and if yes give an example showing MVC pattern for your application?

Basically, Flask is a minimalistic framework which behaves same as MVC framework. So MVC is a perfect fit for Flask, and the pattern for MVC we will consider for the following example

from flask import Flask

app = Flask(_name_)

@app.route(“/”)

Def hello():

return “Hello World”

app.run(debug = True)

In this code your,

Configuration part will be
from flask import Flask

app = Flask(_name_)

View part will be
@app.route(“/”)

Def hello():

return “Hello World”

While you model or main part will be
app.run(debug = True)

41) Explain database connection in Python Flask?

Flask supports database powered application (RDBS). Such system requires creating a schema, which requires piping the shema.sql file into a sqlite3 command.  So you need to install sqlite3 command in order to create or initiate the database in Flask.

Flask allows to request database in three ways

before_request() : They are called before a request and pass no arguments
after_request() : They are called after a request and pass the response that will be sent to the client
teardown_request(): They are called in situation when exception is raised, and response are not guaranteed. They are called after the response been constructed.  They are not allowed to modify the request, and their values are ignored.
42) You are having multiple Memcache servers running Python, in which one of the memcacher server fails, and it has your data, will it ever try to get key data from that one failed server?

The data in the failed server won’t get removed, but there is a provision for auto-failure, which you can configure for multiple nodes. Fail-over can be triggered during any kind of socket or Memcached server level errors and not during normal client errors like adding an existing key, etc.

43) Explain how you can minimize the Memcached server outages in your Python Development?

•  When one instance fails, several of them goes down, this will put larger load on the database server when lost data is reloaded as client make a request. To avoid this, if your code has been written to minimize cache stampedes then it will leave a minimal impact
•  Another way is to bring up an instance of Memcached on a new machine using the lost machines IP address
•  Code is another option to minimize server outages as it gives you the liberty to change the Memcached server list with minimal work
•  Setting timeout value is another option that some Memcached clients implement for Memcached server outage. When your Memcached server goes down, the client will keep trying to send a request till the time-out limit is reached

44) Explain what is Dogpile effect? How can you prevent this effect?

Dogpile effect is referred to the event when cache expires, and websites are hit by the multiple requests made by the client at the same time. This effect can be prevented by using semaphore lock. In this system when value expires, first process acquires the lock and starts generating new value.

45) Explain how Memcached should not be used in your Python project?

•  Memcached common misuse is to use it as a data store, and not as a cache
•  Never use Memcached as the only source of the information you need to run your application. Data should always be available through another source as well
•  Memcached is just a key or value store and cannot perform query over the data or iterate over the contents to extract information
•  Memcached does not offer any form of security either in encryption or authentication

Credit: JournalDev