Python Interview questions

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Define encapsulation in Python?

Encapsulation is one of the fundamental concepts in object-oriented programming (OOP). It describes the idea of wrapping data and the methods that work on data within one unit. This puts restrictions on accessing variables and methods directly and can prevent the accidental modification of data. To prevent accidental change, an object's variable can only be changed by an object's method. Those type of variables are known as private variable. Protected members (in C++ and JAVA) are those members of the class which cannot be accessed outside the class but can be accessed from within the class and it's subclasses. To accomplish this in Python, just follow the convention by prefixing the name of the member by a single underscore "_".

What are python iterators?

Iterators are objects which can be traversed though or iterated upon.

What is the difference between list and tuples in Python?

List is mutable, is slower than a tuple, l = [1,2,3] Tuple is immutable, are faster than a list t = (1,2,3)

What are the generators in python?

Functions that return an iterable set of items are called generators

How to import modules in python?

Modules can be imported using the import keyword. You can import modules in three ways- import array import array * # imports all from array import *

Does python support multiple inheritance?

Multiple inheritance means that a class can be derived from more than one parent classes. Python does support multiple inheritance, unlike Java.

What are local variables and global variables in Python?

Global variables are declared outside a function they can be accessed by any function in the program. Local variables Any variable declared inside a function is known as a local variable. This variable is present in the local space and not in the global space.

List out the inheritance styles in Django.

1) Abstract Base Classes: This style is used when you only want parent's class to hold information that you don't want to type out for each child model. 2)Multi-table Inheritance: This style is used If you are sub-classing an existing model and need each model to have its own database table. 3) Proxy models: You can use this model, If you only want to modify the Python level behavior of the model, without changing the model's fields.

What is the usage of help() and dir() function in Python?

1) Help() function: The help() function is used to display the documentation string and also facilitates you to see the help related to modules, keywords, attributes, etc. 2) Dir() function: The dir() function is used to display the defined symbols. output: ['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'l']

How is Multithreading achieved in Python?

1) Python has a multi-threading package but if you want to multi-thread to speed your code up, then it's usually not a good idea to use it. 2) Python has a construct called the Global Interpreter Lock (GIL). The GIL makes sure that only one of your 'threads' can execute at any one time. A thread acquires the GIL, does a little work, then passes the GIL onto the next thread. 3) This happens very quickly so to the human eye it may seem like your threads are executing in parallel, but they are really just taking turns using the same CPU core. 4) All this GIL passing adds overhead to execution. This means that if you want to make your code run faster then using the threading package often isn't a good idea.

What is the process of compilation and linking in python?

1) create a c file 2) place the file in the modules directory 3) add the location of the file in Setup.local 4) run the make 5) successful run rebuild make

What are the key features of python?

1) python is an interpreted language which means it does not need to be compiled. 2) Python is dynamically typed which means you do not have to state the variable types such as int or string 3) Python is object oriented so you can use class definition 4) Functions are first class objects which means that can be assigned to variables, returned from other functions and passed into functions. Classes are also first class objects. 5) Writing python is quick if you need to test a quick script it wont take long to do.

How will you capitalize the first letter of string?

In Python, the capitalize() method

What is monkey patching in Python?

In Python, the term monkey patch only refers to dynamic modifications of a class or module at run-time.

What is the difference between NumPy and SciPy?

In an ideal world, NumPy would contain nothing but the array data type and the most basic operations: indexing, sorting, reshaping, basic elementwise functions, et cetera. All numerical code would reside in SciPy. However, one of NumPy's important goals is compatibility, so NumPy tries to retain all features supported by either of its predecessors. Thus NumPy contains some linear algebra functions, even though these more properly belong in SciPy. In any case, SciPy contains more fully-featured versions of the linear algebra modules, as well as many other numerical algorithms. If you are doing scientific computing with python, you should probably install both NumPy and SciPy. Most new features belong in SciPy rather than NumPy.

What are functions in Python?

A function is a block of code which is executed only when it is called. To define a Python function, the def keyword is used.

What is a namespace?

A namespace is a system used to make sure that names are unique. Namespaces in Python are implemented as Python dictionaries, this means it is a mapping from names (keys) to objects (values) Some namespaces in Python: global names of a module local names in a function or method invocation built-in names: this namespace contains built-in functions (e.g. abs(), cmp(), ...) and built-in exception names

How do you do data abstraction in Python?

Abstract classes allow you to provide default functionality for the subclasses. In python by default, it is not able to provide abstract classes, but python comes up with a module which provides the base for defining Abstract Base classes(ABC) and that module name is ABC. ABC works by marking methods of the base class as abstract and then registering concrete classes as implementations of the abstract base. A method becomes an abstract by decorated it with a keyword @abstractmethod.

What is a lambda function?

An anonymous function is known as a lambda function. This function can have any number of parameters but, can have just one statement.

How to create an empty class in Python?

An empty class is a class that does not have any code defined within its block. It can be created using the pass keyword. However, you can create objects of this class outside the class itself. IN PYTHON THE PASS command does nothing when its executed. it's a null statement.

Explain Inheritance in Python with an example

Inheritance allows One class to gain all the members(say attributes and methods) of another class. Inheritance provides code reusability, makes it easier to create and maintain an application. The class from which we are inheriting is called super-class and the class that is inherited is called a derived / child class. They are different types of inheritance supported by Python: 1) Single Inheritance - where a derived class acquires the members of a single super class. 2) Multi-level inheritance - a derived class d1 in inherited from base class base1, and d2 are inherited from base2. 3) Hierarchical inheritance - from one base class you can inherit any number of child classes 4) Multiple inheritance - a derived class is inherited from more than one base class.

How does break, continue and pass work?

Break: Allows loop termination when some condition is met and the control is transferred to the next statement. Continue: Allows skipping some part of a loop when some specific condition is met and the control is transferred to the beginning of the loop. Pass: Used when you need some block of code syntactically, but you want to skip its execution. This is basically a null operation. Nothing happens when this is executed.

What are the built-in types of python?

Built-in types in Python are as follows - Integers Floating-point Complex numbers Strings Boolean Built-in functions

How are classes created in Python?

Class in Python is created using the class keyword.

What type of language is python? programming or scripting?

It can be both but is a programming language. Python has object oriented programming so you can use classes, inheritance and polymorphic but you can also write a script without oop.

What is a dictionary in Python?

It defines one-to-one relationship between keys and values. Dictionaries contain pair of keys and their corresponding values. Dictionaries are indexed by keys

What does len() do?

It is used to determine the length of a string, a list, an array, etc.

What are docstrings in Python?

Docstrings are not actually comments, but, they are documentation strings. These docstrings are within triple quotes.

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.

What is pickling and unpickling?

Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.

What is Polymorphism in Python?

Polymorphism means the ability to take multiple forms. So, for instance, if the parent class has a method named ABC then the child class also can have a method with the same name ABC having its own parameters and variables. Python allows polymorphism.

What is PEP8

Python enhancement proposal set of rules on how to format python code for readability.

Does Python have OOps concepts?

Python is an object-oriented programming language. This means that any program can be solved in python by creating an object model. However, Python can be treated scripting language

What are Python libraries? Name a few of them.

Python libraries are a collection of Python packages. Some of the majorly used python libraries are - Numpy, Pandas, Matplotlib, Scikit-learn and many more.

What are python modules

Python modules are files containing Python code. This code can either be functions classes or variables. A Python module is a .py file containing executable code. Some of the commonly used built-in modules are: os sys math random data time JSON

What are Python packages?

Python packages are namespaces containing multiple modules.

How can you generate random numbers in Python?

Random module is the standard module that is used to generate a random number. The method is defined as: import random random.random() randrange(a, b): it chooses an integer and define the range in-between [a, b). uniform(a, b): it chooses a floating point number that is defined in the range of [a,b).Iyt returns the floating point number

What is self in Python?

Self is an instance or an object of a class. In Python, this is explicitly included as the first parameter. However, this is not the case in Java where it's optional. It helps to differentiate between the methods and attributes of a class with local variables. The self variable in the init method refers to the newly created object while in other methods, it refers to the object whose method was called.

What is the difference between deep and shallow copy?

Shallow copy - copies the reference pointers which point to the original value and is there is any change to shallow copy it will also change the original object. Shallow copy allows faster execution of the program and it depends on the size of the data that is used. Deep copy is used to store the values that are already copied. Deep copy doesn't copy the reference pointers to the objects. It makes the reference to an object and the new object that is pointed by some other object gets stored. The changes made in the original copy won't affect any other copy that uses the object. Deep copy makes execution of the program slower due to making certain copies for each object that is been called.

How can the ternary operators be used in python?

Ternary operators are more commonly known as conditional expressions in Python. These operators evaluate something based on a condition being true or not. This consists of the true or false values with a statement that has to be evaluated for it.

What are negative indexes and why are they used?

The index for the negative number starts from '-1' that represents the last index in the sequence and '-2' as the penultimate index and the sequence carries forward like the positive number. The negative index is used to remove any new-line spaces from the string and allow the string to except the last character that is given as S[:-1]. The negative index is also used to show the index to represent the string in correct order.

What advantages do NumPy arrays offer over (nested) Python lists?

The main benefits of using NumPy arrays should be smaller memory consumption and better runtime behavior, allows matrix multiplcation

How can files be deleted from the OS in Python?

To delete a file in Python, you need to import the OS Module. After that, you need to use the os.remove() function.

How do you calculate percentiles with Python/ NumPy?

We can calculate percentiles with the following code import numpy as np a = np.array([1,2,3,4,5]) p = np.percentile(a, 50) #Returns 50th percentile, e.g. median print(p)

How to get indices of N maximum values in a NumPy array?

We can get the indices of N maximum values in a NumPy array using the below code: import numpy as np arr = np.array([1, 3, 2, 4, 5]) print(arr.argsort()[-3:][::-1])

What does this mean: *args, **kwargs? And why would we use it?

We use *args when we aren't sure how many arguments are going to be passed to a function, or if we want to pass a stored list or tuple of arguments to a function. **kwargs is used when we don't know how many keyword arguments will be passed to a function, or it can be used to pass the values of a dictionary as keyword arguments.

Is python numpy better than lists?

We use python numpy array instead of a list because of the below three reasons: Less Memory Fast Convenient

What is type conversion in Python?

When you cast an object to another data type. This can be dont with the following: int() - converts any data type into integer type float() - converts any data type into float type ord() - converts characters into integer hex() - converts integers to hexadecimal oct() - converts integer to octal tuple() - This function is used to convert to a tuple. set() - This function returns the type after converting to set. list() - This function is used to convert any data type to a list type. dict() - This function is used to convert a tuple of order (key,value) into a dictionary. str() - Used to convert integer into a string.

is indentation in python required

Yes, python uses whitespace using four spaces

What does [::-1] do?

[::-1] is used to reverse the order of an array or a sequence. you can also use the reverse method

What is __init__?

__init__ is a method or constructor in Python. This method is automatically called to allocate memory when a new object/ instance of a class is created. All classes have the __init__ method.

How is python an interpreted language?

an interpreted language is any programming language which is not in machine level code before runtime. Therefore python is an interpreted language. Python has an interpreter that translates the code to

What is the difference between Python Arrays and lists?

arrays can hold only a single data type elements whereas lists can hold any data type elements.

How can you randomize the items of a list in place in Python?

from random import shuffle x = ['Keep', 'The', 'Blue', 'Flag', 'Flying', 'High'] shuffle(x) print(x)

What is the purpose of is, not and in operators?

is: returns true when 2 operands are true (Example: "a" is 'a') not: returns the inverse of the boolean value in: checks if some element is present in some sequence

How will you convert a string to all lowercase?

lower() function can be used

What is map function in Python?

map function executes the function given as the first argument on all the elements of the iterable given as the second argument. If the function given takes in more than 1 arguments, then many iterables are given. #Follow the link to know more similar functions.

How to remove values to a python array?

pop() or remove() method the difference between these two functions is that the pop() returns the deleted value whereas the remove() does not.

Explain split(), sub(), subn() methods of "re" module in Python.

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.

What does an object() do?

t returns a featureless object that is a base for all classes. Also, it does not take any parameters.

How do you write comments in python?

with the # symbol

What is the difference between range & xrange?

xrange and range are the exact same in terms of functionality. They both provide a way to generate a list of integers for you to use. The only difference is that xrange doesn't actually generate a static list at run-time like range does. It creates the values as you need them with a special technique called yielding.

is python case sensitive

yes

Does python make use of access specifiers?

yes, you make a variable function of method protected with the single or double underscore

How to comment multiple lines in python?

you place the # symbol in front of all the lines you want to comment out


Kaugnay na mga set ng pag-aaral

EAT RIGHT PREP (Pt #3) - PRACTICE QUESTIONS - RD EXAM

View Set

Network+ Guide to Networks - Sixth Edition - Chapter 4 Review

View Set

11.6 Describe income tax methods of depreciation.

View Set

A&P II: Ch. 24 The Urinary System Review

View Set