.
Previous Next

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

Previous Next