Python Interview Questions

By | April 2, 2019

Python is one of the most versatile and powerful programming languages. It has a very bright future and promises many opportunities for its developer. So, whenever you go for a job as a Python Developer, you have to face the interview and the interviewer will ask many questions related to Python in order to check your level in python programming. Many times, we have seen that the interviewer asked questions related to the basic python and the candidate could not even able to give their answers and then they feel embarrassing and this results from demotivation for the candidate. Here in this article we have provided Top 100 question frequently asked in the python Interviews, that would help you to crack the Interview.

Python Interview Questions

Question: Who is the creator of Python?
Answer: Guido van Rossum

Question: What is Python?
Answer: Python Interview QuestionsPython is the most useful, high-level, object-oriented, interpreted programming language.

Question: What do you mean by interpreted programming language?
Answer: An interpreted programming language in which the code gets directly executed without compilation.

Question: Tell some benefits of Python.
Answer:

  • It is Dynamic language
  • It supports object-oriented programming languages
  • It does not have a concept of access modifiers like private, public, and protected but you can use magic functions to use the methods as public or private.
  • It has a very simple syntax which makes it easy to learn.
  • Apart from desktop application python is also used for web development.

[su_button url=”http://www.techgeekbuzz.com/python-ides-text-editor/” background=”#1263c6″ size=”8″ wide=”yes” center=”yes” radius=”round”]Top Best Python IDE for 2019[/su_button]

Question: What is a Dynamic type Language?
Answer: Unlike other programming languages in python for every variable, you do not need to declare its data type. That makes Python a Dynamic language.

E.g. var1=10 # var1 is an integer type
var2 =“Hello world” # var2 is a string

Question: Name the tool in python which is used to find Bugs
Answer: PyChecker and Pylint

Question: What pass keyword do and why do use it?
Answer: The pass is a special keyword in the python which performs the NULL operation when you execute a pass keyword nothing happens.

In python, if you declare an if statement or a function you have to define the function and the statement if you do not define them the python interpreter through an error. To overcome this error, you can use the pass keyword inside the if statements and functions.

e.g.

remove_h=”hello world”
for i in remove_h:
if i==h:
pass
else:
print(i)
#output
h
e
l
l
o
w
o
r
l
d

Question: Write code to get the current file directory.
Answer: import os

print(os.__file__)
#output
Users\user_name\AppData\Local\Programs\Python\Python37-32\lib\os.py

Question: Name all the inbuild datatype in python:
Answer: Python has 6 inbuilt data types

Numbers
Strings
List
Tuples
Dictionaries
Sets

Question: What are Mutable and Immutable Datatypes
Answer: Mutable are those data types in python whose value can be changed.

E.g. list, Dictionaries and Sets

Immutable are those data types once they have been assigned you cannot manipulate their values.

E.g. Strings, Tuples and Numbers

Question: Comment on Python Memory management.
Answer: Python interpreter handles the memory management. It uses private heaps to control and maintain the memory. In python the user does not get any access related to its memory management, python memory management takes control of all the memory action by itself. Python has an automatic garbage collector

Question: Write a code to convert 144 into a string
Answer:

str(144)

Question: What is a lambda function?
Answer: Lambda function is an anonymous function which can be written in a single line.

e.g.

# Normal function in python
def mul(a,b):
return a*b
mul(10,20)
#lambda function
mul=lambda a,b : a*b
mul(10,20)

Question: Give the main difference between tuple and list.
Answer: Tuples are immutable whereas lists are mutable.

e.g.

list1=[0,1,2,3,4] #list
tuple1=(0,1,2,3,4) #tuples
list1[2]=4 #Mutable
tuple1[2]=4 # it will through an error because tuples are immutable

Question: What is negative indexing in python??

Answer: Python data-types such as list, tuples and sets support the positive as well as negative indexing. In negative indexing, if you pass -1 index it will call the last value of the list or if you call -2 indexing it will the second last value of the list.

e.g.

list1=[0,1,2,3,4,5]
print(list1[-1])
print(list1[-2])

#outputs

5
4

[su_button url=”http://www.techgeekbuzz.com/python-vs-javascript/” background=”#1263c6″ size=”8″ wide=”yes” center=”yes” radius=”round”]Know the Deep Comparison Between Python or Javascript[/su_button]

Question: What are the methods of a class?
Answer: Methods are the functions, which are defined inside a class.

e.g

class Animal:
def method_1(self):
pass
def method_2(self):
print(“hello world”)

Question: What is a __init__ method?
Answer: __init__ method is a reserved method of a class is also known as the constructor of a class. Whenever you initialize any instance of a class the __init__ method automatically call.

E.g

class Animal:
def __init__(self):
print(“I am an Animal”)
def method_1(self):
pass
dog=Animal() #instance of a class

#Output

I am an Animal

Question: What are Exceptions in Python?
Answer: Exceptions are the errors occurs during execution of code.

Question: What Raises an Exception?
Answer: In python, you can raise an Error by using a statement raise and all the statement after it won’t execute.

e.g.

print(“hello”)
raise ValueError
print(“world”)

#output

hello
ValueError

Question: Does Python have a concept of inbuilt Array?
Answer: Python does have a list but they are not Arrays. Python does not have support for in-built array data type but you can use the array with the help of a third-party library Numpy.

Question: What range function does in python?
Answer: range() is a special function often use in python it is used to iterate over a number of the sequence. range function can accept 3 arguments initial state, last state and the steps taken to reach the last point.

e.g.

for i in range(2,10,2)
print(i)

#output

2
4
6
8

Question: What are dictionaries in python and how they are different from a list?
Answer: A dictionary is an in-built data type in python which consist of a pair of key and values separated by a colon(:).

#dictionary syntax:

dic= {“key1”: “value1”, “key2”:”value2”}

Dictionaries are the unorder collections of key and values whereas a list is an ordered collection of values.

In the list, we use the index to call a value but in dictionaries, we use keys to call the corresponding value.

Question: What error will be shown if you index a key that is not a part of the dictionary?
Answer: KeyError

Question: What is slicing in python?
Answer: Slicing gives more control to the user over a string or a list. With the help of slicing, you can retrieve any sequence of values that you want.

e.g

# List slicing
lis=[1, ”hello”,3, ”world”,5,6,7, ”I am”,”here”]
print(lis[2:6])
print(list[3:8:2])

#outputs

[3,”world”,5,6]
[“world”,6,”I am”]

Question: What is a class in python?
Answer: A class is a blueprint of an object or instance which consist of a set of methods and attributes. A class have no existence until its object or instance has made.

#syntax of a class
class Animal:
def method(self)
pass

Question: What are try and except statements?
Answer: Try and except statement are the part of exception handling. The try and except statements are similar to if and else statements but the difference is we use try and except statement for the error handling.

If you write a code for the try block and if it through an error the try block stop being executed and the interpreter directly jumps to the except block to execute its code.

#syntax for try and execute statements

try:
print(“hello world”)
print(“2”/3) #error
except:
print(“there is an error in the above statement”)

#output

hello world
there is an error in the above statement

[su_button url=”http://www.techgeekbuzz.com/java-vs-python/” background=”#1263c6″ size=”8″ wide=”yes” center=”yes” radius=”round”]Get Complete Detailed Analysis over Python vs Java[/su_button]

Question: What is an index in python?
Answer: In python to retrieve a specific value from a list, sting, or tuples we use the index. An Index is the integer which starts from 0 and every index corresponding to a value.

Question: What Assert statement does in python?
Answer: The assert statement checks whether the statement is True or False. If the assert statement is True nothing happens but if it is False the statement throws an AssertError.

e.g.

print(“hello”)
assert 2+2==4
print(“world”)
assert 2+2==5
print(“world”)

#output

hello
world

AssertionError

Question: What is the object of a class?
Answer: An object is an instance of a class and a tool to access the properties and method of the class.

Question: What open() and close() functions do in python?
Answer: open() function is used to open a text file for reading, writing and appending purpose.

When you open the file for reading, writing or appending you also need to close it so close function helps to close the open file.

Question: What does a map function do in python?
Answer: A map() is an inbuilt function in python which take 2 arguments. The 1st argument is the function and an iterable as its 2nd argument. The map function passes all the values of the iterable through the function one by one and at last return a list.

#syntax for the map()

def mul3(num):
return n*3
num=[1,2,3,4,5]
res=map(mul3,num)
print(list(res))

Question: How python can be used for web development?
Answer: Python has many frameworks like Django, flask, etc. which are used for web development, and you can simply get these frameworks by using pip install command.

Question: Explain filter() function.
Answer: filter() is an inbuilt function in python that is used to filter an iterable by removing items which do not match the predicate.

#filter syntax

lis=[10,23,24,25]
res=list(filter(lambda x: x%2==0,lis))
print(res)

#output

[10,24]

Question: What are predicates?
Answer: Predicates are those functions which return a Boolean

Question: Does python support procedural programming?
Answer: Yes, though python is known for its object-oriented programming, python does support the procedural programming.

Question: In python how can we use the third-party libraries?
Answer: To use the 3rd party libraries first we need to install those. You can go to the python documentation to install the libraries or you can use the pip install command to install the libraries.

Question: What is a function?
Answer: A function is a set of code which is used to perform a task. This help to enhance the reusability of code. In python to declare a function, we use a keyword def.

Question: How many types of Function does python have?
Answer: Like other programming, language python has 2 types of function

Built-in functions (functions already provided by the python)

User-defined functions

Question: If we declare a function and do not define it what will happen?
Answer: The python interpreter will throw an error.

[su_button url=”http://www.techgeekbuzz.com/python-vs-django/” background=”#1263c6″ size=”8″ wide=”yes” center=”yes” radius=”round”]Python vs Django[/su_button]

Question: If a function does not return anything will it throw an error?
Answer: No.

Question: What a break statement does?
Answer: A break statement terminates the loop statement and stop the iteration.

e.g.

#break syntax
for i in range(4):
if i==2:
break
print(i)

#output

0
1

Question: If a break statement uses inside the nested loop which loop it will terminate?
Answer: If we use a break statement inside a nested loop it will terminate the innermost loop.

Question: What do you understand by inheritance of class in python?
Answer: Inheritance is a way which helps to share the functionality of one class with another class. To inherit a class from another class we pass the base class name in the parentheses of derived or subclass.

Question: What are dunders in python?
Answer: Dunders are the special magic methods used in python which have 2 underscores at the beginning and end of their name. some e.g. of dunders methods are __init__, __str__, __del__,etc

What are the sets?
Answer: Sets are the unordered collections of data types which are immutable and do not accept the repetitive values. You are iterable but you cannot use index retrieve a value from a set.

#set syntax
sets={1,2,3,4,5,5,6,6,6,6}
print(sets)
#output:

{1,2,3,4,5,6} #it eliminates the repetitive values

Question: What are tuples?
Answer: Tuples are similar to a list, like the list in tuple we use indices to retrieve its values. The only difference is tuples are immutable whereas lists are mutable.

e.g.
tup=(1,2,3,4,5) # to declare a tuple we use parentheses
print(tup[2])

#output

3

Question: Can we use a list as a key of a dictionary?
Answer: No, the keys of the dictionary should be an immutable datatype such as tuples, strings or numbers.

Question: Why this statement often use in python if __name__==”__main__”: ?
Answer: __name__ is a special variable in the python which executes first before anything else. It uses with the if statement to check whether the file is executing directly or it’s being imported. If the file is running directly the __name__ variable will be automatically assigned “__main__” if not it assigned as the name of the file.

Question: What are *args?
Answer: *args is a special syntax which can accept a number of arguments pass to a function and treat those as a tuple.

e.g.

def arg(*args):
print(args)
print(type(args))
arg(1,2,3,4,5,6,7,8)

#output

(1,2,3,4,5,6,7,8)
<class ‘tuple’>

Question: What are **kwargs in python?
Answer: **kwargs are similar to *args, a special syntax which can accept a number of argument pass to function but in kwargs it treat the passed argument as a Dictionary.

e.g.

def kwa(**kwargs):
print(kwargs)
print(type(kwargs))
kwa(x=”hello”, y=”world”,z=4)

#output

{'x': 'hello', 'y': 'world', 'z': 4}
<class 'dict'>

Question: What does the end statement does in python?
Answer: Whenever we use a print() statement it always prints it on a new line. An end statement is an additional statement with the print() which have a value of ‘\n’ by default that’s why every print() statement print on a new line. We can manipulate the value of end to change the print statement format.

e.g.

print(“hello”, end=’ ‘)
print(“world”) #here end value id ‘\n’ by default
print(“go for”, end=”-“)
print(“it”)

#output

hello world
go for-it

Question: What is Django?
Answer: Django is one of the most widely used frameworks of Python.

Question: What does help() function do in python?
Answer: help() function show the documentation related to the object passed in the help parenthesis.

e.g.

lis=[1,2,3,4]
help(lis)

Question: What are list comprehensions in python?
Answer: A list comprehension is a method of creating a new list from an iterable.

E.g.

#List comprehension Syntax:
old_list=[1,2,3,4,5,6]
new_list=[i*2 for i in old_list]
print(new_list)

#output

[2, 4, 6, 8, 10, 12]

Question: What does a continue keyword do in python?
Answer: The continue statement jump back to the loop without executing the next statements.

#continue syntax

for i in range(10):
if i>3:
continue
print(i)

#output

0
1
2
3

Question: What ord() and chr() functions do in python?
Answer: The ord() return an ASCII code of the argument pass in it. Whereas the chr() perform adverse of ord(), it returns the corresponding value for the given ASCII code.

e.g.

print(ord(‘a’))
print(chr(97))
</pre.
#output

97
‘a’

Question: What does isaplha() function do in python?
Answer: isalpha() is a special method used to check whether the given string containing only alphabets or not. If the string contains only alphabets the method will return true else it will return False.

e.g.
print(“Hello”.isalpha())
print(“Hello 2”.isalpha())

#output

True
False

Question: What does a split() function do?
Answer: split() is a function used with a string to get a list out of it. By default, the split function split the string into list values by using the white space.

e.g.

str=’hello world I am here’
print(str.split())
print(str.split(‘e’))

#output
[‘hello’, ‘world’, ‘I’, ‘am’, ‘here’]
[‘h’, ‘llo world I am h’, ‘r’, ”]

Question: What does title() and join() function do in python?
Answer: The title() function used with the string and it uppercase the first letter of each word and lowercase the rest.

The join() function used with tuples and list and it helps to join all the values of tuple or list altogether and return a string.

e.g

jlist=['1','2','3']
print("".join(jlist))
str="helLO woRld"
print(str.title())

#Output

123

Hello World

Question: What is Python GIL?
Answer: GIL stands for Global Interpreter Lock, and it is a muter or lock which allow only one thread to hold the control of the Python interpreter.

Question: How the python list is different from a linked list.
Answer: The Python list uses the contiguous memory location to store the list values like an array, whereas the linked List values do not store in a contiguous memory location.

Question: Name the library used to generate a random number?

Answer: Random Library

e.g.

from random import randint
print(randint(1,10))

#output

3

Question: What is recursion?
Answer: Recursion is a concept in which a function call itself it is also known as self-reference.

e.g.

#Recursion Syntax in python
def fac(n):
if n==1:
return 1 # Base Case
else:
return n*fac(n-1)
print(fac(3))

#output

Question: What is the base case of recursion and why do we need it?
Answer: A base case in a recursion refers to that statement that does not allow the function to further call itself. A base case is necessary for each recursion if you do not provide a base case to the recursion it will throw infinite results.

Question: How errors are different from the exception in python?
Answer: Error rise in a program due to some coding issue while exception occurs due to an interruption in the program by unusual inputs.

Question: What does for loop works in python.
Answer: For loop use an iterator to move from one point to another, it iterates from one value to the last of the iterators.

Question: Can we directly access a function which is defined inside another function?
Answer: No.

Question: What are decorators in python?
Answer: Decorators are one of the most powerful tools of python, which allow wrapping a function or class into another function to enhance its functionality.

Question: What would be the output of this code?

lis=[1,2,3,”hello”,”world”]
print(lis[-1])

Answer: “world”

Question: What is a floor division?
Answer: It is similar to the normal division but in this, we use double division sign to divide two integers and it returns an integer.

e.g.

print(6//9) #floor division
print(6/9) # Normal division

#output

0

0.6666666666666666

Question: What are the Generators in python?
Answer: Generators are similar to the iterators such as list and tuples, which can be iterate with the help of for loop. To create a generator, we use functions and a special statement called yield. In simple words, generators are the function which yield output instead of returning.

#Generator Syntax

def rev():
def rev():
i=4
while i>0:
yield i
i=i-1
for i in rev():
print(i)

#Output

4
3
2
1

Question: What does yield statement do in python?
Answer: Yield statement used to define a generator, in the normal function we use return statement but in generators, we use yield statement to retrieve a result from a generator.

Question: How yield statement is different from return?
Answer: When we call a function if it has a yield statement then it will provide a sequence of result whereas a return statement will provide a specific value. A return statement terminates the function whereas the yield cannot.

Question: Write a code which show an equivalence to this code my_fun=my_dec(my_fun)
Answer: @my_dec

Question: What is NumPy?
Answer: Numpy is a very powerful and widely used package in python. The NumPY package id highly used for the data science and scientific research.

Question: What is a Docstring in python?
Answer: Docstring means documentation string and it is used to provide some additional information regarding the Python modules, Functions, Classes and Methods.

Question: What do we do to copy an object in python?
Answer: To copy an object, we use a copy module.

Question: What will be the output of the following code?

lis1=[1,2,3,4,5]
lis2=lis1
lis1[3]=40
print(lis2[3])

#Output

40

Question: What self-variable does in python classes?
Answer: self is a conventional variable which is used as the first argument of every class method and it is used to hold the instance of the object.

Question: What are ternary operators in python?
Answer: Ternary operators are similar to the conditional operator and provide an alternative method to write the conditional operator code.

e.g.
x= 35
y=75
min = x if x < y else y
print(min)

#output

35

Question: What is functional programming?
Answer: In functional programming we can use a function as an argument and pass it to the another function.

e.g.

#Functional Programming
def fun1(fun2,arg):
return fun2(fun2(arg))
def mul(n):
return n*2
print(fun1(mul,10))

#Output

40

Question: What does del() function do in python?
Answer: The del() function is used to delete the object.

Question: What phenomena use when you transverse through a dictionary object in python?
Answer: Tuple unpacking

#Output key is key1 and values is val1 key is key2 and values is val2 key is key3 and values is val3 Question: Can we define a class inside a class in python? Answer: Yes. OUTPUT Questions Question: What would be the output of this code print(“5”*4) Answer: #output 5555 Question: What would be the output of the following code a,b,*c=[1,2,3,4,5] print(a) print(b) print(c) Answer: #output 1 2 [3, 4, 5] Question: what would be the output? lis=[1,2,3,4,5,6,7] for i in range(4):

  lis.pop(i)
print(lis)

Answer: #Output

[2, 4, 6]

Question: what would be the output of the following code?

lis=[[]]*3
lis[0].append(4)
print(lis)

Answer:

#Output

[[4], [4], [4]]

Question: what would be the output of the following code?

Lis1=[1,2,3,4]
Lis2=[1,2,3,4]
print(Lis1==Lis2)
print(Lis1 is Lis2)

Answer:

#Output

True
False

Question: What would be the Output of the following Code?

lis=[10,3,20,19,4]
print(lis.sort())

# OUTPUT

None

Question: What would be the output of the following code?
print(bool(3<4)*20)

Answer:

#Output

20

Question: What would be the output of the following code?
print(“70’+’33”)

#Output

70’+’33

Question: What would be the output of the following code?

lis=[1,2,3,4,5,6,7]
a=lis.sort()
b=sorted(lis)
if a==b:
  print(True)
else:
  print(False)

Answer:

#Output

False

Question: Write code to add a delay of 1 min.
Answer:

Question: What would be the output of the following code?

lis1,lis2=[1,2,3],[1,2,3]
if id(lis1)==id(lis2):
  print(True)
else:
  print(False)

Answer:

#Output

False

Question: What would be the output of the following code?

lis1=[1,2,3]
lis2=lis1
del(lis1)
print(lis2)

Answer:

#Output

[1, 2, 3]

Question: What would be the output of the following code?

print(3**1**2**4)

#Output

3

Question: What would be the output of the following code?

def re():
return "Hello"
print("Hello2")
print(re())

Answer:

#Output
Hello”

Question: What would be the Output of the following code?

lis=["1100110011001100","11001100"]
if lis[1]in lis[0]:
  print("yes")
else:
  print("No")

Answer:

#Output
Yes

Question: What would be the output?

print([1,2,3]*3)
Answer:

#Output

[1, 2, 3, 1, 2, 3, 1, 2, 3]

Question: Name some main Features of Python for which it is Popular.
Answer:

  1. It supports the Functional and structured Programming language, also follows the concepts of OOP’s.
  2. It is a Dynamic language.
  3. It has a feature of Automatic Garbage collection.
  4. It is very easy to interpret.

Question: What is Python?
Answer: Python is a high level, interpreted, dynamic, and Object-oriented Programming language. It is written in the English language which makes it easier to read and understand.

Question: What is lambda in Python?
Answer: Lambda is a special function of Python which allows you to write a function in a single line.

Question: What for keyword does in Python?
Answer: for is a loop which iterates a group of elements basically list.

Question: What is slicing a list or string?
Answer: Slicing a list or String means to select a specific range in a given sequence.

Question: What is the main difference between list and tuples?
Answer: lists are mutable its mean that you can change the value of lists but tuples are immutable you cannot change the values of tuples.

Question: What help() and dir() functions do?
Answer: help() function used to display the documentation string of the object which is placed inside the help function parenthesis.

While dir() function used to display the defined symbol and it returns None.

Question: Name the type of error for this syntax:

>>> k=14
>>> l = ”hello world”
>>> print(k+l)

Answer: TypeError, you cannot concatenate an integer and string directly, to do so you have to change the type of integer to string first.

Question: What is string concatenation and why do we use it?
Answer: String concatenation is a method which concatenates two strings. It’s used to combine two strings together.

E.g.
>>> k= “hello”
>>> l= “world”
>>> p= k+l #string concatenation:
>>> print(p)

#output will be >>> helloworld

Question: What are Dictionaries in Python?
Answer: Dictionaries are the collections of keys and their corresponding values inside the curly braces.

E.g.
>>> dict = {“one”: “its one”, “two” : ” its two”, “three” : “its three”}
>>> print( dict[“two”]) # here we are calling the dict value “its two” using key “two”
>>> its two # output

Question: How to convert any object to a string?
Answer: To convert any object to the string we use simple function str(); consider x is an object so to convert it to string we will write this statement str(x).

Question: What is mutable built-in type in python?
Answer: There are some built-in types in Python which are mutable. By mutable means, their value can be manipulated which is already assigned.

Some examples of Mutable built-in types are:

  • List
  • Sets
  • Dictionaries

[su_button url=”http://www.techgeekbuzz.com/top-20-most-frequent-asked-python-interview-questions-intermediate/” background=”#1263c6″ size=”8″ center=”yes” radius=”round”]Python Interview Questions for Intermediate Level Developer[/su_button]

Question: Define immutable built-in type with its examples.
Answer: Immutable are those built-in type which value cannot be changed once it assigned.

Some examples of Immutable built-in types:

  • String
  • Tuples
  • Numbers

Question: What pass keyword do?
Answer: When you use pass keyword in your code it simply means that pass the just above statement or function and perform no operation. pass used when you need to leave some statement or function and want no operation to perform because python is an interpreted language and if you just leave any statement or function blank without any explanation it will show an error, so to ignore the error we use pass keyword.

Question: Java is Static Data type and Python is Dynamic data type explain it.
Answer: When we use java we have to define the data type for each variable before we declare the variable which makes the Java a static type. But in Python we do not need to define the data type of each variable, so Python is a Dynamic type.

Question: Comment on how memory managed in Python.
Answer: All the python memory is managed by Python Private Heap Space, all the data structure and Object are located in Private Heap and the Programmer does not have the access to the Private heap. It is Python Interpreter which takes the full care of the Private heap.

Question: What are the Local variables?
Answer: When a variable is assigned inside a function is known as Local variable and only that specific function is allowed to use that variable.

Question: What are the global variables?
Answer: All those variables that can be referenced by the function by using global keyword.

Question: What is Django?
Answer: Django is a Full-stack web framework which is written on python and used to develop the dynamic web application.

Question: What are the module and packages in Python?
Answer: Module: Module is the Python Program file that can be imported to other python Program by using import keyword

Packages: Packages are the folders which contain a bunch of python module and subfolders. Subfolders also contain modules.

Question: What split() function do.
Answer: split() function is basically used for split the string into a list

Question: What are Django, Pyramid, and flask in Python?
Answer: Django: Django is a full stack Python web-framework.

Pyramid: Pyramid is also a Python web-framework which is used to build large web applications.

Flask: flask is a python microframework which is basically used to build small web applications.

Question: What is map() function does in Python?
Answer: the map function accepts 2 arguments the first argument can be a function or statement and the 2nd argument is the type which iterates through the first argument.

Question: what is “None” often used to Represent?
Answer: Absence of value.

Question: What will be the output of this code?
foo= print()

if foo==None:
print(1)
else:
print(2)

Answer: 1

Question: What is floor division?
Answer:  the symbol of the floor division is “//” double division sign it basically divide one value with another and give the answer an integer value.

e.g.

p= 12//5
print(p)

2   #output

[su_button url=”http://www.techgeekbuzz.com/python-frameworks/” background=”#1263c6″ size=”8″ center=”yes” radius=”round”]Check here Python Frameworks[/su_button]

Question: Does python have a compiler?
Answer: Yes, python does a have the compiler. It’s works automatically.

Question: Name all data type used in Python.
Answer: 1. Integer

  1. String
  2. List

4.Tuple

  1. Dictionary

Question: Write the statement to reverse the list.
Answer: list.reverse()

Question: What are all the file processing mode in python?
Answer: 1. “r”= Used for reading the file

  1. “w”= used for write and overwrite on in the file or create the new file.
  2. “rw”= use for both read and write simultaneously
  3. “a”= it used for append the file and can create a new file too.

Question: Explain the concept of *args and ** kwargs.
Answer: *args , It is a special kind of function definition which is used to pass multiple variables as arguments to the function. *args basically used when you are not sure about how many arguments passeds to the function.

# *args syntax:
def fun(*agrs): #here args is a variable you can choose other variable name too instead of args.
for i in args:
print(i)
fun(“hellow”,”world”,”its” ,“an”, “args”,”function”)
# output
hellow
world
its
an
args
function

**kwargs: It is special kind of function in python which allow the user to mass multiple argument in the function. But in **kwargs the argument passes in the function as dictionaries.

# e.g of **kwargs:

def fun(**kwargs):
For k,v in kwargs.items():
Print(str(k) + “value is “+ str(v)
fun(k1=”value 1”,k2=”value 2”,k3=”value 3”)

#output

k1 value is value 1
k2 value is value 2
k3 value is value 3

Question: How the Python interpreter work?
Answer: The Python interpreter consists two things one is compiler and second is a virtual machine. First, the compiler takes your source code and convert it into Byte code. Byte code is simply a lower level code which is platform independent. Then the byte code is fed into the PVM(Python Virtual Machine). The PVM execute the Byte code and give the output.

Question: Explain the .py and .pyc file extension.
Answer: the .py is the file extension of the Python programme, and .pyc is the file extension of the compiled byte code file which is generated by python.

Question: What is an Exception in python?
Answer: Exception can be defined as an event that occur due to incorrect code or input.

Question: What we use to deal with the exception?
Answer: to avoid the exception we can use try/except statement. If any exception occur, the code in try block stop execution and the code in the except block start to run.

# e.g.

try:
i=2
j=0
print(i/j)
except ZeroDivisionError:
print(“error has occurred because of zero division”)

#output

an error has occurred because of zero division

Question: What is raise an exception?
Answer: to raise the exception and terminate the programme we can use raise exception statement.

# e.g.

print(45)
raise ValueError
print(34)
#output

45

ValueError

Question: Write all errors occurred in python.
Answer: Import error: it occurs when import statement fails

IndexError: when indexing of any list fails

NameError: undefined or unknown variable

SyntaxError: when the code is not written properly

TypeError: when an unappropriated variable is call.

ValueError

There are many other exception or error in python. There are several exceptions in the third party libraries.

Question: What is NumPy?
Answer: it is a fundamental package which is basically used for scientific computation with Python.

Question: Give some main features of NumPy.
Answer: 1. It has a powerful N-dimensional array

  1. shophisticatd functions
  2. tools for integrating c/c++ and Fortran code
  3. useful linear algebra, Fourier transform, and random number capabilities.

Question: What is list comprehensions?
Answer: List comprehension is a method which can make the list in a concise way.

#e.g

Lis=[i*I for i in range(10) if i%2==0]

Question: What is the difference between xrange() and range()?
Answer: both range() and xrange() shear the same properties, but the main difference occur in their return type. xrange() return the xrange object but the range return the list object.

Leave a Reply

Your email address will not be published. Required fields are marked *