Phython Interview Questions and Answers
Phython Interview Questions and Answers
1. Compare Java & Python Criteria Java Python Ease of use Good Very Good Speed of coding Average Excellent Data types Static typed Dynamically typed Data Science & machine learning applications Average Very Good 2. How are the functions help( ) and dir( ) different? These are the two functions that are accessible from the Python Interpreter. These two functions are used for viewing a consolidated dump of built-in functions. • help( ) – it will display the documentation string. It is used to see the help related to modules, keywords, attributes, etc. To view the help related to string datatype, just execute a statement help(str) – it will display the documentation for ‘str, module. ? Eg: >>>help(str) or >>>help() – it will open the prompt for help as help> • to view the help for a module, help> module module name Inorder to view the documentation of ‘str’ at the help>, type help>modules str • to view the help for a keyword, topics, you just need to type, help> “keywords python- keyword” and “topics list” • dir( ) – will display the defined symbols. Eg: >>>dir(str) – will only display the defined symbols. 3. Which command do you use to exit help window or help command prompt? quit When you type quit at the help’s command prompt, python shell prompt will appear by closing the help window automatically. 4. Does the functions help( ) and dir ( ) list the names of all the built_in functions and variables? If no, how would you list them? No. Built-in functions such as max( ), min ( ) , filter( ), map( ), etc is not apparent immediately as they are available as part of standard module.To view them, we can pass the module ” builtins ” as an argument to “dir( )”. It will display the built-in functions, exceptions, and other objects as a list.>>>dir(__builtins ) [‘ArithmeticError’, ‘AssertionError’, ‘AttributeError’, ……… ] 5. Explain how Python does Compile-time and Run-time code checking? Python performs some amount of compile-time checking, but most of the checks such as type, name, etc are postponed until code execution. Consequently, if the Python code references a user -defined function that does not exist, the code will compile successfully. In fact, the code will fail with an exception only when the code execution path references the function which does not exists. 6. Whenever Python exists Why does all the memory is not de-allocated / freed when Python exits? Whenever Python exits, especially those python modules which are having circular references to other objects or the objects that are referenced from the global namespaces are not always de – allocated/freed/uncollectable. It is impossible to deallocate those portions of memory that are reserved by the C library. On exit, because of having its own efficient clean up mechanism, Python would try to deallocate/ destroy every object. 7. Explain Pythons zip() function.? zip() function- it will take multiple lists say list1, list2, etc and transform them into a single list of tuples by taking the corresponding elements of the lists that are passed as parameters. Eg: list1 = [A, B,C] and list2 = [10,20,30]. zip(list1, list2) # results in a list of tuples say [(A,10),(B,20),(C,30)] whenever the given lists are of different lengths, zip stops generating tuples when the first list ends. 8. Explain Pythons pass by references Vs pass by value . (or) Explain about Pythons parameter passing mechanism? In Python, by default, all the parameters (arguments) are passed “by reference” to the functions. Thus, if you change the value of the parameter within a function, the change is reflected in the calling function.We can even observe the pass “by value” kind of a behaviour whenever we pass the arguments to functions that are of type say numbers, strings, tuples. This is because of the immutable nature of them.
9. As Everything in Python is an Object, Explain the characteristics of Pythons Objects. • As Python’s Objects are instances of classes, they are created at the time of instantiation. Eg: object-name = class-name(arguments) • one or more variables can reference the same object in Python • Every object holds unique id and it can be obtained by using id() method. Eg: id(obj-name) will return unique id of the given object. every object can be either mutable or immutable based on the type of data they hold. • Whenever an object is not being used in the code, it gets destroyed automatically garbage collected or destroyed • contents of objects can be converted into string representation using a method 10. Explain how to overload constructors or methods in Python. Python’s constructor – _init__ () is a first method of a class. Whenever we try to instantiate a object __init__() is automatically invoked by python to initialize members of an object. 11. Which statement of Python is used whenever a statement is required syntactically but the program needs no action? Pass – is no-operation / action statement in Python If we want to load a module or open a file, and even if the requested module/file does not exist, we want to continue with other tasks. In such a scenario, use try-except block with pass statement in the except block. Eg: try:import mymodulemyfile = open(“C:myfile.csv”)except:pass 12. What is Web Scraping? How do you achieve it in Python? Web Scrapping is a way of extracting the large amounts of information which is available on the web sites and saving it onto the local machine or onto the database tables. In order to scrap the web:load the web page which is interesting to you. To load the web page, use “requests” module. parse HTML from the web page to find the interesting information.Python has few modules for scraping the web. They are urllib2, scrapy, pyquery, BeautifulSoap, etc. 13. What is a Python module? A module is a Python script that generally contains import statements, functions, classes and variable definitions, and Python runnable code and it “lives” file with a ‘.py’ extension. zip files and DLL files can also be modules.Inside the module, you can refer to the module name as a string that is stored in the global variable name . A module can be imported by other modules in one of the two ways. They are 1. import 2. from module-name import 14. Name the File-related modules in Python? Python provides libraries / modules with functions that enable you to manipulate text files and binary files on file system. Using them you can create files, update their contents, copy, and delete files. The libraries are : os, os.path, and shutil. Here, os and os.path – modules include functions for accessing the filesystem shutil – module enables you to copy and delete the files. 15. Explain the use of with statement? In python generally “with” statement is used to open a file, process the data present in the file, and also to close the file without calling a close() method. “with” statement makes the exception handling simpler by providing cleanup activities. General form of with: with open(“file name”, “mode”) as file-var: processing statements note: no need to close the file by calling close() upon file-var.close() 16. When does a dictionary is used instead of a list? Dictionaries – are best suited when the data is labelled, i.e., the data is a record with field names. lists – are better option to store collections of un-labelled items say all the files and sub directories in a folder. List comprehension is used to construct lists in a natural way. Generally Search operation on dictionary object is faster than searching a list object.
17. What is the use of enumerate() in Python? Using enumerate() function you can iterate through the sequence and retrieve the index position and its corresponding value at the same time. >>> for i,v in enumerate([‘Python’,’Java’,’C++’]): print(i,v) 0 Python 1 Java 2 C++ 18. How many kinds of sequences are supported by Python? What are they? Python supports 7 sequence types. They are str, list, tuple, unicode, bytearray, xrange, and buffer. where xrange is deprecated in python 3.5.X. 19. Explain split(), sub(), subn() methods of To modify the strings, Python’s “re” module is providing 3 methods. They are: split() – uses a regex pattern to “split” a given string into a list. sub() – finds all substrings where the regex pattern matches and then replace them with a different string subn() – it is similar to sub() and also returns the new string along with the no. of replacements. 20. How to display the contents of text file in reverse order? 1. convert the given file into a list. 2. reverse the list by using reversed() Eg: for line in reversed(list(open(“file-name”,”r”))): print(line)
Top