Python Interview Questions and Answers Set 4

31. What is __init__.py?

It is used to import a module in a directory, which is called package import.

32. Print contents of a file ensuring proper error handling?

try:

withopen(‘filename’,’r’)asf:

printf.read()

exceptIOError:

print”No such file exists”

33. How do we share global variables across modules in Python? 

We can create a config file and store the entire global variable to be shared across modules in it. By simply importing config, the entire global variable defined will be available for use in other modules.

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)

Output of module1.py will be

123

34. Does Python support Multithreading?

Yes

35. How do I get a list of all files (and directories) in a given directory in Python?

Following is one possible solution there can be other similar ones:­

import os

for dir name,dirnames,filenames inos.walk(‘.’):

# print path to all subdirectories first.

for subdirname in dirnames:

print os.path.join(dirname,subdirname)

# print path to all filenames.

for filename in filenames:

printos.path.join(dirname,filename)

# Advanced usage:

# editing the ‘dirnames’ list will stop os.walk() from recursing into there.

if ‘.git’ in dirnames:

# don’t go into any .git directories.

dirnames.remove(‘.git’)

36. How to append to a string in Python?

The easiest way is to use the += operator. If the string is a list of character, join() function can also be used.




37. How to convert a string to lowercase in Python?

use lower() function.

Example:

a=’MYSTRING’

print.lower(a)

38. How to convert a string to lowercase in Python?

Similar to the above question. use upper() function instead.

39. How to check if string A is substring of string B?

The easiest way is to use the in operator.

‘abc’ in ‘abcdefg’

True

40. Find all occurrences of a substring in Python

There is no simple built­in string function that does what you’re looking for, but you could use the more powerful regular expressions:

>>>[m.start()form inre.finditer(‘test’,’test test test test’)] [0,5,10,15]

// these are starting indices for the string.