https://www.edureka.co/blog/interview-questions/python-interview-questions/#Whattypeoflanguageispython?
1What kind of language is Python?
* Guido van Rossum began working on Python in the late 1980s as a successor to the ABC programming language and first released it in 1991 as Python 0.9.0.
* Python 2.0 was released in 2000 and introduced new features such as list comprehensions, cycle-detecting garbage collection, reference counting, and Unicode support.
* Python 3.0, released in 2008, was a major revision that is not completely backward-compatible with earlier versions.
* Python 2 was discontinued with version 2.7.18 in 2020
Python is
Python is a high-level, general-purpose programming language. Its code design is readability with the use of significant indentation.
Python is dynamically-typed and garbage-collected. It supports multiple programming paradigms, including structured (particularly procedural), object-oriented and functional programming. It is often described as a "batteries included" language due to its comprehensive standard library
2Is Python an Interpreted Language?
https://www.youtube.com/watch?v=vZu-khdQUqI
Python is Just-In-Time-Compile language, it is slitelly different from Interpreted Language:
In python Compiler convert source code into Intermediate code (called Bitcode just like Java) and this Bitcode serve into different type of Machines (Window, Linux, Mac) but this Bitcode could not run directally. So we have to install Pyhton Virtual Machine(PVM) into the Machine to run bitcode.
PVM is a Just-In-Time-Compiler. Just-In-Time-Compiler read the Bitcode and convert into Machinecode and operatig system excute the Machincode
Just-In-Time-Compiler is faster then Interpreted language.
Note: There are two types of languages
a) Compile Language: Convert source code into Machine Code and store machine code into a file, When the program will run it will excuted to machine code.
b) Interpreted Language: No any machine lavel code not stored in Interpreted. Inerpreted convert source code into Machine code during the run time whenever we excute program.
3How is memory managed in python?
x=5
-Stack Memory: x:422682 Named or Reference variable get memory into Stack Memory
-Private Heap Space: 5:422682 Object get the memory into Heap Space. Private Heap Space can not access directly.Memory are provided by 'Python Memory Manager'
Python manage the Garbage collector and it automatically run when need to Python and release the Garbage block.
4What is the difference between list and tuple?
-
List
- List start by: []
- List is container to contain the difference types of objects and is use to iterate type object
- Syntax: list_1 = [10, ‘Chelsea’, 20]
- Lists are slower than tuples
- Lists consume more memory
- Lists are mutable i.e they can be added,edited,deleted.
- List is a class there lot of function available like (Append,Insert,Clear,Index,Count)
-
TUPLES
- TUPLES start by: ()
- TUPLES is also similer to List but contains immutable objects
- Syntax: tup_1 = (10, ‘Chelsea’ , 20)
- Tuples are faster than list.
- Tuples consume less memory.
- Tuples are immutable (tuples are lists which can’t be edited).
- Tuples has only 'Index and Count' function
4Difference between List Comprehension and Dict Comprehension ?
-
List
- Syntex: [expresion for item in iterable if condition]
- ls =[i for i in range(10)]
-main difference is bracket
-
Dict
- Syntex: {key:value for(key,value) in iterable if condition}
-ds ={n:n for n in range(1,10)}
-main difference is bracket
4Difference between Generator and Iterator?
-
Generator
- Generatores are iterators which can excute only once.
- Generatore uses "yield" keyword
- Generator are mostly used in loops to generato an iterator by rturing all the values in the loop without affecting the iteration of the loop
- Every Generator is an iterator
def sqr(n):
for i in range(1,n+1):
yield i*i
a =sqr(3)
print(next(a))
print(next(a))
print(next(a))
=======Output==
1
4
9
-
Iterator
- An iterator is an object which contains a counatbl number of values and it is used to iterate over iterable objects like list,tupls, sets etc.
- Iterators are used mostly to iterate or convert other ojects to an iterator useng iter() function.
- Iterator uses iter() and next() functions.
- Every iterator is not generator
- iter_list = iter(['A','B','C'])
print(next(iter_list))
print(next(iter_list))
print(next(iter_list))
=======Output==
A
B
C
5Similerty between list and tuple?
Heterogeneous
Indexing
Slicing Operator
Counting
6What is an identity operator?
There are two identity operator in python
1: is : it meas check two reference variable has same object id or not
if x is y:
print('True')
2: is not
7What is monkey patching in Python?
In Python, the term monkey patch only refers to dynamic modifications of a class or module at run-time.
Consider the below example:
class MyClass:
def __ini__(self,x):
self.a =x
def get_data(self):
print("some code fetch data from database")
t1 =MyClass(5)
def new_get_data(self):
print("some code fetch data from test database")
// use monkey patch overrite class function by function
MyClass.get_data = new_get_data
print("After monkey patching")
t1.get_data()
8What is a lambda function?
An anonymous (One Liner) function is known as a lambda function. This function can have any number of parameters but, can have just one statement.
a = lambda x,y : x+y
print(a(5, 6))
9How can you randomize the items of a list in place in Python?
By using the shuffle import from random
from random import shuffle
x = ['Keep', 'The', 'Blue', 'Flag', 'Flying', 'High']
shuffle(x)
print(x)
10What are python iterators?
Python has some iterable types of variable like list,set,tuple,dictionary,string so this type of variable can be iterate (looping) so this is call iterators, single store variable like int, float can't iterate.
iterators is object that point to any iterable object variable element.
mylist =[10,20,30,40,50]
a =iter(mylist)
print(next(a))
11What are decorators in Python?
A Decorator is just a function that takes another function as an argument, and some kind of fucntionality and then returns another function.
All of this without altering the source code of the original function that you passed in.
def decorator_func(func):
def wrapper_func():
print("wrapper_func worked")
return func()
print("decorator_func worked")
return wrapper_func
def show():
print("Show Worked")
decorator_show = decorator_func(show)
decorator_show()
===== Output ==
decorator_func worked
wrapper_func worked
Show Worked
=========Alternative
start by the @ Symbol
@decorator_func
def display():
print('display wordked')
12What is slicing in Python?
Slicing is used to access parts of sequences like lists, tuples, and strings. The syntax of slicing is-[start:end:step]. The step can be omitted as well. When we write [start:end] this returns all the elements of the sequence from the start (inclusive) till the end-1 element. If the start or end element is negative i, it means the ith element from the end. The step indicates the jump or how many elements have to be skipped. Eg. if there is a list- [1,2,3,4,5,6,7,8]. Then [-1:2:2] will return elements starting from the last element till the third element by printing every second element.i.e. [8,6,4]
13How to combine dataframes in pandas?
The dataframes in python can be combined in the following ways-
Concatenating them by stacking the 2 dataframes vertically.
Concatenating them by stacking the 2 dataframes horizontally.
Combining them on a common column. This is referred to as joining.
The concat() function is used to concatenate two dataframes. Its syntax is- pd.concat([dataframe1, dataframe2]).
14What are the new features added in Python 3.9.0.0 version?
The new features in Python 3.9.0.0 version are-
New Dictionary functions Merge(|) and Update(|=)
New String Methods to Remove Prefixes and Suffixes
Type Hinting Generics in Standard Collections
New Parser based on PEG rather than LL1
New modules like zoneinfo and graphlib
Improved Modules like ast, asyncio, etc.
Optimizations such as optimized idiom for assignment, signal handling, optimized python built ins, etc.
Deprecated functions and commands such as deprecated parser and symbol modules, deprecated functions, etc.
Removal of erroneous methods, functions, etc.
15What is namespace in Python?
A namespace is a naming system used to make sure that names are unique to avoid naming conflicts.
16What is PYTHONPATH?
It is an environment variable which is used when a module is imported. Whenever a module is imported, PYTHONPATH is also looked up to check for the presence of the imported modules in various directories. The interpreter uses it to determine which module to load.
17How to install Python on Windows and set path variable?
To install Python on Windows, follow the below steps:
Install python from this link: https://www.python.org/downloads/
After this, install it on your PC. Look for the location where PYTHON has been installed on your PC using the following command on your command prompt: cmd python.
Then go to advanced system settings and add a new variable and name it as PYTHON_NAME and paste the copied path.
Look for the path variable, select its value and select ‘edit’.
Add a semicolon towards the end of the value if it’s not present and then type %PYTHON_HOME%
18 Is indentation required in python?
Indentation is necessary for Python. It specifies a block of code. All code within loops, classes, functions, etc is specified within an indented block. It is usually done using four space characters. If your code is not indented necessarily, it will not execute accurately and will throw errors as well.
19 Is indentation required in python?
Indentation is necessary for Python. It specifies a block of code. All code within loops, classes, functions, etc is specified within an indented block. It is usually done using four space characters. If your code is not indented necessarily, it will not execute accurately and will throw errors as well.
20 What is the difference between Python Arrays and lists?
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.
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]
21What is __init__?
__init__ is a method or constructor in Python. This method is automatically called to allocate memory when a new object/ instance of a class is created. All classes have the __init__ method.
Here is an example of how to use it.
class Employee:
def __init__(self, name, age,salary):
self.name = name
self.age = age
self.salary = 20000
E1 = Employee("XYZ", 23, 20000)
# E1 is the instance of class Employee.
#__init__ allocates memory for E1.
print(E1.name)
print(E1.age)
22How does break, continue and pass work?
Break: Allows loop termination when some condition is met and the control is transferred to the next statement.
Continue: Allows skipping some part of a loop when some specific condition is met and the control is transferred to the beginning of the loop
Pass: Used when you need some block of code syntactically, but you want to skip its execution. This is basically a null operation. Nothing happens when this is executed.
23What 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.
24What are the generators in python?
Functions that return an iterable set of items are called generators.
25How will you capitalize the first letter of string?
In Python, the capitalize() method capitalizes the first letter of a string. If the string already consists of a capital letter at the beginning, then, it returns the original string.
26How will you convert a string to all lowercase?
To convert a string to lowercase, lower() function can be used.
stg='ABCD'
print(stg.lower())
27What does this mean: *args, **kwargs? And why would we use it?
* Python. We can pass a variable number of arguments to a function using special symbols.
* There are two special symbols:
-: *args (Non-Keyword Arguments)
-: **kwargs (Keyword Arguments)
What is Python *args ?
-: The special syntax *args in function definitions in python is used to pass a variable number of arguments to a function. It is used to pass a non-key worded, variable-length argument list.
def myFun(*argv):
for arg in argv:
print(arg)
myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')
Output:
Hello
Welcome
to
GeeksforGeeks
def myFun(arg1, *argv):
print("First argument :", arg1)
for arg in argv:
print("Next argument through *argv :", arg)
myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')
Output:
First argument : Hello
Next argument through *argv : Welcome
Next argument through *argv : to
Next argument through *argv : GeeksforGeeks
What is Python **kwargs
The special syntax **kwargs in function definitions in python is used to pass a keyworded, variable-length argument list. We use the name kwargs with the double star. The reason is that the double star allows us to pass through keyword arguments (and any number of them).
A keyword argument is where you provide a name to the variable as you pass it into the function.
One can think of the kwargs as being a dictionary that maps each keyword to the value that we pass alongside it. That is why when we iterate over the kwargs there doesn’t seem to be any order in which they were printed out.
def myFun(**kwargs):
for key, value in kwargs.items():
print("%s == %s" % (key, value))
myFun(first='Geeks', mid='for', last='Geeks')
Output:
first == Geeks
mid == for
last == Geeks
def myFun(*args, **kwargs):
print("args: ", args)
print("kwargs: ", kwargs)
myFun('geeks', 'for', 'geeks', first="Geeks", mid="for", last="Geeks")
Output:
args: ('geeks', 'for', 'geeks')
kwargs: {'first': 'Geeks', 'mid': 'for', 'last': 'Geeks'}
28Explain split(), sub(), subn() methods of “re” module in Python.
To modify the strings, Python’s “re” module is providing 3 methods. They are:
split() – uses a regex pattern to “split” a given string into a list.
sub() – finds all substrings where the regex pattern matches and then replace them with a different string
subn() – it is similar to sub() and also returns the new string along with the no. of replacements.
29What are Python packages?
Python packages are namespaces containing multiple modules.
30How can files be deleted in Python?
To delete a file in Python, you need to import the OS Module. After that, you need to use the os.remove() function.
import os
os.remove("xyz.txt")
31How to add values to a python array?
Elements can be added to an array using the append(), extend() and the insert (i,x) functions.
a=arr.array('d', [1.1 , 2.1 ,3.1] )
a.append(3.4)
print(a)
a.extend([4.5,6.3,6.8])
print(a)
a.insert(2,3.8)
print(a)
32How to remove values to a python array?
Array elements can be removed using pop() or remove() method. The difference between these two functions is that the former returns the deleted value whereas the latter does not.
a=arr.array('d', [1.1, 2.2, 3.8, 3.1, 3.7, 1.2, 4.6])
print(a.pop())
print(a.pop(3))
a.remove(1.1)
print(a)
Basic Python Programs – Python Interview Questions
33Write a program in Python to execute the Bubble sort algorithm.
def bs(a):
# a = name of list
b=len(a)-1nbsp;
# minus 1 because we always compare 2 adjacent values
for x in range(b):
for y in range(b-x):
a[y]=a[y+1]
a=[32,5,3,6,7,54,87]
bs(a)
Output: [3, 5, 6, 7, 32, 54, 87]
34Write a program in Python to produce Star triangle.
def pyfunc(r):
for x in range(r):
str= ' '*(r-x-1)+'*'*(2*x+1)+'
'
print(str)
pyfunc(9)
*
***
*****
*******
*********
***********
35Write a program to produce Fibonacci series in Python.
def febFun(n):
f=0
s=1
if n==0:
print(f)
else:
print(f,s)
for x in range(2,n):
next =f+s
print(next)
f=s
s=next
febFun(9)
=======output===
0 1 1 2 3 5 8 13 21
36Write a program in Python to check if a number is prime.
Natural number that is grater then 1 and that has no positive divisor other than 1 or itself.
def checkPrime(n):
if n > 0:
for x in range(2,n):
if(n%x)==0:
print(n,' is not prime number')
break
else:
print(n,' is prime number')
checkPrime(9)
37Write a program in Python to check if a sequence is a Palindrome.
Reverse to string and check it is equal to provided string or not, If matched mean it is Palndrome
def checkPalindrome(mystr):
rev_mystr = mystr[::-1]
if mystr == rev_mystr:
print('Yes Palindrome')
else:
print('Not Palindrome')
checkPalindrome(input('Enter the value:'))
38Write a sorting algorithm for a numerical dataset in Python.
list = ["1", "4", "0", "6", "9"]
list = [int(i) for i in list]
list.sort()
print (list)
39Discuss Django architecture.
Django MVT Pattern:
40Explain how you can set up the Database in Django.
You can use the command edit mysite/setting.py, it is a normal python module with module level representing Django settings.
Django uses SQLite by default; it is easy for Django users as such it won’t require any other type of installation. In the case your database choice is different that you have to the following keys in the DATABASE ‘default’ item to match your database connection settings.
Engines: you can change the database by using ‘django.db.backends.sqlite3’ , ‘django.db.backeneds.mysql’, ‘django.db.backends.postgresql_psycopg2’, ‘django.db.backends.oracle’ and so on
Name: The name of your database. In the case if you are using SQLite as your database, in that case, database will be a file on your computer, Name should be a full absolute path, including the file name of that file.
If you are not choosing SQLite as your database then settings like Password, Host, User, etc. must be added.
DATABASES = {
'default': {
'ENGINE' : 'django.db.backends.sqlite3',
'NAME' : os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
41Give an example how you can write a VIEW in Django?
This is how we can use write a view in Django:
from django.http import HttpResponse
import datetime
def Current_datetime(request):
now = datetime.datetime.now()
html = "It is now %s/body/html % now
return HttpResponse(html)
Data Analysis – Python Interview Questions
42What is map function in Python?
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.
43Is python numpy better than lists?
We use python numpy array instead of a list because of the below three reasons:
1. Less Memory
2. Fast
3. Convenient
44How to get indices of N maximum values in a NumPy array?
We can get the indices of N maximum values in a NumPy array using the below code:
import numpy as np
arr = np.array([1, 3, 2, 4, 5])
print(arr.argsort()[-3:][::-1])
===output===
[ 4 3 1 ]
Multiple Choice Questions (MCQ) – Python Interview Questions
45Which of the following statements create a dictionary? (Multiple Correct Answers Possible)
a) d = {}
b) d = {“john”:40, “peter”:45}
c) d = {40:”john”, 45:”peter”}
d) d = (40:”john”, 45:”50”)
Answer: b, c & d. Dictionaries are created by specifying keys and values.