Python Interview Questions
1. Basic
Q1. What is python?
Python is a high-level, interpreted, interactive
general-purpose programming language.
Highly interactive and has simple syntax.
Q2. Python use cases?
AI
Machine learning
Data analytics,
Data science,
Game development,
Web development,
Q3. Why python is preferred?
Many libraries, frameworks,
Security,
Extensible,
Portable,
Scripting & automation,
Visualizations, graphics
Q4. Interpreted in python?
Code is not compiled, instead interpreter reads the code line by line and executes the code.
Q5. Specify python version in a program?
#!/usr/bin/python2.7.3
Q6. Is python case sensitive?
Yes. Int1 is different from int1.
# Python case sensitive example
Int1 = 10
int1 = 20
print (Int1)
O/p:
10
Q7. What is interpreter in python?
CPython is an interpreter.
Q8. What is Key word in python?
Key words are reserved word in python and can not be used as Variable name, function name.
False, None, true start with Capital letter remaining all keywords start with smallcase.
Key words in python are:
|
and |
del |
if |
pass |
|
as |
elif |
import |
raise |
|
assert |
else |
in |
return |
|
async |
FALSE |
is |
try |
|
await |
except |
lambda |
while |
|
break |
finally |
None |
with |
|
class |
for |
nonlocal |
yield |
|
continue |
from |
not |
TRUE |
|
def |
global |
or |
Q9. What is an identifier in python?
Identifier is a name given to entities like Variables, functions, classes…
Q10. What is a variable?
Reserved memory location to store values.
Int1 = 10
Int1 is variable.
Q11. Constant / Literal in python?
Variable which can not be changed is constant /Literal.
These are declared in modules, which can be imported.
Q12. Literal in python?
Raw data assigned to variables, constants.
Q13. Operators in python?
1. Arithmetic operators (+, -, *, /, %, **, //)
2. Assignment operators (=, +=, -=, *=, /=, %=, **=)
3. Comparison operators (==, !=, <>, >, <, >=, <=)
4. Logical operators (and, or, not)
5. Identity operators (is, is not)
Q14. Type conversions in python?
Converting one data type to another data type.
2 types:
1. Implicit
2. Explicit
Implicit:
In Implicit automatic data type conversion happens.
# Python Implicit data type conversion
num1 = 10
num2 = 20.30
result = num1 + num2
print("Data type of result :", type(result))
print("result :", result)
O/p:
Data type of result : <class 'float'>
result : 30.3
Explicit:
Use functions to convert. Like int(), float(), str().
num1 = 10
num2 = 20.30
num3 = int (num2)
num4 = float (num1)
num5 = str (num1)
Q15. Data types in python?
Text: str
Numeric: int,
float, complex
Sequence: list,
tuple, range
Mapping: Dict
Set types: set, frozen set
Boolean type: bool
Binary
types: bytes, byte
array, memory view
Q16. input in python?
Takes input from user.
#
num1 = int(input ('enter a num :'))
print(num1)
Q17. Output
formatting in python?
x = 10
y = 20
add = x + y
print('The value of x is {} and y is {}'.format(x, y), 'and their sum is :', add)
Q18. Flaws of
python?
High memory consumption,
Debugging errors
2. Loops/ flow control
Q1. Types of flow control in python?
1. Conditional (if, if else, if elif else)
2. loops (for loop, while loop)
1. Conditional (if, if else, if elif else)
2. loops (for loop, while loop)
Q2. loop control statements /branching in python?
1. break,
2. continue
3. pass
2. continue
3. pass
Q3. If 'n' number is given print output as 123..n ?
n = int(input())
i = 0
while i< n:
i +=1
print(i, end ='')
print(i, end ='')
Q4. Int division, float division?
a = int(input('n1 :'))
b = int(input('n2 :'))
print (a // b)
print (a / b)
Q5. Print squares?
n = int(input('n1 :'))
i = 0
while i< n:
i +=1
print(i **2)
i = 0
while i< n:
print(i **2)
Q6. Leap year or not?
# function to find year is leap year or not
def is_leap(year):
leap = True
# Write your logic here
if (year % 4 == 0) and (year % 100 != 0):
return leap
elif (year % 400 == 0) and (year % 100 == 0):
return leap
else:
return False
year = int(input('year :'))
print(is_leap(year))
def is_leap(year):
# Write your logic here
if (year % 4 == 0) and (year % 100 != 0):
year = int(input('year :'))
Q7. Generate list comprehension as below?
X=1, y=1, z=2
All permutations of [i, j, k] are:
[[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 1, 0], [0, 1, 1], [0, 1, 2], [1, 0, 0], [1, 0, 1], [1, 0, 2], [1, 1, 0], [1, 1, 1], [1, 1, 2]]
Print an array of the elements that do not sum to n= 3.
[[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 2]]
All permutations of [i, j, k] are:
[[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 1, 0], [0, 1, 1], [0, 1, 2], [1, 0, 0], [1, 0, 1], [1, 0, 2], [1, 1, 0], [1, 1, 1], [1, 1, 2]]
[[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 2]]
results = []
a = int(input('a is :'))
b = int(input('b is :'))
c = int(input('c is :'))
d = int(input('d id :'))
for x in list(range(a+1)):
for y in list(range(b+1)):
for z in list(range(c+1)):
if ( x+y+z) !=d:
results.append([x, y, z])
print(results)
for x in list(range(a+1)):
print(results)
Q8. Second largest number from list?
n = int(input())
a = [int(x) for x in input().split(',')]
largest = secondlargest = -100
for x in a:
if x > largest:
tmp = largest
largest = x
secondlargest = tmp
elif x > secondlargest and x != largest:
secondlargest = x
print(secondlargest)
for x in a:
largest = x
secondlargest = tmp
elif x > secondlargest and x != largest:
print(secondlargest)
3. Data Types / Data Structures
Q1. Python string?
Immutable.
Created in single, double, triple quotes.
string_single_quotes = 'Hello'
string_double_quotes = "Hello"
string_triple_quotes = '''hello'''
Q2. Reassign a
string in python?
str1 = 'hi'
str1 = 'hello' # reassign str1
Q3. String slicing?
#
str1 = 'hello python'
print (str1[0:6])
Q4. Numbers in number data type in python?
Int, float, complex
#
int_num = 10
float_num = 20.12
complex_num = 2 + 3j
Q5. Difference between tuple, list?
Both are sequences.
List is mutable, tuple is immutable.
Q6. Can we sort tuple? tuple= (1,5,3)
yes
list = [1,5,3]
list.sort()
O/p:
[1,3,5]
tuple(1,5,3)
sorted(tuple)
Out[20]:
[1, 3, 5]
Q7. List(1,2), tuple(a,b) dictionary {[1,a], [2,b]}
list = [1, 2]
tuple =('a', 'b')
dict1 = dict(zip(tuple, list))
print(dict1)
Output: {'a': 1, 'b': 2}
Q8. Built-in List Functions & Methods?
1 cmp(list1, list2): Compares elements of lists.
2 len(list): Gives length of the list.
3 max(list): Returns max value.
4 min(list): Returns min value.
5 list(seq): Converts a tuple into list.
Q9. Diff between append & extend method in python?
Append: Adds argument as a single element to end of a list.
Length of list increases by one.
#
list1 = ['Bng','Hyd', 'Chennai']
list2 = [1,2,3]
list1.append(list2)
print (list1)
O/p:
['Bng', 'Hyd', 'Chennai', [1, 2, 3]]
Extend: adding each element in argument to the list and extending it.
Length of list increases by number of elements in its argument.
#
list1 = ['Bng','Hyd', 'Chennai']
list2 = [1,2,3]
list1.extend(list2)
print (list1)
O/p:
['Bng', 'Hyd', 'Chennai', 1, 2, 3]
Q10. sets in python?
A Set is an unordered collection data type that is inerrable, mutable, and has no duplicate elements, works fast.
Advantage of using a set, as opposed to a list, is that it has a highly optimized method for checking whether a specific element is contained in the set.
This is based on data structure known as a hash table.
Frozen Sets:
Frozen sets are immutable objects that support methods and operators that produce a result without affecting the frozen set or sets to which they are applied.
Q11. list comprehension?
A list comprehension generally consists of these parts:
Output expression,
input sequence,
a variable representing member of input sequence and
an optional predicate part
List1 = [x ** 2 for x in range (1, 11) if x % 2 == 1]
Here,
x ** 2 #--> is output expression,
range (1, 11) #--> is input sequence,
x #--> is variable and
if x % 2 == 1 #--> is predicate part.
Q12. collect duplicates from list using python?
# Python program to print duplicates from a list of integers
def Repeat(x):
_size = len(x)
repeated = []
for i in range(_size):
k = i + 1
for j in range(k, _size):
if x[i] == x[j] and x[i] not in repeated:
repeated.append(x[i])
return repeated
# Driver Code
list1 = [10, 20, 30, 20, 20, 30, 40,
50, -20, 60, 60, -20, -20]
print (Repeat(list1))
Q13. Mutable and immutable objects?
Immutable Objects: These are of in-built types like int, string, float, bool, unicode, tuple.
Mutable Objects: These are of type list, dict, set
Exception: However, there is an exception in immutability as well. We know that tuple in python is immutable. But the tuple consists of a sequence of names with unchangeable bindings to objects.
Consider a tuple
tup = ([3, 4, 5], 'myname')
A list as an item inside a tuple can be changed.
Example:
tuple =([1,2,3],'hkn')
tuple[0][0]=10
pritn(tuple)
Out/put:
([10, 2, 3], 'hkn')
Q14. pop in python?
By default, removes last element.
list1 = [1,2,3,4]
list1.pop()
print(list1)
O/p:
[1, 2, 3]
Q15. Iterate through dictionary?
dict1 = {1: 'sam', 2: 'ram', 3: 'tom'}
for i in dict1:
print (dict1[i])
O/p:
sam
ram
tom
Q16. Slicing a string?
str = 'helloPython'
print (str[0:])
print (str[0:5:2])
O/p:
helloPython
hlo
Q17. String format?
# string format
print("Hi, I am {}, I am from {}.".format(input ('enter name :'), input('city :')))
print('int number is : {:d}'.format(10))
print('float number is : {:f}'.format(10.20))
# int minimum width, no padding
print("{:5d}".format(12))
# int minimum width & padding
print("{:05d}".format(12))
O/p:
enter name :hk
city :nn
Hi, I am hk, I am from nn.
int number is : 10
float number is : 10.200000
12
00012
Q18. can you create empty set?
Yes
a = set()
print(type (a))
Q19. Add elements to set?
#
set1 = {10, 20, 30}
set1.add(40)
Q20. Add multiple elements to set?
#
set1 = {10, 20, 30}
set1.update([40, 50, 60])
print (set1)
Q21. range?
a = list(range(5))
print(a)
4. Files / Input, Output
Q1. Open a file and read the content?
#
try:
file1 = open(r"D:\8_AWS\text1.txt")
print (file1.read())
print('Take cursor position to 0:', file1.seek(0))
finally:
file1.close() # close file
try:
Q2. Get current directory and files in it?
#
import os
# Get current working directory
print(os.getcwd())
# Get lsit of ifles in directory
print (os.listdir())
import os
# Get current working directory
print(os.getcwd())
# Get lsit of ifles in directory
print (os.listdir())
Q3. Delete /Remove a file?
# Remove file
# File removed & returns None
print(os.remove('file1.py'))
# File removed & returns None
print(os.remove('file1.py'))
Q. Remove a directory?
import os
os.rmdir(r'D:\8_AWS\tmp_dir')
Q. Use a file in another file?
We can import a file
as a module in another file.
In below example
file1 is imported as a module in file2.
# file1
def file1():
print ('hi, this is from file1')
# file2
from file1 import *
file1()
O/p:
hi, this is from
file1
5. Exceptions
Q1. What are assertions?
Assertion is a sanity-check.
Place assertions at the start of a function to check for valid input.
def Salary(Sal):
assert (Sal >= 0),"always greater than 0"
return (Sal)
print (Salary(130000))
print (Salary(-10000))
Q2. What is exception?
Errors detected during execution are called exceptions.
#
a=2
b=0
div = a/b # we get ZeroDivisionError exception
O/p:
Traceback (most recent call last):
File "D:\0_python\file2.py", line 4, in <module>
div = a/b # we get ZeroDivisionError exception
ZeroDivisionError: division by zero
Q3. Handle an exception?
Using Try and Except block we can handle exception.
try:
a=int(input ('enter a:'))
b=int(input ('enter b:'))
div = a/b
except ZeroDivisionError:
print ('Except ZeroDivisionError ')
Q4. Raising exception?
The raise statement allows the programmer to force a
specified exception to occur.
try:
a=int(input ('enter a:'))
b=int(input ('enter b:'))
div = a/b
except ZeroDivisionError:
raise RuntimeError from None
print ('Except ZeroDivisionError ')
O/p:
enter a:2
enter b:0
Traceback (most recent call last):
File "D:\0_python\file2.py", line 6, in <module>
raise RuntimeError from None
RuntimeError
Q5. User defined exception example?
class NameNotCurrectError(Error):
"""Raised when input name is not matched"""
pass
# Guess this City
name1 = 'Bengaluru'
# Guess until you are right
while True:
try:
name2 = input("Enter city: ")
if name2 != name1:
raise NameNotCurrectError
break
except NameNotCurrectError:
print("Name not matched, try again!")
print()
print("Congrats! u guessed correctly.")
Q6. Cleanup in exception?
Done by finally block.
Finally clause is useful for releasing external resources (such as files or network connections), regardless of whether the use of the resource was successful.
def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
print("division by zero!")
else:
print("result is", result)
finally:
print("executing finally clause")
divide (2,1)
6. Functions
Q1. What is a function?
Function is a similar kind of tasks as a block.
Q2. Types of
functions?
2 types.
1.
User defined functions
2.
Built in functions.
Q3.
Types of arguments in a function?
4 types of
arguments:
1. Required arguments
2. Default arguments
def default_args(name, city='Bng'):
print (name, city)
# Name is required argument
# City is default arg
default_args('hk')
3.Keyword arguments
def keyword_args(name1, name2):
print (name1, name2)
# name1, name2 are keywords
keyword_args(name1='bng', name2= 'hyd')
4. Variable-length
arguments / arbitrary arguments
def print_cities(*cities):
for city in cities:
print(city)
print_cities('Bengaluru', 'Hyd', 'Pune', 'Mysore')
Q4. Scopes in python?
Local Scope
Enclosed Scope
Global Scope
Built-in Scope
LEGB rule applies for scope.
Q5. Recursive function?
Function
calls itself.
# recursive function
def recursive_func_sum(n):
if n <= 1:
return n
else:
return n + recursive_func_sum(n-1)
print (recursive_func_sum(10))
Q6. Generative
function?
Yield keyword is used
Q7. decorative?
A function returning another function, usually applied as a
function transformation using the @wrappersyntax. Common examples for
decorators are classmethod() and staticmethod().
Q8. *args vs **kwargs?
*args is used for passing variable number of non-keyword arguments
in a function.
Non keyword means not a dictionary.
Args can be strings, numbers.
Asterisk(*) is unpacking operator.
# *args example
def n_names(*names):
return names
# Takes variable number of args
# args are given as tuple
print("names are :",n_names('Bng', 'Hyd', 'Mysore' ))
print('')
# Takes variable number of args
print("names are :",n_names('Pune', 'Coorg', 'Mangalore', 'Shimoga' ))
# **kwargs example
def n_names(**names):
return names
# Takes variable number of kwargs
#
print("names are :", n_names(a='Bng', b='Hyd', c='Mysore', d ='are south cities' ))
print('')
# Takes variable number of kwargs
print("names are :", n_names(a= 'Coorg', b='Mangalore', c='Shimoga', d='are west Karnataka cities' ))
Q9. Packing vs
unpacking args in python?
Packing is tuple of args as a single variable like *args.
cities = ('Bng', 'Mysore', 'Shimoga', 'Mangalore')
def print_cities (*args):
for i in args:
print (i)
print_cities(*cities)
O/p:
Bng
Mysore
Shimoga
Mangalore
Q10. What is partial function in python?
Partial functions allow us to fix a certain
number of arguments of a function and generate a new function.
Example:
#
from functools import partial
# A normal function
def f(a, b, c, x):
return 1000*a + 100*b + 10*c + x
# A partial function that calls f with a as 3, b as 2 and c as 1.
g = partial(f, 3, 2, 1)
# Calling g()
print(g(4))
O/p:
3214
6.1. Lambda Fucntion:
Q. Anonymous function?
Function without a name and on fly is called anonymous function.
Example: lambda.
Q. Lambda syntax?
lambda [args]: expression
# # Example of lambda function
num = [1,2,3]
print (list(map((lambda x : x**2), num )))
O/:
[1, 4, 9]
# Lambda fucntion with reduce
#import reduce() function
from functools import reduce
numb = [ 1, 2, 3]
sum = reduce((lambda x, y: x + y), numb)
print(sum)
O/p:
6
Q. lambda usage on DataFrame:
df['comp_score'] = df['compound'].apply(lambda c: 'pos' if c >=0 else 'neg')
7. Classes
Q. What is class attribute in python?
Class attributes are variables defined
inside class.
class Class_1:
class_name = 'Grade1'
# class_name is class attribute
Q2. What is python class method?
class Class_1:
class_name = 'Grade1'
# class_name is class attribute
def grade_info (self, class_name):
# grade_info is calss method
Q3. What is instance attribute?
Attribute under __init__ method in instance.
(attribute inside an instance)
class Class_1:
# details is instance attribute
def __init__(self, detail):
self.detail = detail
Q4. Object in python?
class Class_1:
# details is instance attribute
def __init__(self, detail):
self.detail = detail
# grade_info is calss method
def grade_info (self):
print('Grade details are :', self.detail)
# object1 is object
object1 = Class_1('Grade1')
object1.grade_info()
Q5. Inheritance?
The process in which one class inherits attributes and methods from another class.
Attributes, Methods inherited from: Parent class
Class which inherits is called Child class.
class Class_parent():
pass
class Class_child(Class_parent):
pass
Q6. Types of inheritance in python?
1. Single Inheritance (parent-child)
2. Multiple Inheritance (parent, parent -child)
3. Multi-Level Inheritance (Grand parent-parent-child)
4. Hierarchical Inheritance (Parent-child, child)
5. Hybrid Inheritance (Grand parent -parent, parent-child)
Q7. What is MRO (Method Resolution Order)?
Method resolution order defines the order in which the base classes are searched when executing a method.
(Parent class, child class relationship)
Q8. What is Encapsulation in python? Need of encapsulation?
Encapsulation is wrapping data and the methods as a single unit.
Readable code, security are the benefits of Encapsulation.
Encapsulation is implemented using public, private and protected members
Q9. What is Polymorphism?
Polymorphism is the ability to use the same syntax for objects of different types.
Same function name can be used for different types.
Q10. Generative function?
Yield keyword is used
Q11. decorative?
A function returning another function, usually applied as a function transformation using the @wrappersyntax. Common examples for decorators are classmethod() and staticmethod().
Q12. Higher order functions?
Functions that take other functions as arguments are called higher order functions.
# higher order function
def sum1(x):
return x + 1
def sum2(func, x, y):
result = func(x)
return func(x) + y
print(sum2(sum1, 5, 5))
O/p:
11
Q13. What is Operator overloading?
Operator overloading is using an operator beyond its pre-defined purpose.
# Here Plus operator used for addition and concatenation
print(10 + 20)
print('10' +'20')
8. Modules/ libraries
9 Others:
Q1. Multithreading in python?
To run multiple tasks parallelly.
import threading
t1 = threading.Thread(target=print_square, args=(10,))
t2 = threading.Thread(target=print_cube, args=(10,))
Q2. __init__.py usage?
https://stackoverflow.com/questions/448271/what-is-init-py-for
Python defines two types of packages, regular packages and namespace packages.
Regular packages are traditional packages as they existed in Python 3.2 and earlier. A regular package is typically implemented as a directory containing an __init__.py file. When a regular package is imported, this __init__.py file is implicitly executed, and the objects it defines are bound to names in the package’s namespace. The __init__.py file can contain the same Python code that any other module can contain, and Python will add some additional attributes to the module when it is imported.
Q3. deep copy, shallow copy?
Deep copy is a process in which the copying process occurs recursively. It means first constructing a new collection object and then recursively populating it with copies of the child objects found in the original. In case of deep copy, a copy of object is copied in other object. It means that any changes made to a copy of object do not reflect in the original object. In python, this is implemented using “deepcopy()” function.
A shallow copy means constructing a new collection object and then populating it with references to the child objects found in the original. The copying process does not recurse and therefore won’t create copies of the child objects themselves. In case of shallow copy, a reference of object is copied in other object. It means that any changes made to a copy of object do reflect in the original object. In python, this is implemented using “copy()” function.
basic copy in python.
# importing copy module
import copy
# initializing list 1
li1 = [1, 2, [3,5], 4]
# using copy for shallow copy
li2 = copy.copy(li1)
# using deepcopy for deepcopy
li3 = copy.deepcopy(li1)
Q4. Adding 2 dataframes ?
#Adding 2 data frames:
import pandas as pd
d1 = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}
df1 = pd.DataFrame(d)
d2 = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c'])}
df2 = pd.DataFrame(d2)
new_df =pd.concat([df1, df2], axis=1)
Q5. List comprehension vs Generator comprehension?
# List comprehension vs Generator comprehension
list1 = [1,2,3]
# List comprehension
list_comprehension = [x**2 for x in list1]
# Generator comprehension
# () are used in generator comprehension
generator_comprehension = (x**2 for x in list1)
print ('')
print(list_comprehension)
print ('')
for i in generator_comprehension:
print (i)
Q6. If n is given print sum 1/1 to 1/n?
n = int(input ('enter a num :'))
i = 1
sum = 0
while i < (n +1):
sum += 1/i
i += 1
print (sum)
O/p:
enter a num
:3
1.8333333333333333
#
from functools import reduce
num = int (input ('enter a num: '))
numb = list (range (num +1))
sum = reduce((lambda x, y: x + 1 / y), numb)
print(sum)
Q. Reverse a string?
def rev_str(my_str):
length = len(my_str)
for i in range(length - 1, -1, -1):
yield my_str[i]
# For loop to reverse the string
for char in rev_str("hello"):
print(char, end='')
No comments:
Post a Comment