.
Previous

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.

Previous