Python: Python Interview Questions and Answers
Python: Python Interview Questions and Answers
WWW.PAVANONLINETRAININGS.COM
Python Interview Questions and Answers
1) A = 10, 20, 30
In the above assignment operation, what is the data type of ‘A’ that Python appreciates as?
Unlike other languages, Python appreciates ‘A’ as a tuple. When you print ‘A’, the output is (10,20,30). This type of assignment is
2) A = 1,2,3,4
a,b,c,d = A
In the above assignment operations, what is the value assigned to the variable ‘d’?
3) a = 10
b = 20
Swap these two Variables without using the third temporary variable?
a, b = b, a
When we say Name = ‘john’ in Python, the name is not storing the value ‘john’. But, ‘Name’ acts like a tag to refer to the object
‘john’. The object has types in Python but variables do not, all variables are just tags. All identifiers are variables in Python.
WWW.PAVANONLINETRAININGS.COM
5) a = 10
b=a
a = 20
print b
Output is 10.
6) How do you find the type and identification number of an object in Python?
type(<variableName>) gives the type of the object that variable is pointing to, and
id(<variablename>) give the unique identification number of the object that variable is pointing to.
Ex:
print(id(b)) #1452987584
7) a = 0101
b=2
c = a+b
WWW.PAVANONLINETRAININGS.COM
In Python2, any number with leading 0 is interpreted as an octal number. So, variable a points to 65(Equalent in Decimal) then
WWW.PAVANONLINETRAININGS.COM
WWW.PAVANONLINETRAININGS.COM
10) What are the basic Data Types Supported by Python?
String: str
NoneType: None
11) How do you check whether the two variables are pointing to the same object in Python?
In Python, we have an operation called ‘is’ operator, which returns true if the two variables are pointing to the same object.
Example:
a = "Hello world"
c=a
print(a is c) #Returns true if the two variables are pointing to the same object
print(id(a)) #64450416
print(id(c)) #64450416
Python provides an interesting way of handling loops by providing a function to write else block in case the loop is not
Example :
WWW.PAVANONLINETRAININGS.COM
a = [10,20,30]
for i in a:
else:
#Output
in for loop
in for loop
in for loop
in else block
13) How do you programmatically know the version of Python you are using?
The version property under sys module will give the version of Python that we are using.
import sys
print(sys.version)
14) How do you find the number of references pointing to a particular object?
WWW.PAVANONLINETRAININGS.COM
The getrefcount() function in the sys module gives the number of references pointing to a particular object including its own
reference.
import sys
x = "JohnShekar"
y=x
print(sys.getrefcount(x))
Here, the object ‘JohnShekar’ is referred by x, y and getrefcount() function itself. So the output is 3.
‘del’ is the keyword statement used in Python to delete a reference variable to an object.
import sys
x = "JohnShekar"
y=x
print(sys.getrefcount(x))
del x
16) What is the difference between range() and xrange() functions in Python?
WWW.PAVANONLINETRAININGS.COM
range() and xrange() are two functions that could be used to iterate a certain number of times in for loops in Python.
In Python 3, there is no xrange , but the range function behaves like xrange in Python 2.
If you want to write code that will run on both Python 2 and Python 3, you should use range().
Example:
a = range(1, 10000)
x = xrange(1, 10000)
print(type(a))
print(type(x))
All variables and functions follow lowercase and underscore naming convention.
WWW.PAVANONLINETRAININGS.COM
Examples: is_prime(), test_var = 10 etc
None, True, False are predefined constants follow camel case, etc.
Class names are also treated as constants and follow camel case.
Example: UserNames
18) What happens in the background when you run a Python file?
When we run a .py file, it undergoes two phases. In the first phase it checks the syntax and in the second phase it compiles to
bytecode (.pyc file is generated) using Python virtual machine, loads the bytecode into memory and runs.
A module is a .py file in Python in which variables, functions, and classes can be defined. It can also have a runnable code.
The keyword “import” is used to import a module into the current file.
There is a function called reload() in Python, which takes module name as an argument and reloads the module.
The List is one of the built-in data structures in Python. Lists are used to store an ordered collection of items, which can be of
different type.
WWW.PAVANONLINETRAININGS.COM
Elements in a list are separated by a comma and enclosed in square brackets.
A = [1,2,3,4]
B = [‘a’,’b’,’c’]
C = [1,’a’,’2’,’b’]
List in Python is sequence type as it stores ordered collection of objects/items. In Python String and tuple are also sequence
types.
When there is an immutable ordered list of elements, we choose tuple. Because we cannot add/remove an element from the
tuple. On the other hand, we can add elements to a list using append () or extend() or insert(), etc., and delete elements from a
Simple tuples are immutable, and lists are not. Based on these properties one can decide what to choose in their
programming context.
When we pass -1 to the index operator of the list or tuple, it returns the last value. If -2 is passed, it returns the last but one
value.
Example:
a = [1,2,3,4] #List
print(a[-1])#4
WWW.PAVANONLINETRAININGS.COM
print(a[-2])#3
b = (1,2,3,4) #Tuple
print(b[-1])#4
print(b[-2])#3
When the value passed to the index operator is greater than the actual size of the tuple or list, Index Out of Range error is
thrown by Python.
a = [1,2,3,4] #List
In Python, to access more than one element from a list or a tuple we can use ‘:’ operator. Here is the syntax. Say ‘a’ is list
a[startindex:EndIndex:Step]
Example:
a = [100,200,300,400,500,600,700,800]
print(a[3:]) # Prints the values from index 3 till the end [400, 500, 600, 700, 800]
WWW.PAVANONLINETRAININGS.COM
print(a[3:6])#Prints the values from index 3 to index 6. [400, 500, 600]
print(a[2::2])#Prints the values from index 2 till the end of the list with step count 2. [300, 500, 700]
a = [1,2,3,4,5,6,7,8]
print(a)
print(numbers)
28) What is the difference between Python append () and extend () functions?
The extend() function takes an iterable (list or tuple or set) and adds each element of the iterable to the list. Whereas append
Example:
a = [1,2,3,4,5]
b = [6,7,8]
a.extend(b)
WWW.PAVANONLINETRAININGS.COM
print(a)#[1, 2, 3, 4, 5, 6, 7, 8]
c = ['a','b']
a.append(c)
**********************************************************************************************
#Creating strings
print(name)
print(mychar)
print(name1)
print(name2)
WWW.PAVANONLINETRAININGS.COM
#========Strings are immutable=========================
str1="welcome"
str2="welcome"
str2=str2+"to python"
str="welcome"
#============Slicing==============
str="welcome"
print(str[1:3]) #el
print(str[:6])#welcom
print(str[4:])#ome
WWW.PAVANONLINETRAININGS.COM
print(str[1:-1]) #elcom #elimate 1 char from end
print(len("hello")) #5
print(max("abc")) #c
print(min("abc")) #a
s1 = "Welcome"
#==============Strings comparison================
WWW.PAVANONLINETRAININGS.COM
print ("yellow" <= "fellow") #False
#===============Testing strings====================
s = "welcome to python"
print(s.isalnum()) #False
print("Welcome".isalpha()) #True
print("2012".isdigit()) #True
print("first Number".isidentifier())#False
print(s.islower()) #True
print("WELCOME".isupper()) #True
s = "welcome to python"
print(s.endswith("thon")) #True
print(s.startswith("good")) #False
print(s.find("come")) #3
print(s.find("become")) #-1
WWW.PAVANONLINETRAININGS.COM
print(s.count("o")) #3
#===============Converting Strings================
s = "String in PYTHON"
s1 = s.capitalize()
s2 = s.title()
print(s2)#String In Python
s3 = s.lower()
s4 = s.upper()
s5 = s.swapcase()
WWW.PAVANONLINETRAININGS.COM
s6 = s.replace("in", "on")
30) How do you create a list which is a reverse version on another list in Python?
Python provides a function called reversed(), which will return a reversed iterator. Then, one can use a list constructor over it
to get a list.
Example:
a =[10,20,30,40,50]
print(a)
In Python, dictionaries are kind of hash or maps in another language. Dictionary consists of a key and a value. Keys are unique,
and values are accessed using keys. Here are a few examples of creating and accessing dictionaries.
Examples:
WWW.PAVANONLINETRAININGS.COM
########Retrieving, modifying and adding elements in the dictionary##############
print(friends['tom']) # 111-222-333
friends['bob'] = '888-999-666'
friends['bob'] = '888-999-777'
del friends['bob']
WWW.PAVANONLINETRAININGS.COM
32) How do you merge one dictionary with the other?
Python provides an update() method which can be used to merge one dictionary on another.
Example:
a = {'a':1}
b = {'b':2}
a.update(b)
33) How to walk through a list in a sorted order without sorting the actual list?
In Python we have function called sorted(), which returns a sorted list without modifying the original list. Here is the code:
a=[500,300,400,200,100]
34) names = [‘john’, ‘fan’, ‘sam’, ‘megha’, ‘popoye’, ’tom’, ‘jane’, ‘james’,’tony’]
Write one line of code to get a list of names that start with character ‘j’?
Solution:
WWW.PAVANONLINETRAININGS.COM
names = ['john', 'fan', 'sam', 'megha', 'popoye', 'tom', 'jane', 'james', 'tony']
jnames=[name for name in names if name[0] == 'j'] #One line code to filter names that start with ‘j’
print(jnames)
Write a Python code to find how many different characters are present in this string?
Solution:
print(len(set(a))) #16
TypeError: Occurs when the expected type doesn’t match with the given type of a variable.
ValueError: When an expected value is not given- if you are expecting 4 elements in a list and you gave 2.
WWW.PAVANONLINETRAININGS.COM
38) How Python supports encapsulation with respect to functions?
Python supports inner functions. A function defined inside a function is called an inner function, whose behavior is not
39) How do you open an already existing file and add content to it?
In Python, open(<filename>,<mode>) is used to open a file in different modes. The open function returns a handle to the file,
using which one can perform read, write and modify operations.
Example:
List
Sets
Dictionaries
Strings
Tuples
WWW.PAVANONLINETRAININGS.COM
Numbers
In Python, module is the way to structure program. Each Python program file is a module, which imports other modules like
The folder of Python program is a package of modules. A package can have modules or subfolders.
import random
print(random.random())
Example:
import os
import cx_Oracle
os.environ['PATH'] = 'E:\\app\\OracleHomeUser1\\instantclient_18_3'
WWW.PAVANONLINETRAININGS.COM
# Connect to hr account in Oracle Database 11g Express Edition
cur = con.cursor()
cur.execute(query)
print("Completed!!!")
cur.close()
con.close()
43) How to connect to the Microsoft Excel and read write data in to excel using python script?
WWW.PAVANONLINETRAININGS.COM
# import openpyxl module
import openpyxl
path = "C:\SeleniumPractice\data3.xlsx"
workbook = openpyxl.load_workbook(path)
sheet = workbook["Sheet1"]
rows=sheet.max_row
cols=sheet.max_column
for r in range(1,rows+1):
for c in range(1,cols+1):
print()
WWW.PAVANONLINETRAININGS.COM
Writing data into Excel:
import openpyxl
path = "C:\SeleniumPractice\Test2.xlsx"
workbook = openpyxl.load_workbook(path)
sheet= workbook.active
for r in range(1,5):
for c in range(1,3):
workbook.save(path)
WWW.PAVANONLINETRAININGS.COM
LIST vs TUPLES
LIST TUPLES
Lists are mutable i.e they can be edited. Tuples are immutable (tuples are lists which can’t be edited).
Lists are slower than tuples. Tuples are faster than list.
Syntax: list_1 = [10, ‘Chelsea’, 20] Syntax: tup_1 = (10, ‘Chelsea’ , 20)
Inheritance allows One class to gain all the members(say attributes and methods) of another class. Inheritance provides code
reusability, makes it easier to create and maintain an application. The class from which we are inheriting is called super-class
1. Single Inheritance – where a derived class acquires the members of a single super class.
2. Multi-level inheritance – a derived class d1 in inherited from base class base1, and d2 are inherited from base2.
3. Hierarchical inheritance – from one base class you can inherit any number of child classes
4. Multiple inheritance – a derived class is inherited from more than one base class.
46). How can you randomize the items of a list in place in Python?
WWW.PAVANONLINETRAININGS.COM
from random import shuffle
shuffle(x)
print(x)
list.sort()
print (list)
Example:
import time;
WWW.PAVANONLINETRAININGS.COM