Google News
logo
Python Interview Questions
Python is an object-oriented, high level language, interpreted, dynamic and multipurpose programming language. Developed by Guido van Rossum in the early 1990. Python runs on many Unix variants, on the Mac, and on Windows 2000 and later.
Python variables are the most powerful features of a programming language is the ability to manipulate variables. A variable is a name that refers to a value. An  assignment statement creates new variables and gives them values.

Ex :
>>> name = 'Free Time Learning'
>>> x = 120
>>> value = 91.125784037
Python keywords are special reserved words which convey a special meaning to the compiler/interpreter. In Python keywords are case sensitive each keyword have a special meaning and a specific operation. 

Python Keywords :

True, break, finally, is, return, False, continue, for, lambda, try, None, except, in, raise, pass, class, def, from, nonlocal, while, and, del, global, not, with, as,  elif, if, or, assert, else, import, yield.
In Python, we use the hash (#) symbol to start writing a comment. 

Single lined comment :
In case user wants to specify a single line comment, then comment must start with ?#?

Multi lined Comments :
If we have comments that extend multiple lines, one way of doing it is to use hash (#) in the beginning of each line. For example.

#This is
#educational website.
#URL is freetimelearning.com
Python has five standard data types :

Numbers : Python supports both integers and floating point numbers. There’s no type declaration to distinguish them; Python tells them apart by the presence or absence of a decimal point.
String : String is a sequence of characters. Python supports unicode characters. Generally strings are represented by either single or double quotes.
List : List is a versatile data type exclusive in Python. In a sense it is same as array in C/C++. But interesting thing about list in Python is it can simultaneously 

hold different type of data.
Tuple : Tuple is another data type which is a sequence of data similar to list. But it is immutable. That means data in a tuple is write protected. Data in a tuple is  written using parenthesis and commas.
Set : Set is an unordered collection of unique items. Set is defined by values separated by comma inside braces { }. Items in a set are not ordered.
Dictionary : Python Dictionary is an unordered sequence of data of key-value pair form. It is similar to the hash table type. Dictionaries are written within curly braces in the form key:value.
Operators are the constructs which can manipulate the value of operands.Python supports following operators.

Arithmetic Operators
Comparison Operators
Logical Operators
Assignment Operators
Bitwise Operator
Conditional Operators
The datetime classes in Python are categorized into main 5 classes.

date : Manipulate just date ( Month, day, year)
time : Time independent of the day (Hour, minute, second, microsecond)
datetime : Combination of time and date (Month, day, year, hour, second, microsecond)
timedelta : A duration of time used for manipulating dates
tzinfo :  An abstract class for dealing with time zones
Python provides numerous built-in functions that are readily available to us at the Python prompt.

Some of the functions like input() and print() are widely used for standard input and output operations respectively. Let us see the output section first.
A function is a section of program or a block of code that is written once and can be executed whenever required in the program.

There are two types of functions :

Built-In Functions : Functions that are predefined. We have used many predefined functions in Python.
User- Defined : Functions that are created according to the requirements.
isdigit() : Returns true if string contains only digits and false otherwise.
islower() : Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise.
isupper() : Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise.
isnumeric() : Returns true if a unicode string contains only numeric characters and false otherwise.
isspace() : Returns true if string contains only whitespace characters and false otherwise.
range () returns a list whereas xrange () returns an object that acts like an iterator for generating numbers on demand.
Pass in Python signifies a no operation statement indicating that nothing is to be done.
Pylint and Pychecker. Pylint verifies that a module satisfies all the coding standards or not. Pychecker is a static analysis tool that helps find out bugs in the course code.
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.
An anonymous function is known as a lambda function. This function can have any number of parameters but, can have just one statement.
 
Example :
a = lambda x,y : x+y
print(a(5, 6))
Output : 11
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.
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.
map function executes the function given as the first argument on all the elements of the iterable given as the second argument. If the function given takes in more than 1 arguments, then many iterables are given. #Follow the link to know more similar functions.
1 . convert the given file into a list.
2 . reverse the list by using reversed()
Eg :  for line in reversed(list(open(“file-name”,”r”))): 
         print(line)
Yes. Python is Object Oriented Programming language. OOP is the programming paradigm based on classes and instances of those classes called objects. The features of OOP are:
Encapsulation, Data Abstraction, Inheritance, Polymorphism.
A class is a blue print/ template of code /collection of objects that has same set of attributes and behaviour. To create a class use the keyword class followed by class name beginning with an uppercase letter. For example, a person belongs to class called Person class and can have the attributes (say first-name and last-name) and behaviours / methods (say showFullName()). A Person class can be defined as:

Syntax : 
class Person():
#method
def inputName(self,fname,lname): self.fname=fname self.lastname=lastname
#method
def showFullName() (self):
print(self.fname+" "+self.lname)person1 = Person() #object instantiation person1.inputName("Ratan","Tata") #calling a method inputName person1. showFullName() #calling a method showFullName()


Note : whenever you define a method inside a class, the first argument to the method must be self (where self – is a pointer to the class instance).
Both .py and .pyc files holds the byte code. “.pyc” is a compiled version of Python file. This file is automatically generated by Python to improve performance. The .pyc file is having byte code which is platform independent and can be executed on any operating system that supports .pyc format.
An interpreter is a program that reads and executes code. This includes source code, pre-compiled code, and scripts. Common interpreters include Perl, Python, and Ruby interpreters, which execute Perl, Python, and Ruby code respectively
The template is a simple text file.  It can create any text-based format like XML, CSV, HTML, etc.  A template contains variables that get replaced with values when the template is evaluated and tags (% tag %) that controls the logic of the template.
PEP stands for Python Enhancement Proposal. It is a set of rules that specify how to format Python code for maximum readability.
A namespace is a naming system used to make sure that names are unique to avoid naming conflicts.
Global Variables :
Variables declared outside a function or in global space are called global variables. These variables can be accessed by any function in the program.
 
Local Variables :
Any variable declared inside a function is known as a local variable. This variable is present in the local space and not in the global space.
 
Example :
a=2
def add():
b=3
c=a+b
print(c)
add()
Output : 5
 
When you try to access the local variable outside the function add(), it will throw an error.
Type conversion refers to the conversion of one data type iinto another.
 
int() : converts any data type into integer type
 
float() : converts any data type into float type
 
ord() : converts characters into integer
 
hex() : converts integers to hexadecimal
 
oct() : converts integer to octal
 
tuple() : This function is used to convert to a tuple.
 
set() : This function returns the type after converting to set.
 
list() : This function is used to convert any data type to a list type.
 
dict() : This function is used to convert a tuple of order (key,value) into a dictionary.
 
str() : Used to convert integer into a string.
 
complex(real,imag) : This functionconverts real numbers to complex(real,imag) number.
Arrays and lists, in Python, have the same way of storing data. But, arrays can hold only a single data type elements whereas lists can hold any data type elements.
 
Example :
import array as arr
My_Array=arr.array('i',[1,2,3,4])
My_list=[1,'abc',1.20]
print(My_Array)
print(My_list)
 
Output :
array(‘i’, [1, 2, 3, 4]) [1, ‘abc’, 1.2]
The pass keyword represents a null operation in Python. It is generally used for the purpose of filling up empty blocks of code which may execute during runtime but has yet to be written. Without the pass statement in the following code, we may run into some errors during code execution.
 
def myEmptyFunc():
    # do nothing
    pass

myEmptyFunc()    # nothing happens
 
## Without the pass keyword
# File "<stdin>", line 3
# IndentationError: expected an indented block
xrange() and range() are quite similar in terms of functionality. They both generate a sequence of integers, with the only difference that range() returns a Python list, whereas, xrange() returns an xrange object.
 
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

for i in xrange(1,10):    # numbers from 1 to 9
    print i       # output => 1 2 3 4 5 6 7 8 9

for i in xrange(1, 10, 2):    # skip by two for next
    print i       # output => 1 3 5 7 9
 
Note : xrange has been deprecated as of Python 3.x. Now range does exactly the same what xrange used to do in Python 2.x, since it was way better to use xrange() than the original range() function in Python 2.x.
Python library offers a feature - serialization out of the box. Serializing a object refers to transforming it into a format that can be stored, so as to be able to deserialize it later on, to obtain the original object. Here, the pickle module comes into play.
 
Pickling : Pickling is the name of the serialization process in Python. Any object in Python can be serialized into a byte stream and dumped as a file in the memory. The process of pickling is compact but pickle objects can be compressed further. Moreover, pickle keeps track of the objects it has serialized and the serialization is portable across versions.
The function used for the above process is pickle.dump().
 
Unpickling : Unpickling is the complete inverse of pickling. It deserializes the byte stream to recreate the objects stored in the file, and loads the object to memory.
The function used for the above process is pickle.load().
Generators are functions that return an iterable collection of items, one at a time, in a set manner. Generators, in general, are used to create iterators with a different approach. They employ the use of yield keyword rather than return to return a generator object.

Let's try and build a generator for fibonacci numbers :
 
## generate fibonacci numbers upto n
def fib(n):
    p, q = 0, 1
    while(p < n):
        yield p
        p, q = q, p + q

x = fib(10)    # create generator object 
  
## iterating using __next__(), for Python2, use next()
x.__next__()    # output => 0
x.__next__()    # output => 1
x.__next__()    # output => 1
x.__next__()    # output => 2
x.__next__()    # output => 3
x.__next__()    # output => 5
x.__next__()    # output => 8
x.__next__()    # error
  
## iterating using loop
for i in fib(10):
    print(i)    # output => 0 1 1 2 3 5 8
* .py files contain the source code of a program. Whereas, .pyc file contains the bytecode of your program. We get bytecode after compilation of .py file (source code). .pyc files are not created for all the files that you run. It is only created for the files that you import.

* Before executing a python program python interpreter checks for the compiled files. If the file is present, the virtual machine executes it. If not found, it checks for .py file. If found, compiles it to .pyc file and then python virtual machine executes it.

* Having .pyc file saves you the compilation time.
* As the name suggests, ‘slicing’ is taking parts of.
* Syntax for slicing is [start : stop : step]
* start is the starting index from where to slice a list or tuple
* stop is the ending index or where to sop.
* step is the number of steps to jump.
* Default value for start is 0, stop is number of items, step is 1.
* Slicing can be done on strings, arrays, lists, and tuples.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(numbers[1 : : 2])  #output : [2, 4, 6, 8, 10]​
* Negative indexes are the indexes from the end of the list or tuple or string.
* Arr[-1] means last element of array Arr[]

arr = [1, 2, 3, 4, 5, 6]

#get the last element
print(arr[-1]) #output 6

#get the second last element
print(arr[-2]) #output 5​
Python's constructor : _init__ () is the first method of a class. Whenever we try to instantiate an object __init__() is automatically invoked by python to initialize members of an object. We can't overload constructors or methods in Python. It shows an error if we try to overload.
 
class student:  
    def __init__(self,name):  
        self.name = name  
    def __init__(self, name, email):  
        self.name = name  
        self.email = email  
       
# This line will generate an error  
#st = student("chanti")  
  
# This line will call the second constructor  
st = student("chanti", "chanti@gmail.com")  
print(st.name)  
 
Output :  
chanti
It is a string's function which converts all uppercase characters into lowercase and vice versa. It is used to alter the existing case of the string. This method creates a copy of the string which contains all the characters in the swap case. If the string is in lowercase, it generates a small case string and vice versa. It automatically ignores all the non-alphabetic characters. See an example below.
 
string = "IT IS IN LOWERCASE."  
print(string.swapcase())  
  
string = "it is in uppercase."  
print(string.swapcase())  
 
it is in lowercase. 
IT IS IN UPPERCASE.
The join() is defined as a string method which returns a string value. It is concatenated with the elements of an iterable. It provides a flexible way to concatenate the strings. See an example below.
 
str = "Chanti"  
str2 = "ab"  
# Calling function    
str2 = str.join(str2)    
# Displaying result    
print(str2)  
 
Output :
aChantib
In Python 3, the old Unicode type has replaced by "str" type, and the string is treated as Unicode by default. We can make a string in Unicode by using art.title.encode("utf-8") function.
Decorators are very powerful and a useful tool in Python that allows the programmers to modify the behaviour of any class or function. It allows us to wrap another function to extend the behaviour of the wrapped function, without permanently modifying it.
 
# Decorator example  
def decoratorfun():  
    return another_fun  
 
Functions vs. Decorators : A function is a block of code that performs a specific task whereas a decorator is a function that modifies other functions.
The Python dictionary is a built-in data type. It defines a one-to-one relationship between keys and values. Dictionaries contain a pair of keys and their corresponding values. It stores elements in key and value pairs. The keys are unique whereas values can be duplicate. The key accesses the dictionary elements.
 
Keys index dictionaries.
 
Example :
 
The following example contains some keys Country Hero & Cartoon. Their corresponding values are India, Sivaji, and Chanti respectively.
 
>>> dict = {'Country': 'India', 'Hero': 'Sivaji', 'Cartoon': 'Chanti'}  
>>>print dict[Country]  
India  
>>>print dict[Hero]  
Sivaji 
>>>print dict[Cartoon]  
Chanti
Python 2.x is an older version of Python. Python 3.x is newer and latest version. Python 2.x is legacy now. Python 3.x is the present and future of this language.
 
The most visible difference between Python2 and Python3 is in print statement (function). In Python 2, it looks like print "Hello", and in Python 3, it is print ("Hello").
 
String in Python2 is ASCII implicitly, and in Python3 it is Unicode.
 
The xrange() method has removed from Python 3 version. A new keyword as is introduced in Error handling.
The enumerate() function is used to iterate through the sequence and retrieve the index position and its corresponding value at the same time.
 
For i,v in enumerate(['Python','Java','C++']):  
print(i,v)  
0 Python  
1 Java  
2 C++  
# enumerate using an index sequence  
for count, item in enumerate(['Python','Java','C++'], 10):  
Unlike C++, we don’t have ?: in Python, but we have this :
 
[on true] if [expression] else [on false]
 
If the expression is True, the statement under [on true] is executed. Else, that under [on false] is executed.
 
Below is how you would use it :
 
>>> a,b=2,3
>>> min=a if a<b else b
>>> min
Output : 2
 
>>> print("Hi") if a<b else print("Bye")
Output : Hi
A language is case-sensitive if it distinguishes between identifiers like myname and Myname. In other words, it cares about case- lowercase or uppercase. Let’s try this with Python.
 
>>> myname='Ramana'
>>> Myname
Traceback (most recent call last) :
 
File “<pyshell#3>”, line 1, in <module>
 
Myname
 
NameError : name ‘Myname’ is not defined
 
As you can see, this raised a NameError. This means that Python is indeed case-sensitive.
PYTHONSTARTUP : It contains the path of an initialization file having Python source code. It is executed every time we start the interpreter. It is named as .pythonrc.py in Unix, and it contains commands that load utilities or modify PYTHONPATH.

PYTHONCASEOK : It is used in Windows to instruct Python to find the first case-insensitive match in an import statement. We can set this variable with any value to activate it.

PYTHONHOME : It is an alternative module search path. It is usually embedded in PYTHONSTARTUP or PYTHONPATH directories to make switching of module libraries easy.
The map() function in Python has two parameters, function and iterable. The map() function takes a function as an argument and then applies that function to all the elements of an iterable, passed to it as another argument. It returns an object list of results.
 
For example :
def calculateSq(n):
return n*n
numbers = (2, 3, 4, 5)
result = map( calculateSq, numbers)
print(result)
To display the contents of a file in reverse, the following code can be used:
 
for line in reversed(list(open(filename.txt))):
print(line.rstrip())
Equivalent to constructors in OOP terminology, __init__ is a reserved method in Python classes. The __init__ method is called automatically whenever a new object is initiated. This method allocates memory to the new object as soon as it is created. This method can also be used to initialize variables.
Python does follow an object-oriented programming paradigm and has all the basic OOPs concepts such as inheritance, polymorphism, and more, with the exception of access specifiers. Python doesn’t support strong encapsulation (adding a private keyword before data members). Although, it has a convention that can be used for data hiding, i.e., prefixing a data member with two underscores.
Both append() and extend() methods are methods used to add elements at the end of a list.
 
append(element) : Adds the given element at the end of the list that called this append() method

extend(another-list) : Adds the elements of another list at the end of the list that called this extend() method
Flask supports a database-powered application (RDBS). Such a system requires creating a schema, which needs piping the schema.sql file into the sqlite3 command. So, we need to install the sqlite3 command in order to create or initiate the database in Flask.
 
Flask allows to request for a 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 a situation when an exception is raised and responses are not guaranteed. They are called after the response has been constructed. They are not allowed to modify the request, and their values are ignored.
NumPy arrays provide users with three main advantages as shown below :
 
* NumPy arrays consume a lot less memory, thereby making the code more efficient.
* NumPy arrays execute faster and do not add heavy processing to the runtime.
* NumPy has a highly readable syntax, making it easy and convenient for programmers.
Monkey patching is the term used to denote the modifications that are done to a class or a module during the runtime. This can only be done as Python supports changes in the behavior of the program while being executed.
 
The following is an example, denoting monkey patching in Python:
# monkeyy.py 
class X: 
     def func(self): 
          print "func() is being called"
The above module (monkeyy) is used to change the behavior of a function at the runtime as shown below:
import monkeyy 
def monkey_f(self): 
     print "monkey_f() is being called"
# replacing address of “func” with “monkey_f
monkeyy.X.func = monkey_f 
obj = monk.X() 
# calling function “func” whose address got replaced
# with function “monkey_f()
obj.func()
* Python uses private heaps to maintain its memory. So the heap holds all the Python objects and the data structures. This area is only accessible to the Python interpreter; programmers can’t use it.

* And it’s the Python memory manager that handles the Private heap. It does the required allocation of the memory for Python objects.

* Python employs a built-in garbage collector, which salvages all the unused memory and offloads it to the heap space.
Python has a regular expression module “re.”
 
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)$","info@freetimelearning.com"))
In call-by-value, the argument whether an expression or a value gets bound to the respective variable in the function.
 
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.
We use both “call-by-reference” and “pass-by-reference” interchangeably. When we pass an argument by reference, then it is available as an implicit reference to the function, rather than a simple copy. In such a case, any modification to the argument will also be visible to the caller.
 
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 id() is one of the built-in functions in Python.
Signature: id(object)
It accepts one parameter and returns a unique identifier associated with the input object.
Python’s print() function always prints a newline in the end. The print() function accepts an optional parameter known as the ‘end.’ Its value is ‘\n’ by default. We can change the end character in a print statement with the value of our choice using this parameter.
 
# Example: Print a  instead of the new line in the end.
print("Let's learn" , end = ' ')  
print("Python") 

# Printing a dot in the end.
print("Learn to code from freetimelearn" , end = '.')  
print("com", end = ' ')
 
Output :
Let's learn Python
Learn to code from freetimelearn.com
Python provides a break statement to exit from a loop. Whenever the break hits in the code, the control of the program immediately exits from the body of the loop.
 
The break statement in a nested loop causes the control to exit from the inner iterative block.
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.
 
The signature of the rstrip() is :
str.rstrip([char sequence/pre>
#Example
test_str = 'Programming    '
# The trailing whitespaces are excluded
print(test_str.rstrip())
Inheritance is used to specify that one class will get most or all of its features from its parent class. It is a feature of Object Oriented Programming. The new class is called derived (or child) class and the one from which it inherits is called the base (or parent) class.
The child class or derived class inherits the features from the parent class, adding new features to it. It facilitates re-usability of code.
The signature for the list comprehension is as follows :
[ expression(var) for var in iterable ]

For example, the below code will return all the numbers from 10 to 20 and store them in a list.
>>> alist = [var for var in range(10, 20)]
>>> print(alist)
There are two ways to copy objects in Python.
 
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.
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.
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
Built­in dir() function of Python ,on an instance shows the instance variables as
well as the methods and class attributes defined by the instance’s class and all its base classes alphabetically. So by any object as argument to dir() we can find all the methods & attributes of the object’s class
help() and dir() both functions are accessible from the Python interpreter and used for viewing a consolidated dump of built-in functions.
 
Help() function : The help() function is used to display the documentation string and also facilitates you to see the help related to modules, keywords, attributes, etc.

Dir() function : The dir() function is used to display the defined symbols.
Polymorphism means the ability to take multiple forms. So, for instance, if the parent class has a method named ABC then the child class also can have a method with the same name ABC having its own parameters and variables. Python allows polymorphism.
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.speed
Sets are unordered collection objects in Python. They store unique and immutable objects. Python has its implementation derived from mathematics.
The collection type like a list, tuple, dictionary, and set are all iterable objects whereas they are also iterable containers which return an iterator while traversing.
We can delete a key in a dictionary by using the del() method.
 
>>> site_stats = {'site': 'freetimelearning.com', 'traffic': 10000, "type": "organic"}
>>> del site_stats["type"]
>>> print(site_stats)
{'site': 'google.co.in', 'traffic': 1000000}

Another method, we can use is the pop() function. It accepts the key as the parameter. Also, a second parameter, we can pass a default value if the key doesn’t exist.
 
>>> site_stats = {'site': 'freetimelearning.com', 'traffic': 10000, "type": "organic"}
>>> print(site_stats.pop("type", None))
organic
>>> print(site_stats)
{'site': 'freetimelearning.com', 'traffic': 10000}
We can utilize the following single statement as a conditional expression. default_statment if Condition else another_statement
 
>>> no_of_days = 366
>>> is_leap_year = "Yes" if no_of_days == 366 else "No"
>>> print(is_leap_year)
Yes
If class A is a subclass of class B, then everything in B is accessible in /by class A. In addition, class A can define methods that are unavailable in B, and also it is able to override methods in B. For Instance, If class B and class A both contain a method called func(), then func() in class B can override func() in class A. Similarly, a method of class A can call another method defined in A that can invoke a method of B that overrides it.
Import MySQLdb module as : import MySQLdb Establish a connection to the database. db = MySQLdb.connect(“host”=”local host”, “database-user”=”user-name”, “password”=”password”, “database-name”=”database”) Initialize the cursor variable upon the established connection: c1 = db.cursor() Retrieve the information by defining a required query string. s = “Select * from dept” Fetch the data using fetch() methods and print it. data = c1.fetch(s) Close the database connection. db.close()
zip() function : it will take multiple lists say list1, list2, etc and convert them into a single list of tuples by taking their corresponding elements of the lists that are passed as parameters.
 
Example :
list1 = [‘A’, ‘B’,’C’] and list2 = [10,20,30]. zip(list1, list2) # results in a list of tuples say [(‘A’,10),(‘B’,20),(‘C’,30)]
 
whenever the given lists are of different lengths, zip stops generating tuples when the first list ends.
import pandas as pd
import numpy as np
df = pd.DataFrame({‘A’:[3,1,1],’B’:[1,3,2]})
sort = df.sort_values(by = ‘B’)
print(sort)
* In, a heap-max the key at root should be maximum among all the keys present in the heap. The same property must be recursively true for all nodes.

* In a heap-min the key at root should be minimum among all the keys present in the heap. The same property should be recursively true for all nodes.
Python provides modules with functions which enable you to manipulate text and binary files on file system. Based on them you can create files, update the contents, copy, and delete files. The modules are os, shutil.
We need to implement the following steps to install Python on Windows, and they are :
 
First you need to install Python from https://www.python.org/downloads/
After installing Python on your PC, find the place where it is located in your PC using the cmd python command.

Then visit advanced system settings on your PC and add new variable. Name the new variable as PYTHON_NAME then copy the path and paste it.

Search for the path variable and select one of the values for it and click on ‘edit’.
Finally we need to add a semicolon at the end of the value and if the semicolon is not present then type %PYTHON_NAME%.
In simple words, abstraction can be defined as hiding of unnecessary data and showing or executing necessary data. In technical terms, abstraction can be defined as hiding internal process and showing only the functionality. In Python abstraction can be achieved using encapsulation.
Encapsulation is one of the most important aspects of object-oriented programming. Binding or wrapping of code and data together into a single cell is called encapsulation. Encapsulation in Python is mainly used to restrict access to methods and variables.
Empty class in Python is defined as a class that does not contain any code defined within the block. It can be created using pass keyword and object to this class can be created outside the class itself.
 
Example :
class x:
&nbsp; pass
obj=x()
obj.id="123"
print("Id = ",obj.id)
 
Output : 123
There are many IDE’s to execute Python code. But, as a beginner, the following two IDE’s will be helpful 
 
* PyCharm
* Spyder
The different stages of the Life Cycle of a Thread can be stated as follows.
 
Stage 1 : Creating a class where we can override the run method of the Thread class.
Stage 2 : We make a call to start() on the new thread. The thread is taken forward for scheduling purposes.
Stage 3 : Execution takes place wherein the thread starts execution, and it reaches the running state.
Stage 4 : Thread wait until the calls to methods including join() and sleep() takes place. 
Stage 5 : After the waiting or execution of the thread, the waiting thread is sent for scheduling.
Stage 6 : Running thread is done by executing the terminates and reaches the dead state.
# Enter number of terms needed  #0,1,1,2,3,5....
a=int(input("Enter the terms"))
f=0     #first element of series
s=1    #second element of series
if a<=0:
    print("The requested series is
",f)
else:
    print(f,s,end=" ")
    for x in range(2,a):
        next=f+s                           
        print(next,end=" ")
        f=s
        s=next</pre>


Output : Enter the terms 5 0 1 1 2 3

a=input("enter sequence")
b=a[::-1]
if a==b:
    print("palindrome")
else:
    print("Not a Palindrome")
 
Output : enter sequence 323 palindrome
The following code can be used to sort a list in Python:
 
list = ["1", "4", "0", "6", "9"]
list = [int(i) for i in list]
list.sort()
print (list)
Django is an advanced python web framework that supports agile growth and clean pragmatic design, built through experienced developers, this cares much about the trouble of web development, so you can concentrate on writing your app without wanting to reinvent that wheel.
* Excellent documentation
* Python web framework
* SEO optimised
* High scalability
* Versatile in nature
* Offers high security
* Thoroughly tested
* Provides rapid Development
* One of the important advantages of Django is it is a framework of python language which is very simple to learn
* Django is a multifaceted framework
* When it comes to security Django is the best framework
* Scalability is added advantage of Django
Django web framework is operated and also maintained by an autonomous and non-profit organization designated as Django Software Foundation (DSF). The initial foundation goal is to promote, support, and advance this Django Web framework.
There are three possible inheritance styles in Django, and they are:
 
Proxy models : This style is mainly used for those who want to modify the Python level behaviour of the model, without modifying the model’s fields.

Abstract Base Classes : This inheritance style is used only when we want to make parent class hold the data which they don’t want to repeat it again in the child class.

Multi-table Inheritance : This inheritance style is used only when we want to subclass an existing model and there must a database table designed for each model on its own.
Django has described as a loosely coupled framework because concerning the MTV architecture it’s based upon. Django’s architecture means a variant of MVC architecture and also MTV is helpful because this completely separates the server code of the client’s machine.
It is an automatically built file inside each Django project. It is a flat wrapper encompassing the Django-admin.py. It possesses the following usage :
 
It establishes your project's package on sys.path.
It fixes the DJANGO_SETTING_MODULE environment variable to point to your project's setting.py file.
Django-admin.py is a command-line argument which is utilised for administrative tasks.
A session comprises a mechanism to store information on specific server-side at the interaction by the web application. By default, session reserves in the database and allows file-based and cache-based sessions.
A cookie is a piece of information that is stored in a client browser for a specific time. When the specific time is completed cookie gets automatically removed from the client browser.
The two methods to set and get cookie values are
 
Set_cookie : this method is used to set the values of the cookie
Get_cookie : this method is used to get the values of the cookie
This is defined as an occurrence of event when the cache expires and also when the websites are hit with more number of requests by the client at a time. This dogpile effect can be averted by the use of a semaphore lock. If in the particular system the value expires then, first of all, the particular process receives the lock and begin generating new value.
Iterators in Python are basically containers that consist of a countable number of elements. Any object that is an iterator implements two methods which are, the __init__() and the __next__()  methods. When you are making use of iterators in Django, the best situation to do it is when you have to process results that will require a large amount of memory space. To do this, you can make use of the iterator() method which basically evaluates a QuerySet and returns the corresponding iterator over the results.
Ten Python GUI frameworks that are popular in 2023 for building interactive GUIs :

1. PyQt5 : PyQt5 is a popular Python binding for the Qt cross-platform UI and application framework. It is a feature-rich framework that is easy to use and provides an extensive set of widgets and tools for building cross-platform applications with a native look and feel.

2. PySide2 : PySide2 is another popular Python binding for the Qt framework, similar to PyQt5. It provides an easy-to-use API for building cross-platform applications with a native look and feel.

3. Tkinter : Tkinter is a standard Python GUI toolkit that comes with most Python installations. It is simple to use and provides a wide range of widgets and tools for building GUIs, making it an excellent choice for simple and small-scale projects.

4. Kivy : Kivy is a modern, cross-platform, open-source Python framework for creating multi-touch applications. It provides a wide range of widgets and tools for building cross-platform applications, making it an excellent choice for developers who want to build mobile or desktop apps.

5. PyGTK : PyGTK is a Python binding for the GTK+ widget toolkit. It provides an easy-to-use API for building cross-platform applications with a native look and feel.
6. wxPython : wxPython is a Python binding for the wxWidgets C++ GUI framework. It is a popular and easy-to-use framework for building cross-platform desktop applications with a native look and feel.

7. PyGUI : PyGUI is a cross-platform Python GUI toolkit that provides a simple and flexible API for building desktop applications. It is a lightweight and easy-to-use framework for building simple GUIs.

8. Pyforms : Pyforms is a Python framework that provides a simple API for building GUI applications. It provides an extensive set of widgets and tools for building cross-platform applications with a native look and feel.

9. PySimpleGUI : PySimpleGUI is a simple and easy-to-use Python GUI toolkit that provides an intuitive API for building desktop applications. It is an excellent choice for beginners who want to build simple GUIs quickly.

10. PyWebview : PyWebview is a lightweight and easy-to-use Python GUI toolkit that allows developers to build desktop applications with HTML, CSS, and JavaScript. It is an excellent choice for building web-based desktop applications with a native look and feel.