Full Stack QNA
Full Stack QNA
Answer: Python is a high-level, interpreted programming language with the following key features:
● Easy to Learn and Use: Python has a simple syntax that mimics natural language.
● Interpreted Language: Code is executed line-by-line, making debugging easier.
● Dynamically Typed: You don't need to declare variable types explicitly.
● Extensive Libraries: Offers standard libraries for web development, machine learning, data analysis, etc.
● Portability: Python code is platform-independent and runs on multiple platforms.
● Open Source and Community Support: Freely available with a supportive community.
Follow-up tip: Mention how these types help in various real-world applications, such as using lists for dynamic data storage or dictionaries for key-value pair mapping.
Answer:
Follow-up tip: Explain how you would use a tuple for constant data, a list for dynamic arrays, and a set for unique data.
Answer:
● copy(): Creates a shallow copy, only copying the object's reference for nested objects.
● deepcopy(): Creates a deep copy, cloning all levels of the object hierarchy.
Example:
import copy
shallow_copy[0][0] = 99
print(original) # Output: [[99, 2], [3, 4]]
print(deep_copy) # Output: [[1, 2], [3, 4]]
Answer: Decorators are functions that modify the behavior of another function or method. They are often used for logging, access control, or memoization.
Example:
def decorator_function(original_function):
def wrapper_function():
print("Wrapper executed before the original function.")
return original_function()
return wrapper_function
@decorator_function
def display():
print("Original function executed.")
display()
Follow-up tip: Mention how decorators help in frameworks like Flask/Django for route handling or adding middleware.
Answer: The GIL is a mutex that protects access to Python objects, ensuring that only one thread executes Python bytecode at a time. It simplifies memory management but limits multi-threaded performance.
Follow-up tip: Explain how you can bypass GIL limitations using multiprocessing for CPU-bound tasks or threading for I/O-bound tasks.
Answer:
Example:
Follow-up tip: Mention how they make functions more flexible and adaptable.
8. How does Python manage memory?
Follow-up tip: Highlight how you can use gc (garbage collector) module to optimize memory usage.
Answer:
Follow-up tip: Emphasize Python 3's advantages and its current industry relevance.
Answer:
Follow-up tip: Mention the framework/library you have experience with and provide a short example or use case.
● Be ready to write small code snippets for basic algorithms (e.g., Fibonacci, factorial, or palindrome check).
● Expect debugging or optimization-related questions.
● Be familiar with Pythonic best practices, like using list comprehensions and lambda functions.
Answer:
Example:
a = [1, 2, 3]
b = [1, 2, 3]
c=a
Answer: Comprehensions are a concise way to construct new sequences using an existing iterable. They can be used for lists, dictionaries, and sets.
Examples:
List comprehension:
Dictionary comprehension:
Set comprehension:
13. What are Python's generators and how are they different from iterators?
Answer:
● Generators: Special iterators defined using functions and the yield keyword. They lazily generate values one at a time.
● Difference: Generators use yield, while iterators use the __iter__() and __next__() methods.
Example:
def generate_numbers():
for i in range(5):
yield i
gen = generate_numbers()
print(next(gen)) # 0
print(next(gen)) # 1
Follow-up tip: Mention the memory efficiency of generators, especially for large datasets.
14. How does Python implement exception handling?
Answer: Python uses try, except, else, and finally blocks to handle exceptions.
Example:
try:
num = int(input("Enter a number: "))
print(10 / num)
except ZeroDivisionError:
print("You can't divide by zero!")
except ValueError:
print("Invalid input. Please enter a number.")
else:
print("Division successful!")
finally:
print("Execution complete.")
Answer: A metaclass is a class of a class that defines how a class behaves. Classes are instances of metaclasses.
Example:
class Meta(type):
def __new__(cls, name, bases, dct):
print(f"Creating class {name}")
return super().__new__(cls, name, bases, dct)
class MyClass(metaclass=Meta):
pass
# Output: Creating class MyClass
Follow-up tip: Discuss how metaclasses are used in frameworks like Django for model creation.
Answer:
● @staticmethod: Defines a method that doesn’t operate on an instance or class. It has no access to self or cls.
● @classmethod: Defines a method that operates on the class and can access cls.
Example:
class MyClass:
@staticmethod
def static_method():
print("I don't access instance or class.")
@classmethod
def class_method(cls):
print(f"I can access the class: {cls}")
17. What is the difference between mutable and immutable objects in Python?
Answer:
● Mutable objects: Can be modified after creation (e.g., list, dict, set).
● Immutable objects: Cannot be modified after creation (e.g., int, float, tuple, str).
Example:
# Mutable
lst = [1, 2, 3]
lst[0] = 99
print(lst) # [99, 2, 3]
# Immutable
tup = (1, 2, 3)
# tup[0] = 99 # TypeError
Answer:
Example:
obj = Child()
print(isinstance(obj, Parent)) # True
print(type(obj) == Parent) # False
Answer: Magic methods (dunder methods) are special methods surrounded by double underscores and used to define object behavior.
Common examples:
Example:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"Point({self.x}, {self.y})"
p1 = Point(1, 2)
p2 = Point(3, 4)
print(p1 + p2) # Point(4, 6)
Answer: The with statement ensures proper acquisition and release of resources using context managers.
Example:
Follow-up tip: Discuss how with simplifies exception handling when dealing with file I/O or database connections.
Answer:
Example:
# Global
x = 10
def modify_global():
global x
x += 5
modify_global()
print(x) # 15
# Nonlocal
def outer():
y = 10
def inner():
nonlocal y
y += 5
inner()
print(y)
outer() # 15
22. What is Python's asyncio module?
Answer: asyncio is a module for writing asynchronous code using async and await. It is used for I/O-bound and high-level structured network code.
Example:
import asyncio
asyncio.run(greet())
1. What is Django?
Answer: Django is a high-level Python web framework that enables rapid development of secure and maintainable websites. It follows the Model-View-Template (MVT)
architectural pattern and includes features like:
Follow-up tip: Highlight Django's ability to integrate with other libraries and its wide use in e-commerce, social networks, and CMS development.
Answer:
Answer: Django uses migrations to manage database schema changes. Key commands include:
Example:
Follow-up tip: Mention that migrations ensure consistency across development and production environments.
Answer: Django provides forms to handle user input, including form validation and rendering.
Example:
class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
message = forms.CharField(widget=forms.Textarea)
# In views.py
from django.shortcuts import render
from .forms import ContactForm
def contact_view(request):
if request.method == "POST":
form = ContactForm(request.POST)
if form.is_valid():
# Process form data
pass
else:
form = ContactForm()
return render(request, 'contact.html', {'form': form})
Settings:
# settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / 'static']
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
# urls.py
from django.conf import settings
from django.conf.urls.static import static
Answer: Django's ORM allows developers to interact with the database using Python code instead of raw SQL.
Example:
# models.py
class Blog(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
published_date = models.DateTimeField(auto_now_add=True)
# Querying data
from myapp.models import Blog
blogs = Blog.objects.filter(title__icontains="Django")
Follow-up tip: Highlight that Django ORM supports complex queries using methods like annotate, aggregate, and joins through select_related.
Answer: Middleware are components executed during request/response processing. Common examples include:
● SecurityMiddleware: Handles security headers.
● AuthenticationMiddleware: Adds user authentication.
class MyCustomMiddleware:
def __init__(self, get_response):
self.get_response = get_response
Answer: Django provides a built-in authentication system for user login, logout, and permissions.
Example:
# settings.py
LOGIN_URL = '/login/'
# views.py
from django.contrib.auth import authenticate, login
def login_view(request):
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('home')
return render(request, 'login.html')
Follow-up tip: Mention Django's built-in User model and django.contrib.auth library.
Answer:
Example:
@login_required
def profile_view(request):
pass
@permission_required('app_name.permission_name')
def special_view(request):
pass
Answer: Using Django REST Framework (DRF), you can build APIs easily.
Example:
Install DRF:
1.
Serializer:
class BlogSerializer(serializers.ModelSerializer):
class Meta:
model = Blog
fields = '__all__'
2.
Views:
class BlogList(APIView):
def get(self, request):
blogs = Blog.objects.all()
serializer = BlogSerializer(blogs, many=True)
return Response(serializer.data)
3.
URLs:
urlpatterns = [
path('blogs/', BlogList.as_view(), name='blog-list'),
]
4.
Follow-up tip: Highlight the use of generic views like ListAPIView or CreateAPIView for simpler APIs.
Answer: Django includes CSRF protection by default, requiring a CSRF token in POST requests.
Example:
<form method="POST">
{% csrf_token %}
<input type="text" name="title">
<button type="submit">Submit</button>
</form>
Answer:
● Use select_related for foreign keys and prefetch_related for many-to-many relationships.
● Avoid querying in loops.
● Use only() or defer() to fetch specific fields.
● Use database indexing for frequently queried fields.
Example:
# Optimized query
blogs = Blog.objects.select_related('author').all()
13. How do signals work in Django?
Answer: Signals allow decoupled components to get notified when certain actions occur.
Example:
@receiver(post_save, sender=Blog)
def notify_admin(sender, instance, created, **kwargs):
if created:
print(f"New blog created: {instance.title}")
Answer:
Example:
class BlogModelTest(TestCase):
def setUp(self):
Blog.objects.create(title="Test Blog", content="Test Content")
def test_blog_content(self):
blog = Blog.objects.get(title="Test Blog")
self.assertEqual(blog.content, "Test Content")
16. What is the difference between get() and filter() in Django ORM?
Answer:
● get():
○ Retrieves a single object matching the query.
○ Raises DoesNotExist exception if no object is found.
○ Raises MultipleObjectsReturned exception if more than one object is found.
Example:
● filter():
○ Retrieves a QuerySet of all objects matching the query.
○ Returns an empty QuerySet if no objects are found.
Example:
Answer:
● select_related:
○ Performs a SQL join and retrieves related data in a single query.
○ Best for foreign key or one-to-one relationships.
Example:
● prefetch_related:
○ Executes multiple queries and performs Python-level joins.
○ Best for many-to-many or reverse foreign key relationships.
Example:
Example:
@receiver(post_save, sender=Blog)
if created:
else:
19. What are Django's class-based views (CBVs), and how do they differ from function-based views (FBVs)?
Answer:
● FBVs:
○ Simple functions that handle HTTP requests and responses.
○ Easier to understand but can become verbose for complex views.
Example:
def home_view(request):
● CBVs:
○ Use Python classes to handle views.
○ More reusable and modular.
Example:
class HomeView(View):
Answer: The ContentType framework allows you to work with models in a generic way. It’s commonly used in permissions and generic relationships.
Example:
permission = Permission.objects.create(
codename='can_publish',
content_type=content_type
● File-based caching
● Database caching
● Memcached
● Redis
# settings.py
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
'LOCATION': '/var/tmp/django_cache',
def my_view(request):
22. What is the difference between ForeignKey, OneToOneField, and ManyToManyField in Django?
Answer:
● ForeignKey:
class Blog(models.Model):
●
● OneToOneField:
class Profile(models.Model):
●
● ManyToManyField:
class Blog(models.Model):
tags = models.ManyToManyField(Tag)
Answer: Django allows creating custom user models using AbstractUser or AbstractBaseUser.
class CustomUser(AbstractUser):
# settings.py
AUTH_USER_MODEL = 'myapp.CustomUser'
Follow-up tip: Mention scenarios where custom user models are beneficial, like adding additional fields (e.g., phone number, address).
Example:
class Document(models.Model):
name = models.CharField(max_length=100)
file = models.FileField(upload_to='documents/')
# settings.py
MEDIA_URL = '/media/'
document = Document.objects.get(id=1)
print(document.file.url)
Answer:
'django.middleware.security.SecurityMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
SECURE_SSL_REDIRECT = True
SECURE_BROWSER_XSS_FILTER = True
●
26. What is the difference between Serializer and ModelSerializer in Django REST Framework?
Answer:
● Serializer:
○ Manually define all fields and validation logic.
Example:
class BlogSerializer(serializers.Serializer):
title = serializers.CharField(max_length=200)
content = serializers.CharField()
● ModelSerializer:
○ Automatically generates fields based on the model.
Example:
class BlogModelSerializer(serializers.ModelSerializer):
class Meta:
model = Blog
fields = '__all__'
27. How does Django's admin interface work, and how can it be customized?
Customizing Admin:
from django.contrib import admin
class BlogAdmin(admin.ModelAdmin):
admin.site.register(Blog, BlogAdmin)
Example:
def blog_list(request):
blogs = Blog.objects.all()
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
Answer: HTML (HyperText Markup Language) is the standard markup language used to create and structure web pages. It uses tags to define elements on a webpage.
Example:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Welcome to My Webpage</h1>
<p>This is a paragraph.</p>
</body>
</html>
Answer: Semantic tags clearly define the meaning of the content they contain, improving accessibility and SEO.
Examples:
Example:
<header>
<h1>Website Title</h1>
</header>
<section>
<article>
<h2>Article Title</h2>
</article>
</section>
<footer>
<p>Copyright © 2024</p>
</footer>
Answer:
● <div>:
○ A block-level element.
○ Used for structuring large sections of content.
Example:
<div>
<h2>Block Content</h2>
</div>
● <span>:
○ An inline element.
○ Used for styling small portions of text.
Example:
Answer:
Example:
<ol>
<li>First item</li>
<li>Second item</li>
</ol>
Example:
<ul>
<li>First item</li>
<li>Second item</li>
</ul>
Example:
<dl>
<dt>HTML</dt>
</dl>
Examples:
<meta charset="UTF-8">
Answer:
● Inline:
○ Occupies only the width of its content.
○ Does not start a new line.
○ Examples: <span>, <a>
Example:
● Block:
○ Occupies the entire width of its container.
○ Starts on a new line.
○ Examples: <div>, <p>
Example:
Example:
Answer: Attributes provide additional information about an HTML element. They are always defined in the opening tag.
Example:
Inline:
1.
Internal:
<script>
console.log('Hello, world!');
</script>
2.
External:
<script src="script.js"></script>
3.
Answer: The <canvas> element is used to draw graphics dynamically using JavaScript.
Example:
<script>
ctx.fillStyle = 'blue';
</script>
Answer:
● <iframe>:
○ Embeds another HTML document into the current one.
Example:
● <embed>:
○ Embeds external resources like PDFs, videos, or audio.
Example:
● <link>:
○ Used to link external resources, such as stylesheets.
Example:
● <a>:
○ Used to create hyperlinks.
Example:
Answer: Void elements are self-closing tags that don’t require a closing tag.
Examples:
<input type="text">
<br>
Answer:
● id:
Example:
<div id="header">Header</div>
○
● class:
○ Reusable identifier for multiple elements.
Example:
<div class="menu">Menu 1</div>
Answer: Data attributes store custom data in an element and are prefixed with data-.
Example:
<script>
</script>
Answer:
● <fieldset>:
○ Groups related form elements.
● <legend>:
○ Provides a caption for the <fieldset>.
Example:
<fieldset>
<legend>Personal Information</legend>
</fieldset>
CSS interview questions:
1. What is CSS?
Answer: CSS (Cascading Style Sheets) is used to style HTML elements. It defines the layout, colors, fonts, and overall presentation of a webpage.
Example:
<style>
body {
background-color: lightblue;
</style>
Answer:
1. Inline CSS:
2.
3. Internal CSS:
<style>
p{
color: green;
}
</style>
4.
5. External CSS:
○ Stored in an external file with a .css extension and linked using the <link> tag.
6.
3. What is the difference between relative, absolute, fixed, and sticky positioning in CSS?
Answer:
● relative:
div {
position: relative;
top: 10px;
●
● absolute:
○ Positioned relative to the nearest positioned ancestor (or the viewport if none exist).
div {
position: absolute;
top: 10px;
●
● fixed:
div {
position: fixed;
top: 10px;
}
●
● sticky:
div {
position: sticky;
top: 10px;
Answer: Pseudo-classes define the state of an element, such as hover, focus, or visited.
Examples:
a:hover {
color: red;
tr:nth-child(even) {
background-color: lightgray;
Answer: Pseudo-elements style specific parts of an element, such as the first letter or before/after content.
Examples:
::before: Adds content before an element.
p::before {
font-weight: bold;
p::first-letter {
font-size: 2em;
color: blue;
Answer:
font-size: 16px;
Answer:
● id:
#header {
background-color: lightblue;
●
● class:
.menu {
color: green;
Example:
<div id="header">Header</div>
Answer:
● Inline:
○ Behaves like an inline element but allows setting width and height.
Example:
div {
display: inline-block;
width: 100px;
height: 50px;
background-color: lightblue;
Answer: Media queries make a website responsive by applying styles based on device properties like screen size or resolution.
Example:
body {
background-color: lightgray;
Answer:
Flexbox: Used for 1-dimensional layouts (row or column).
.container {
display: flex;
justify-content: center;
align-items: center;
.container {
display: grid;
grid-gap: 10px;
Answer: z-index controls the stacking order of elements. Higher values appear on top.
Example:
div {
position: absolute;
z-index: 10;
Answer:
Transitions: Smoothly change properties over time.
div {
div:hover {
background-color: lightblue;
@keyframes slide {
0% { transform: translateX(0); }
div {
Answer: box-sizing defines how the width and height of an element are calculated:
● content-box (default): Includes only the content size, excluding padding and border.
● border-box: Includes padding and border in the width and height.
Example:
div {
box-sizing: border-box;
width: 100px;
padding: 10px;
border: 5px solid black;
14. What are CSS variables, and how are they used?
Answer: CSS variables store reusable values. They are defined with -- and accessed using var().
Example:
:root {
--main-color: lightblue;
h1 {
color: var(--main-color);
15. What is the difference between visibility: hidden and display: none?
Answer:
● visibility: hidden: Hides the element but keeps its space in the layout.
● display: none: Hides the element and removes it from the layout.
Example:
.hidden {
visibility: hidden;
.none {
display: none;
}
JavaScript interview questions:
1. What is JavaScript?
Answer: JavaScript is a high-level, dynamically typed, interpreted programming language primarily used to create interactive and dynamic web pages. It is a client-side scripting language that
also supports server-side development with environments like Node.js.
Example:
Answer:
● var:
○ Function-scoped.
○ Can be redeclared and updated.
var x = 10;
●
● let:
○ Block-scoped.
○ Cannot be redeclared but can be updated.
let y = 10;
y = 20; // Valid
●
● const:
○ Block-scoped.
○ Cannot be updated or redeclared.
const z = 10;
z = 20; // Error: Assignment to constant variable
1. Primitive Types:
○ String
○ Number
○ Boolean
○ BigInt
○ Symbol
○ Undefined
○ Null
2. Non-Primitive Type:
○ Object
Example:
Answer:
●
=== (Strict Equality): Compares values without type conversion.
Answer: A closure is a function that retains access to its outer scope even after the outer function has executed.
Example:
function outer() {
let count = 0;
count++;
return count;
};
console.log(counter()); // 1
console.log(counter()); // 2
6. What are arrow functions, and how are they different from regular functions?
Answer: Arrow functions are a shorthand syntax for writing functions. They do not have their own this, arguments, or prototype.
Example:
// Regular function
function add(a, b) {
return a + b;
}
// Arrow function
console.log(add(2, 3)); // 5
console.log(addArrow(2, 3)); // 5
Key Difference: Arrow functions inherit this from their surrounding scope, while regular functions have their own this.
Answer:
Synchronous: Code executes line-by-line, blocking subsequent operations until the current one completes.
console.log("Start");
console.log("End");
Asynchronous: Code allows other operations to continue while waiting for a task to complete.
console.log("Start");
console.log("End");
Example:
Answer: this refers to the object that is currently executing the function. Its value depends on how the function is called:
Example:
const obj = {
value: 42,
getValue: function () {
return this.value;
};
console.log(obj.getValue()); // 42
Answer: Event delegation is a technique where a parent element handles events for its child elements using event bubbling.
Example:
});
11. Explain the call(), apply(), and bind() methods.
Answer:
function greet(greeting) {
console.log(`${greeting}, ${this.name}`);
bind(): Returns a new function with this bound to the provided value.
Answer: Prototypes are objects from which other objects inherit properties and methods.
Example:
function Person(name) {
this.name = name;
Person.prototype.greet = function () {
};
const john = new Person("John");
Answer: Hoisting moves declarations to the top of their scope during compilation. Variable initializations are not hoisted.
Example:
console.log(a); // undefined
var a = 10;
let b = 20;
14. What is the difference between shallow copy and deep copy?
Answer:
const obj = { a: 1, b: { c: 2 } };
shallowCopy.b.c = 3;
console.log(obj.b.c); // 3
deepCopy.b.c = 4;
console.log(obj.b.c); // 2
Answer: The event loop is responsible for managing the execution of asynchronous code by checking the call stack and callback queue.
Example:
console.log("Start");
console.log("End");