Python Interview Questions Flashcards
source: https://www.edureka.co/blog/interview-questions/python-interview-questions/
*args vs **kwargs
*args
- when we don’t know 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
- 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.
How do you make 3D plots/visualizations using NumPy/SciPy?
Like 2D plotting, 3D graphics is beyond the scope of NumPy and SciPy, but just as in the 2D case, packages exist that integrate with NumPy. Matplotlib provides basic 3D plotting in the mplot3d subpackage, whereas Mayavi provides a wide range of high-quality 3D visualization features, utilizing the powerful VTK engine.
Abstraction
Data Abstraction is providing only the required details and hiding the implementation from the world. It can be achieved in Python by using interfaces and abstract classes.
Access specifiers
Python does not deprive access to an instance variable or function.
Python lays down the concept of prefixing the name of the variable, function or method with a single or double underscore to imitate the behavior of protected and private access specifiers.
add values to array
append(), extend() and the insert (i,x) functions.
Example:
a=arr.array(‘d’, [1.1 , 2.1 ,3.1] )
a.append(3.4)
print(a)
a.extend([4.5,6.3,6.8])
print(a)
a.insert(2,3.8)
print(a)
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])
remove values from array
pop() or remove() method. The difference between these two functions is that the former returns the deleted value whereas the latter does not.
Example:
a=arr.array(‘d’, [1.1, 2.2, 3.8, 3.1, 3.7, 1.2, 4.6])
print(a.pop())
print(a.pop(3))
a.remove(1.1)
print(a)
Output:
- 6
- 1
array(‘d’, [2.2, 3.8, 3.7, 1.2])
Arrays vs Lists
Arrays and lists, in Python, have the same way of storing data.
But, arrays can hold only a single data type elements whereas lists can hold any data type elements.
ALso an array runs faster than a list because it alocates a block of memory.
Break, Continue and Pass
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.
Built-in types
- Integers
- Floating-point
- Complex numbers
- Strings
- Boolean
- Built-in functions
Capitalize the 1st letter of string
- Capitalize() method capitalizes the first letter of a string.
- If the string already consists of a capital letter at the beginning, then, it returns the original string.
Case sensitive
Python is a case sensitive language.
create an empty class
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.
For example-
class a:
pass
obj=a()
obj.name=”xyz”
print(“Name = “,obj.name)
Output:
Name = xyz
Classes
Class in Python is created using the class keyword.
Example:
class Employee:
def __init__(self, name):
self.name = name
E1=Employee(“abc”)
print(E1.name)
Output:
abc
Comments
Comments in Python start with a # character. However, alternatively at times, commenting is done using docstrings(strings enclosed within triple quotes).
Comment multiple lines
Multi-line comments appear in more than one line.
- All the lines to be commented are to be prefixed by a #.
- block of string can be use for multi-lines comments, also called docstrings:
- ”"”block
of
comment”””
- ”"”block
Compilation and Linking
Compiling and linking allows the new extensions to be compiled properly without any error and the linking can be done only when it passes the compiled procedure. If the dynamic loading is used then it depends on the style that is being provided with the system. The python interpreter can be used to provide the dynamic loading of the configuration setup files and will rebuild the interpreter.
The steps that are required in this as:
- Create a file with any name and in any language that is supported by the compiler of your system. For example file.c or file.cpp
- Place this file in the Modules/ directory of the distribution which is getting used.
- Add a line in the file Setup.local that is present in the Modules/ directory.
- Run the file using spam file.o
- After a successful run of this rebuild the interpreter by using the make command on the top-level directory.
- If the file is changed then run rebuildMakefile by using the command as ‘make Makefile’.
Type Conversion (casting)
Type conversion refers to the conversion of one data type iinto another (casting).
- 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.
- complex(real,imag) – This functionconverts real numbers to complex(real,imag) number.
Deep vs Shallow copy
Shallow copy is used when a new instance type gets created and it keeps the values that are copied in the new instance. Shallow copy is used to copy the reference pointers just like it copies the values. These references point to the original objects and the changes made in any member of the class will also affect the original copy of it. 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.
Delete files
import os
os.remove(“xyz.txt”)
Dictionary
- built-in datatype. It defines one-to-one relationship between
- keys and values pair
- it is indexed by keys
- mutable
- iterable
- curly brackets
Django vs Flask
Django and Flask map the URL’s or addresses typed in the web browsers to functions in Python.
Flask is much simpler compared to Django but, Flask does not do a lot for you meaning you will need to specify the details, whereas Django does a lot for you wherein you would not need to do much work.
Django consists of prewritten code, which the user will need to analyze whereas Flask gives the users to create their own code, therefore, making it simpler to understand the code. Technically both are equally good and both contain their own pros and cons.
Django, Pyramid and Flask.
- Flask is a “microframework” primarily build for a small application with simpler requirements. In flask, you have to use external libraries. Flask is ready to use.
- Pyramid is built for larger applications. It provides flexibility and lets the developer use the right tools for their project. The developer can choose the database, URL structure, templating style and more. Pyramid is heavy configurable.
- Django can also be used for larger applications just like Pyramid. It includes an ORM (object-relational-mapping) - like database object in the code.
Django architecture
Django MVT Pattern:
The developer provides the Model, the view and the template then just maps it to a URL and Django does the magic to serve it to the user.
set up Database in Django
setting.py file for dababase details, it is a normal python module with module level representing Django settings.
Django uses SQLite by default; it is easy for Django users as such it won’t require any other type of installation. In the case your database choice is different that you have to the following keys in the DATABASE ‘default’ item to match your database connection settings. If you do have a database server—PostgreSQL, MySQL, Oracle, MSSQL—and want to use it rather than SQLite, then use your database’s administration tools to create a new database for your Django project. Either way, with your (empty) database in place, all that remains is to tell Django how to use it.
- Engines: you can change the database by using ‘django.db.backends.sqlite3’ , ‘django.db.backeneds.mysql’, ‘django.db.backends.postgresql_psycopg2’, ‘django.db.backends.oracle’ and so on
- Name: The name of your database. In the case if you are using SQLite as your database, in that case, database will be a file on your computer, Name should be a full absolute path, including the file name of that file.
- If you are not choosing SQLite as your database then settings like Password, Host, User, etc. must be added.
Inheritance styles in Django
In Django, there are three possible inheritance styles:
- 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.
- 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.
- 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.
Session in Django
- Django provides a session that lets you store and retrieve data on a per-site-visitor basis.
- Django abstracts the process of sending and receiving cookies, by placing a session ID cookie on the client side, and storing all the related data on the server side.
- The data itself is not stored client side. This is nice from a security perspective.
Django templates
- The template is a simple text file.
- It can create any text-based format like XML, CSV, HTML, etc.
- A template contains variables that get replaced with values when the template is evaluated and tags (% tag %) that control the logic of the template.
VIEW in Django
from django.http import HttpResponse
import datetime
def Current_datetime(request):
now = datetime.datetime.now()
html = “It is now %s % now
return HttpResponse(html)
Returns the current date and time, as an HTML document
Docstrings
- Docstrings are not actually comments, but, they are documentation strings.
- These docstrings are within triple quotes.
- They are not assigned to any variable and therefore, at times, serve the purpose of comments as well.
- ””” Using docstring as a comment.
This code divides 2 numbers “””
Encapsulation
Encapsulation means binding the code and the data together. A Python class is an example of encapsulation.
Flask
Flask is a web microframework for Python based on “Werkzeug, Jinja2 and good intentions” BSD license. Werkzeug and Jinja2 are two of its dependencies.
- This means it will have little to no dependencies on external libraries.
- It makes the framework light while there is a little dependency to update and fewer security bugs.
- A session basically allows you to remember information from one request to another. In a flask, a session uses a signed cookie so the user can look at the session contents and modify.
- The user can modify the session if only it has the secret key Flask.secret_key.
Functions
- 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.
Generators
Functions that return an iterable set of items are called generators.
example: function that returns a list
Get Google cache age of any URL or web page
http://webcache.googleusercontent.com/search?q=cache:URLGOESHERE
Example:
http://webcache.googleusercontent.com/search?q=cache:billygustave.com
help() vs dir()
- help() and dir() both functions are accessible from the Python interpreter and used for viewing a consolidated dump of built-in functions.
help()
- returns/displays the docstring for a function/class/module
- help([object])
dir()
- list all functions and variable names in a module
import modules
Modules can be imported using the import keyword. You can import modules in three ways- Example: 1 2 3
import array #importing using the original module name
import array as arr # importing using an alias name
from array import * #imports everything present in the array module
Indentation
- Indentation is necessary for Python. It specifies a block of code.
- All code within loops, classes, functions, etc is specified within an indented block. It is usually done using four space characters.
- If your code is not indented necessarily, it will not execute accurately and will throw errors as well.
negative indexes
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.
Inheritance
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:
- Single Inheritance – where a derived class acquires the members of a single super class.
- Multi-level inheritance – a derived class d1 in inherited from base class base1, and d2 are inherited from base2.
- Hierarchical inheritance – from one base class you can inherit any number of child classes
- Multiple inheritance – a derived class is inherited from more than one base class.
Iterators
objects which can be traversed though or iterated upon.