You are on page 1of 44

Python Interview Questions

Features of python

Python is an interpreted, high-level, general-purpose programming language..


1.Easy to Code,read and Expressive
2.Free and Open-Source:Python is freely available.
3. Python is a high-level language.
4. Portable:Write once and execute anywhere
5. Interpreted: source code is executed line by line, and not all at once.
6.It is easier to write a code in Python as the number of lines is less comparatively.
7. Python is dynamically-typed. This means that the type for a value is decided at
runtime, not in advance.
8. Python is an extensible language, meaning that it can be extended to other
languages.
9.Python has large standard libraries in it.
Basic data types
Text Type: str

Numeric Types: int, float, complex

Sequence Types: list, tuple

Mapping Type: dict


Set Type: set
Strings:
A string is a sequence of characters. a=’python’
print(a)
Examples: print(type(a))
b=’12.345’
‘A’
print(b) d=input()
“Python”
“123” print(type(b)) print(d)
“””programming””” print(type(d))
Python Numbers:

Int: includes positive and negative ,unlimited length


a=1
y=123456789012345678901234567890
print(a)
print(y)
print(type(a))
print(type(y))
z=-234
print(z)
print(type(z))
float: It consists of positive and negative numbers
containing decimals numbers

d=1.10 y=0.123
print(d) print(y)
print(type(d)) print(type(y))

z= -0.123
print(z)
print(type(z))
complex numbers:Complex numbers in python are in the form
of a + bj

x=3+5j
print(x)
z=-5j
print(type(x)) y=5j print(z)
print(y) print(type(z))
print(type(y))
(3+5j)
<class ‘complex’>
Python List
Python tuple
L=[1,2,3]
print(L) T=(1,2,3)
print(type(L)) print(T)
print(type(T))
Output:
Output:
[1,2,3]
<class ’list’>
(1,2,3)
<class ’tuple’>
Python Set Python dictionary
a={1,2,3,4} d = {1:'v1','2':’v2’}
print(a) print(d)
print(type(a)) print(type(d))

{1,2,3,4} {1:'v1','2':’v2’}
<class ’set’> <class ’dict’>
Dictionary
Elements are represented as pair of key and value
Dictionaryname={key1:value1,key2:value2…………….keyn:valuen}

Keys are unique and it can be a string,tuple,number

d1={ 1:1.2 , 2:’a’ , 3:[1,2,3] , 4:(1,2,3) }

d2={(1,2) : 1, ’a’:2 , 1.5:3 } d3={ [1,2,3]:1 , ’a’:2 }


Membership Operators
x=[1,2,3,4,5]
y=int(input("enter the value of y:"))
5
print(y in x)
print(y not in x)
enter the value of y:5
True
False
Logical Operators
x=int(input("Enter the value of x:")) 6
print(x<5 and x<10)
6<5 & 6<10 F&T
print(x<5 or x<4)
print(not(x>10)) 6<5 or 6<4 F or F
not(6>10) not(F)

Enter the value of x:6


False
False
True
Repetition Statements:
for loop
while loop
for loop

Syntax for range:


range(end) #0 to end-1
range(3) 0,1,2
range(6) 0,1,2,3,4,5
range(start,end) #start to end-1

range(2,6) 2,3,4,5

range(1,4) 1,2,3

range(start,end,step) range(-5,0,1)
range(1,10,2) 1,3,5,7,9
-5,-4,-3,-2,-1
range(2,12,2) 2,4,6,8,10
for i in range(0,3): #print even numbers
print(i) for i in range(0,11,2):
print(i)
for i in range(1,3):
print(i) Looping Through a String

#print odd numbers for i in “python”:


for i in range(1,10,2): print(i)
print(i)
while
4<6 5<6 6<6
4 5
i=4+1 i=5+1

1<6 2<6 3<6


1 2 3
i=1+1 i=2+1 i=3+1
The pass statement is used as a placeholder for future code.
When the pass statement is executed, nothing happens, but we avoid getting
an error when empty code is not allowed.
Empty code is not allowed in loops, function definitions, class definitions, or in if
statements

Syntax:
pass
for x in [0, 1, 2]:

pass

def myfunction:

pass
LIST
List is collection of ordered elements,surrounded by square brackets[].
List is mutable(changeable)
List is dynamic. They grow and shrink on demand.
The list is better for performing operations, such as insertion and deletion.
Lists consume more memory
Lists have several built-in methods

l=[]
l1=[1,2,3]
l2=[‘p’,’r’,’o’,’b’,’e’]
#List with mixed datatypes
a=[1,”hai”,3.4]
print(a)
slicing: -7 -6 -5 -4 -3 -2 -1
t = [‘a’,’b’,’c’,’d’,’e’,’f’,’g’] t = [‘a’,’b’,’c’,’d’,’e’,’f’,’g’]
print(t) 0 1 2 3 4 5 6
print(t[1])
print(t[1:3]) ['a', 'b', 'c', 'd', 'e', 'f', 'g']
b
print(t[1:-1]) ['b', 'c']
['b', 'c', 'd', 'e', 'f']
print(t[:3]) ['a', 'b', 'c']
['c', 'd', 'e', 'f', 'g']
print(t[2:]) ['a', 'b', 'c', 'd', 'e', 'f']
['b', 'd', 'f']
print(t[:-1]) ['g', 'f', 'e', 'd', 'c', 'b', 'a']
print(t[1::2])
print(t[::-1])
#Removing duplicates in a list
my_list = [1,1,2,3,2,2,4,5,6,2,1]
my_final_list = set(my_list)
print(list(my_final_list))

Output:
[1, 2, 3, 4, 5, 6]
Comprehensions in Python provide us with a short and concise way to construct new sequences
(such as lists, set, dictionary etc.) using sequences which have been already defined.

List comprehension allows us to create a new list of elements that satisfy a


condition from an iterable. An iterable is any Python construct that can be looped
over like lists, strings, tuples, sets. In list comprehensions we use square brackets.

s=[x*x for x in range(1,11) if x%2==0]

Range includes 1 to 10,

Result of above comprehension will be:

[4, 16, 36, 64, 100]


Tuples:

it is a sequence of immutable objects.

Tuples are fixed in length, heterogeneous, and can be nested.

They are represented by () t2=(1,2,3,4,5)


print(t2)
t1=()
print(type(t1)) t3=(1,1.2,’abc’)
print(t3)
Dictionaries:
Python dictionary is an ordered collection of elements and it is mutable

We can store values as a pair of keys and values

Represented by dict() or {}
Keys in dictionary are unique and they are immutable(strings,numbers,tuples)

d={} d1={1:’Ay’,2:’aa’,3:’n’} d2={‘a’:1,’b’:2,’c’:3}


print(d) print(d2)
print(d1)
print(type(d))

d3={1:1.1,2:’a’,3:[1,2,3],4:(1,2,3)} #mixed dictoinary


print(d3)
Sets:
set is unordered collection of elements and it is mutable
Every element is unique and must be immutable(Numbers,Strings,tuples)

Sets are represented by { } or by built in function set()

s={1,2,3} s1={“python”,(1,2,3)} s2={[1,2,3],1.0,’hai’}


print(s) print(s1) print(s2)
s={3,2,3,1} #output:error because list is
print(s) mutable,but set should have immutable
elements
Output:{1,2,3}
Strings
Multiline Strings:
Strings are immutable
a=””” python is
Invented by
Van Rossum”””
print(a)
Need of Functions:
Simplifies program
Understanding programs becomes easier.
By dividing a large program into smaller functions, different
programmers can work on different functions.
Users can create their own functions
Code reusability
Definition:
A function is a block of organized and reusable program code
that performs a specific, single, and well-defined task.
Built-in functions:
Python interpreter has number of functions that are available
for use.They are called as Bulit-in functions.
Eg: input(),print(),range(),abs(),len(),type(),sum(),sorted(),etc.,

Basic Math Functions


It is a standard module in python,To use mathematical
functions ,we have to import module using “import math”
Calling a Function

Let’s consider the following example which demonstrates function definition and function call:
#Write a program to calculate cube of a number

def cube(x): 2
“”” calculating cube without using return and different
name for formal and actual values”””
print(x*x*x) 8
a=int(input(“Enter the value of a:”)) 2
cube(a)
#Write a program to calculate cube of a number using
return
def cube(x): 2
“”” calculating cube with using return”””
return(x*x*x)
x=int(input(“Enter the value of x:”)) 2
y=cube(x) 8
print(“Cube of the number”,y)
8
Recursive Function:

A recursive functions is a function which calls itself.


Recursion uses divide and conquer strategy to solve problems.
def fact(n):
n=2
"""Returns the factorial of a number n=3 2==0 or 2==1(F)
using recursion.""" 3==0 or 3==1(F)
if n==0 or n==1: 3*2*fact(1)
return 1 3*fact(2)
else:
return n*fact(n-1) Return 6
n=1
1==0 or 1==1(T)
n=int(input(“enter n value”))
3 Return 1
print(“factorial=”,fact(n))
6 Enter n value 3
factorial=6
Global Variable Local Variable
Variable which is defined in the main body of the Variable which is defined inside a function.
program file.

Accessible throughout the program file. Accessible from the point it is defined to the end of
the block it is defined in.

Accessible to all functions in the program. They are not related in any way to other variables
outside the function.

x = 20
def fun():
x = 10
print("Local x =",x)
fun()
print("Global x =",x)

Output of above code is as follows:

Local x = 10
Global x = 20
Anonymous Functions or LAMBDA Functions
Modular programming is a way of organizing programs as they become more
complicated. we can create a Python module, a source file that contains Python source
code to do something useful, and then import this module into our program so that you
can use it.

Creation of Module:
mymodule.py
def greeting(name): Output:Hello,CRT
print("Hello, " + name)
Use of Module:
import mymodule
mymodule.greeting("CRT")
__init__() Method (Constructor)

def __init__(self, arg1, arg2, ...):


statement1
statement2
... class Box:
statementN def __init__(self, l, b):
self.length = l
self.breadth = b
def printdetails(self):
print("Length of box is:", self.length)
print("Breadth of box is:", self.breadth)
def display(self):
self.printdetails()
b = Box(10,20) Length of box is: 10
b. display() Breadth of box is: 20

You might also like