/    /  Python – Interview Questions Part 5

1. How can you copy an object in Python?

Answer: To copy an object in Python,

1. you can try copy.copy () or copy.deepcopy() for the general case.

2. You cannot copy all objects but most of them.

 

2. Explain with example how can convert a number to a string?

Answer: To convert a number into a string, we can use the inbuilt function str().  For octal or hexadecimal representation, use the inbuilt function oct() or hex().

def convert_num_to_str(num):

str_num = str(num)

return str_num

# def convert_num_to_str(3) --> should return "3"

 

3. What is the difference between range and Xrange?

Answer. Range returns the list, and uses the same memory and no matter what the range size is, whereas Xrange returns the xrange object, as it I s much gentler in its memory demands.

 

4. Explain how to delete a file in Python?

Answer: We can delete a file in python by using a command os.remove (filename) or os.unlink(filename).

1. First check whether file exists or not .

2. If os.path.exists(file1.txt):

3. OS.remove(file1.txt)

 

5. Explain how can you generate random numbers in Python?

Answer: In Python we can generate random numbers by using import random

and  random.random() commands.

>>> import random

>>> random.random()

0.3819123032048318

>>> random.random()

0.7228310542996397

 

6. Is It Mandatory For A Python Function To Return A Value?

Answer: It is not at all necessary for a function to return any value. Hence, if needed, we can use none as a return value.

 

7. What Is The Purpose Of Id() Function In Python?

Answer: The id() is one of the built-in functions in Python.

Example: Signature: id(object)

It accepts one parameter and returns a unique identifier associated with the input object.

 

8. What Does The Len() Function Do In Python?

Answer: In Python, the len() is a primary string function. It determines the length of an input string.

>>> some_string = ‘Tutorials’>>> len(some_string)9

9. What Is Whitespace In Python?

Answer: Whitespace represents the characters that we use for spacing and separation. They possess an “empty” representation. It could be a tab or space in python.

 

10. What are the tools that help to find bugs or perform static analysis?

Answer: PyChecker is tool that detects the bugs in Python source code and warns about the style and complexity of the bug.