Interview Questions on Python

41. How to generate random number in python?

Example code :
from random import randint
print(randint(0,100))

42. Create singleton class in python?

# Singleton/SingletonPattern.py
class OnlyOne:
    class __OnlyOne:
        def __init__(self, arg):
            self.val = arg
        def __str__(self):
            return repr(self) + self.val
    instance = None
    def __init__(self, arg):
        if not OnlyOne.instance:
            OnlyOne.instance = OnlyOne.__OnlyOne(arg)
        else:
            OnlyOne.instance.val = arg
    def __getattr__(self, name):
        return getattr(self.instance, name)

x = OnlyOne('sausage')
print(x)
y = OnlyOne('eggs')
print(y)
z = OnlyOne('spam')
print(z)
print(x)
print(y)
print(`x`)
print(`y`)
print(`z`)

43. How to print the output in python?

Use print
Syntax :- print “Hello world”
Ex:- 
s =  'Hello world '
print s

44. How to use classes which are written in another file?

Imprt those classes as  ensioned below
from  filename import classname

45. What are the disadvantages of python?

1. Disadvantages of Python are:
i. Python isn't the best for memory intensive tasks.
ii. Python is interpreted language & is slow compared to C/C++ or java.
iii. Python not a great choice for a high-graphic 3d game that takes up a lot of CPU.

46. How to create threads in python?

Example code which creates thread
Ex :- 
from threading import Thread
class MyThread(Thread):
    def __init__(self):
        pass

47. How to parse an array in python by using for loop?

Ex :-
a = [1,2,3,4,5,6,67,78]
for i in a:
     print i

48. What is the use of pass?

It does nothing. 
If you don’t want to write any thing and if compiler shows any syntax error then you can use pass.

Python 41 - 48

Interview Questions on Python

31. How to write while loop in python?

Syntax :-
while expression:
   statement(s)
Ex :- 
count = 0
while (count < 9):
   print 'The count is:', count
   count = count + 1

32. How to write for loop in python?

Syntax :-
for iterating_var in sequence:
    statements(s)
Ex:-
for letter in 'Python':     # First Example
   print 'Current Letter :', letter
fruits = ['banana', 'apple',  'mango']
for fruit in fruits:        # Second Example
   print 'Current fruit :', fruit

33. How to pass command line arguments?

Syntax :-
python test.py arg1 arg2 arg3

34. How to get command line arguments legth?

Use len()
Ex :-
#!/usr/bin/python
import sys
print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)

35. How to print cmd line arguments?

Use sys.argv
Ex :-
#!/usr/bin/python
import sys
print 'Argument List:', str(sys.argv)
     for arg in str(sys.argv):        # Second Example
         print arg

36. How to open file in write mode?

Syntax :- open('file_name', 'w')
Ex :-  fo = open('file1.txt', 'w')

37. How to open file in read mode ?

Syntax :- open('file_name', 'r')
Ex :- fo = open('file1.txt', 'r')

38. How to create a file?

Open file in write mode. It will create file if it is not exist. But it will truncate the file if it is exist.

39. What happens if we use negative index in string?

A negative index accesses elements from the end of the list counting backwards.
An example to show negative index in python
>>> import array
>>> a= [1, 2, 3]
>>> print a[-3]

40. How to know whether the object is belongs to particular class or not?

Syntax :- isinstance(obj, MyClass)
Ex :- 
if isinstance(obj, MyClass):
     print "obj is my object"

Python 31 - 40

Interview Questions on Python

21. How to convert int to string?

Use str()
Syntax :- 
str(number);
Ex :-
str(23); // returns ‘23’

22. How to find the type of variable?

Use type()
Syntax :- type(i)
Ex :- 
i = 123
type(i)   //type is 'int'

23. How to reverse the string?

Syntax:- stringname[::-1]
Ex: -
s = "String to reverse."
print s[::-1];

24. How to get substring?

Syntax:- stringname[start_index : end_index]
Ex :- 
>>> s = 'Hello, everybody!'
>>> s[0]
'H'
>>> s[:3]
'Hel'
>>> s[2:5]
'llo'

25. How to get character from particular position of string?

Use find()
Syntax :- string1.find(“c”); # here c for character
Ex :-
s="mystring"
s.find("r")

Output : 4

26. How to get index of the string?

Use index()
Syntax :- string1.find(“c”); # here c for character
Ex :-
s="mystring"
s.index("r")

Output : 4

27. How to write if statement?

Syntax :- 
if conditional_Statement :
     #code 
Ex: -
if weight > 50:
        print("There is a $25 charge for luggage that heavy.")

28. How to write ternary operator?

 if  else 
Ex: - 
>>> age = 15
>>> # Conditions are evaluated from left to right
>>> print('kid' if age < 18 else 'adult')
Kid

29. Is there switch statement in python?

No

30. Is there goto statement in python?

No

Python 21 - 30

Interview Questions on Python

11. How to copy an object?

1. Shallow copy :
copy.copy(x)
Return a shallow copy of x.
2. Deep Copy :
copy.deepcopy(x)
Return a deep copy of x.

12. What is the difference b/w deep copy and shallow copy?

A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

13. How to call methods of an object?

By using . (dot)
Ex :- 
class Obj(object):
    def A(self, x):
        print "A %s" % x
    def B(self, x):
        print "B %s" % x
o = Obj()
 # normal route
o.A(1) 

14. How to create constructor?

Use 
def __init__(self, arguments):
      //code

15. How to import another python files in current files?

Syntax :- import filename

16. How to send a mail in python?

Php code :-
#!/usr/bin/python
import smtplib
sender = 'from@fromdomain.com'
receivers = ['to@todomain.com']
message = """From: From Person 
To: To Person 
Subject: SMTP e-mail test
This is a test e-mail message.
"""
try:
   smtpObj = smtplib.SMTP('localhost')
   smtpObj.sendmail(sender, receivers, message)         
   print "Successfully sent email"
except SMTPException:
   print "Error: unable to send email"

17. How to create a variable and initialize values for them?

Syntax :-  var_name = value;
Ex :- 
#!/usr/bin/python
counter = 100          # An integer assignment
miles   = 1000.0       # A floating point
name    = "John"       # A string
print counter
print miles
print name

18. How to create blocks in pyton?

Syntax :-
block_head: 
    1st block line 
    2nd block line 
Ex :-
def my_function():
    print "Hello From My Function!"

19. How to handle the exceptions in python?

Syntax :-
try:
    #try block code here
except ExceptionName:
     print "Exception Occured"
Ex :- 
(x,y) = (5,0)
 try:
   z = x/y
 except ZeroDivisionError, e:
       z = e # repr: ""  
      print z 

20. How to convert string to int?

Use int()
Syntax :- 
int('string_number');
Ex :-
int('23'); // returns 23

Python 11 - 20

Interview Questions on Python

1. What do you know about python?

Python is a general-purpose, object-oriented, and high-level programming language. It is simple and easy to learn
The Python interpreter is easily extended with new functions and data types implemented in C or C++ (or other languages callable from C).

2. Can we use python as interpreter?

Yes. Simply enter ‘python’ in shell and execute python code line by line.

3. How to declare local and global variables?

If you declare variables inside function then they are local.
If you declare out side function they are called global variables.

4. How to create and initialize array?

Create an Array :- 
    Syntax :- array_name = [];
Inialize values :-
    Syntax :- array_name[0] = “value”

5. How to create and initialize tuple?

Create an tuple:- 
    Syntax :- tuple_name = ();
Inialize tuple:-
    Syntax :- tup1 = ('physics', 'chemistry', 1997, 2000);

6. How to create and initialize dictionary?

Create an dictionary:- 
    Syntax :- dictionary_name = {};
Inialize dictionary:-
    Syntax :- dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

7. How to share common variables in multiple files?

Write all common variables in one file and import that file. To use the common variables.
Ex :- 
For example I want a, b & c to share between modules.
config.py :
a=0
b=0
c=0
module1.py: 
import config 
config.a = 1
config.b =2
config.c=3
print “ a, b & resp. are : “ , config.a, config.b, config.c

8. Explain about lamda in python?

Lamda is a  one line function. 
Ex :- 
k= lambda y: y + y
k(30) // returns 60

9. What is pickling and unpickling in python?

Pickling :- converts object  into a string representation writes it into a file.
UnPlickling :- it  is process of retrieving original python object from the stored string representation for use.

10. How to create an object in python?

Use classname followed by parenthesis
Ex :- 
class MyClass:
    """A simple example class"""
    i = 12345
    def f(self):
        return 'hello world'
x = MyClass() //creates object

Python 01 - 10