Ads Here

Saturday, December 11, 2021

 Python Interview Questions and Answers Series 

#1 Nadia Khodaei 11-2-2021 Python Interview Questions and Answers 

1) What makes Python so popular?

 • Easy to use– Python is a high-level programming language that is easy to use, read, write and learn. • Interpreted language– Since python is interpreted language, it executes the code line by line and stops if an error occurs in any line. • Dynamically typed– the developer does not assign data types to variables at the time of coding. It automatically gets assigned during execution. • Free and open source– Python is free to use and distribute. It is open source. • Extensive support for libraries– Python has vast libraries that contain almost any function needed. It also further provides the facility to import other packages using Python Package Manager(pip). • Portable– Python programs can run on any platform without requiring any change. • The data structures used in python are user friendly. • It provides more functionality with less coding. 2) How Python is interpreted? Python language is an interpreted language. Python program runs directly from the source code. It converts the source code that is written by the programmer into an intermediate language, which is again translated into machine language that has to be executed. 3) What is an Interpreted language? An Interpreted language executes its statements line by line. Languages such as Python, Javascript, R, PHP, and Ruby are prime examples of Interpreted languages. Programs written in an interpreted language runs directly from the source code, with no intermediary compilation step. 4) What is PYTHONPATH in Python? PYTHONPATH is an environment variable which the user can set to add additional directories that the user wants Python to add to the sys.path directory list. In short, we can say that it is an environment variable that you set before running the Python interpreter. 5) Is Python fully object oriented? Python supports all the concept of "object-oriented programming" but it is NOT fully object oriented because - The code in Python can also be written without creating classes. 6) Differentiate between NumPy and SciPy? Python Interview Questions and Answers Numpy Scipy NumPy stands for Numerical Python SciPy stands for Scientific Python It is used for efficient and general numeric computations on numerical data saved in arrays. E.g., sorting, indexing, reshaping, and more This module is a collection of tools in Python used to perform operations such as integration, differentiation, and more There are some linear algebraic functions available in this module, but they are not full-fledged. Full-fledged algebraic functions are available in SciPy for algebraic computations. 7) What is the difference between lists and tuples? List and Tuple in Python are the class of data structure. The list is dynamic, whereas the tuple has static characteristics. • List is just like the arrays, declared in other languages. Lists need not be homogeneous always which makes it the most powerful tool in Python. In Python, the list is a type of container in Data Structures, which is used to store multiple data at the same time. Lists are a useful tool for preserving a sequence of data and further iterating over it. list_data = ['an', 'example', 'of', 'a', 'list'] • Tuple is also a sequence data type that can contain elements of different data types, but these are immutable in nature. In other words, a tuple is a collection of Python objects separated by commas. The tuple is faster than the list because of static in nature. tuple_data = ('this', 'is', 'an', 'example', 'of', 'tuple') 8) How will you reverse a list in Python? Python Interview Questions and Answers Output: [5,4,3,2,1] 9) Why is finalize used? Finalize method is used for freeing up the unmanaged resources and clean up before the garbage collection method is invoked. This helps in performing memory management tasks. 10) What is PEP 8? PEP 8 exists to improve the readability of Python code. It is a document that provides guidelines and best practices on how to write Python code. Example of using PEP 8: ❖ Naming Conventions ❖ Code Layout ❖ Indentation ❖ Comments ❖ Whitespace in Expressions and Statements Coding example: Python Interview Questions and Answers 11) How is Memory managed in Python? • Memory in Python is managed by Python private heap space. All Python objects and data structures are located in a private heap. This private heap is taken care of by Python Interpreter itself, and a programmer doesn’t have access to this private heap. • Python memory manager takes care of the allocation of Python private heap space. • Memory for Python private heap space is made available by Python’s in-built garbage collector, which recycles and frees up all the unused memory. 12) What is the usage of help () and dir() function in Python? • dir() tries to return a valid list of attributes of the object it is called upon. Also, dir() function behaves rather differently with different type of objects, as it aims to produce the most relevant one, rather than the complete information. Output: ['customer_name', 'date', 'price', 'product', 'quantity'] • The help() function is used to display the documentation string and also facilitates you to see the help related to modules, keywords, attributes, etc. Output: math. pow = pow(x, y, /) Return x**y (x to the power of y). 13)What is the purpose of is, not and in operators? Operators are referred to as special functions that take one or more values(operands) and produce a corresponding result. • is: returns the true value when both the operands are true (Example: “x” is ‘x’) Python Interview Questions and Answers • not: returns the inverse of the boolean value based upon the operands (example:”1” returns “0” and vice-versa. • In: helps to check if the element is present in a given Sequence or not. 14)How does inheritance work in python? Inheritance refers to defining a new class with little or no modification to an existing class. The new class is called derived (or child) class and the one from which it inherits is called the base (or parent) class. 15) What are the tools that help to find bugs or perform the static analysis? PyChecker is a static analysis tool that detects the bugs in Python source code and warns about the style and complexity of the bug. Pylint is another tool that verifies whether the module meets the coding standard. Example: import pychecker.checker pychecker [options] file1.py file2.py 16) What do you mean by Python literals? Literals refer to the data which will be provided to a given in a variable or constant. List of literlas: • String Literals: These literals are formed by enclosing text in the single or double quotes: “SARA”, ‘45879’ • Numeric Literals: Integer: x=5, Float: x=5.2, Complex:1.73j • Boolean literals: help to denote boolean values. It contains either True or False: x=True 17) What is Scope in Python? The scope defines the accessibility of the python object. To access the particular variable in the code, the scope must be defined as it cannot be accessed from anywhere in the program. The particular coding region where variables are visible is known as scope. 18) What does Len () do? Len () is an inbuilt function used to calculate the length of sequence like list, string and array Python Interview Questions and Answers Example: 19)Types of Scope in Python? • Local Scope The Variables which are defined in the function are a local scope of the variable. These variables are defined in the function body. Example: Output: 1 • Global Scope The Variable which can be read from anywhere in the program is known as a global scope. These variables can be accessed inside and outside the function Example: output: you are clever you are smart you are smart • Nonlocal or Enclosing Scope Nonlocal Variable is the variable that is defined in the nested function. It means the variable can be neither in the local scope nor in the global scope. Example: Python Interview Questions and Answers Output: inner: nonlocal outer: local • Built-in Scope If a Variable is not defined in local, Enclosed or global scope, then python looks for it in the built-in scope. Example: output: 3.1415926523 20) What are the common built-in data types in Python? • Numeric Types • Sequence Types • Mapping Types • Set Types Python Interview Questions and Answers 21) Explain how can you generate random numbers in Python? 22) How can you randomize the items of a list in place in Python? Output: ['Maria', 'SARA', 'Paria', 'Sina', 'Mina', 'Nadia'] 23) What is type conversion in Python? Type Conversion is classified into types: • Implicit Type Conversion: In this form of Type conversion python interpreter helps in automatically converting the data type into another data type without any User involvement. • Explicit Type Conversion: In this form of Type conversion the data type inn changed into a required type by the user. Various Functions of explicit conversion: • int () – function converts any data type into integer. • float () – function converts any data type into float. • ord () – function converts characters into integer. • hex () – function converts integers to hexadecimal strings. • oct () – function converts integer to octal strings. • tuple () – function convert to a tuple. • set () – function returns the type after converting to set. • list () – function converts any data type to a list type. • dict () – function is used to convert a tuple of order (key, value) into a dictionary. • str () – function used to convert integer into a string. Python Interview Questions and Answers • complex (real, imag) – function used to convert real numbers to complex (real, imag) numbers. 24) What are Dict and List comprehensions? • List comprehensions provide a more compact and elegant way to create lists than for-loops, and also allow you to create lists from existing lists. Example: Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Output: ['3.1', '3.14', '3.142', '3.1416', '3.14159'] • Dictionary comprehensions are very similar to list comprehensions – only for dictionaries. They provide an elegant method of creating a dictionary from an iterable or transforming one dictionary into another. Example: output: {2: 4, 3: 9, 4: 16} Dict and list example: Python Interview Questions and Answers output: [11, 12, 13, 14, 15] output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} Combining multiple lists into one: Output: [8, 10, 12] lattening a multi-dimensional list Output: [10, 20, 30, 40, 50, 60, 70, 80, 90] 25) What are modules and packages in Python? • Modular programming refers to the process of breaking a large, unwieldy programming task into separate, smaller, more manageable subtasks or modules. Module contents are made available to the caller with the import statement. The import statement takes many different forms, shown below: import from import as Python Interview Questions and Answers • Packages allow for a hierarchical structuring of the module namespace using dot notation. In the same way that modules help avoid collisions between global variable names, packages help avoid collisions between module names. from import from . sub_pkg1 import 26)What is pickling and unpickling? • Pickling is the name of the serialization process in Python. Any object in Python can be serialized into a byte stream and dumped as a file in the memory. The process of pickling is compact but pickle objects can be compressed further. Moreover, pickle keeps track of the objects it has serialized and the serialization is portable across versions. • Unpickling is the complete inverse of pickling. It deserializes the byte stream to recreate the objects stored in the file and loads the object to memory. Python Interview Questions and Answers 27) What is the difference between .py and .pyc files? • py files contain the source code of a program. Whereas, .pyc file contains the bytecode of your program. We get bytecode after compilation of .py file (source code). pyc files are not created for all the files that you run. It is only created for the files that you import. • Before executing a python program python interpreter checks for the compiled files. If the file is present, the virtual machine executes it. If not found, it checks for .py file. If found, compiles it to .pyc file and then python virtual machine executes it. • Having .pyc file saves you the compilation time. 28) What are generators in Python? Generators are functions that return an iterable collection of items, one at a time, in a set manner. Generators, in general, are used to create iterators with a different approach. They employ the use of yield keyword rather than return to return a generator object. Example: Output: 0 1 1 2 3 5 8 Python Interview Questions and Answers 29) What is lambda in Python? Lambda is an anonymous function in Python, that can accept any number of arguments, but can only have a single expression. It is generally used in situations requiring an anonymous function for a short time period. Lambda functions can be used in either of the two ways: ❖ Assigning lambda functions to a variable: Output: 10 ❖ Wrapping lambda functions inside another function: Output: 10 30) How will you capitalize the first letter of string? Output: Geeks for geeks GeeksForGeeks 31) How will you convert a string to all lowercase? Output: abcd Python Interview Questions and Answers 32) Write a code to sort a numerical list in Python? Output: [1,2,5,7,8] 33) What is self in Python? self represents the instance of the class. By using the “self” keyword we can access the attributes and methods of the class in python. output: Model is audi a4 color is blue Model is ferrari 488 color is green 34) What is __init__? __init__ is a constructor method in Python and is automatically called to allocate memory when a new object/instance is created. All classes have a __init__ method associated with them. It helps in distinguishing methods and attributes of a class from local variables. Example: Python Interview Questions and Answers 35) What is break, continue and pass in Python? • The break statement terminates the loop immediately and the control flows to the statement after the body of the loop. Output: Current Letter : P Current Letter : y Current Letter : t • The continue statement terminates the current iteration of the statement, skips the rest of the code in the current iteration and the control flows to the next iteration of the loop. Output: Current Letter: P Current Letter : y Current Letter : t Current Letter : o Current Letter : n • The pass keyword in Python is generally used to fill up empty blocks and is similar to an empty statement represented by a semi-colon in languages such as Java, C++, JavaScript, etc. 36) What is a map function in Python? Python’s map() is a built-in function that allows you to process and transform all the items in an iterable without using an explicit for loop, a technique commonly known as mapping. map() is useful when you need to apply a transformation function to each item in an iterable and transform them into a new iterable. map () is one of the tools that support a functional programming style in Python. Example: Python Interview Questions and Answers 37)What is the difference between Python Arrays and lists? • List Can consist of elements belonging to different data types sample_list = [1,"Yash”, ['a','e']] • Array Only consists of elements belonging to the same data type sample_array = array. array ('i', [1, 2, 3]) 38) How to add values to a python array? Elements can be added to an array using the append (), extend () and the insert (i,x) functions. Output: array('d', [1.1, 2.1, 3.1, 3.4]) array('d', [1.1, 2.1, 3.1, 3.4, 4.5, 6.3, 6.8]) array('d', [1.1, 2.1, 3.8, 3.1, 3.4, 4.5, 6.3, 6.8]) 39) What is the difference between append () and extend () methods? • append: Appends object at the end. map Python Interview Questions and Answers Output: [1, 2, 3, [4, 5]] • extend: Extends list by appending elements from the iterable. Output: [1, 2, 3, 4, 5] 40)What is slicing in Python? As the name suggests, ‘slicing’ is taking parts of syntax for slicing is [start: stop: step]: • start is the starting index from where to slice a list or tuple • stop is the ending index or where to sop. • step is the number of steps to jump Example: Output: [30, 40, 50, 60, 70] Output: [70, 80, 90] output: [10, 20, 30, 40, 50, 60, 70] Python Interview Questions and Answers Output: [20, 40, 60, 80] 41) Write a command to open the file c:\hello.txt for writing? 42) Write a code to display the contents of a file in reverse? 43) How can files be deleted in Python? 44) Can you write an efficient code to count the number of capital letters in a file? 45) Write a Python program to count the total number of lines in a text file? 46) What does *args and **kwargs mean? • *args: It is used to pass multiple arguments in a function. • **kwargs: It is used to pass multiple keyworded arguments in a function in python. Python Interview Questions and Answers 47) Explain split(), sub(), subn() methods of “re” module in Python? 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. Output: ['On ', 'th Jan ', ', at ', ':', ' AM'] Baked Beans & Spam ('S~*ject has Uber booked already', 1) 48)Write a program in Python to execute the Bubble sort algorithm? Output: [5, 5, 3, 6, 7, 54, 87] [5, 3, 3, 6, 7, 54, 87] [5, 3, 6, 6, 7, 54, 87] [5, 3, 6, 7, 7, 54, 87] [5, 3, 6, 7, 54, 54, 87] [5, 3, 6, 7, 54, 87, 87] [3, 3, 6, 7, 54, 87, 87] [3, 6, 6, 7, 54, 87, 87] [3, 6, 7, 7, 54, 87, 87] [3, 6, 7, 54, 54, 87, 87] [3, 6, 7, 54, 87, 87, 87] [6, 6, 7, 54, 87, 87, 87] [6, 7, 7, 54, 87, 87, 87] [6, 7, 54, 54, 87, 87, 87] [6, 7, 54, 87, 87, 87, 87] [7, 7, 54, 87, 87, 87, 87] [7, 54, 54, 87, 87, 87, 87] [7, 54, 87, 87, 87, 87, 87] [54, 54, 87, 87, 87, 87, 87] [54, 87, 87, 87, 87, 87, 87] [87, 87, 87, 87, 87, 87, 87] Python Interview Questions and Answers 49)What is the usage of numpy? 50) How will you find the shape of any given NumPy array? Output: 2-D Array Shape: (2, 4) 1-D Array Shape: (5,)

No comments:

Post a Comment