KEMBAR78
Full Stack QNA | PDF | Html Element | Html
0% found this document useful (0 votes)
4 views50 pages

Full Stack QNA

The document outlines key features of Python, including its ease of use, dynamic typing, and extensive libraries. It covers various data types, differences between lists, tuples, and sets, and concepts like decorators, memory management, and exception handling. Additionally, it provides insights into Django, its architecture, ORM, middleware, and REST API creation.

Uploaded by

yagarwal943
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views50 pages

Full Stack QNA

The document outlines key features of Python, including its ease of use, dynamic typing, and extensive libraries. It covers various data types, differences between lists, tuples, and sets, and concepts like decorators, memory management, and exception handling. Additionally, it provides insights into Django, its architecture, ORM, middleware, and REST API creation.

Uploaded by

yagarwal943
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

1. What are Python's key features?

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.

2. Explain Python's data types.

Answer: Python has several built-in data types:

● Numeric types: int, float, complex


● Sequence types: list, tuple, range
● Text type: str
● Set types: set, frozenset
● Mapping type: dict
● Boolean type: bool
● Binary types: bytes, bytearray, memoryview

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.

3. What is the difference between a list, tuple, and set?

Answer:

● List: Mutable, ordered, and allows duplicate elements. Example: [1, 2, 2, 3]


● Tuple: Immutable and ordered. Example: (1, 2, 3)
● Set: Mutable, unordered, and does not allow duplicates. Example: {1, 2, 3}

Follow-up tip: Explain how you would use a tuple for constant data, a list for dynamic arrays, and a set for unique data.

4. What is the difference between deepcopy() and copy()?

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

original = [[1, 2], [3, 4]]


shallow_copy = copy.copy(original)
deep_copy = copy.deepcopy(original)

shallow_copy[0][0] = 99
print(original) # Output: [[99, 2], [3, 4]]
print(deep_copy) # Output: [[1, 2], [3, 4]]

5. What are Python decorators?

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.

6. Explain Python's Global Interpreter Lock (GIL).

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.

7. What are Python's *args and **kwargs?

Answer:

● *args: Allows passing a variable number of positional arguments.


● **kwargs: Allows passing a variable number of keyword arguments.

Example:

def example_function(*args, **kwargs):


print("Positional arguments:", args)
print("Keyword arguments:", kwargs)

example_function(1, 2, 3, name="Alice", age=30)

Follow-up tip: Mention how they make functions more flexible and adaptable.
8. How does Python manage memory?

Answer: Python uses dynamic memory allocation managed by:

● Reference Counting: Keeps track of the number of references to an object.


● Garbage Collection: Reclaims memory for objects with zero references.

Follow-up tip: Highlight how you can use gc (garbage collector) module to optimize memory usage.

9. What is the difference between Python 2 and Python 3?

Answer:

● Syntax: print is a statement in Python 2 but a function in Python 3.


● Division: Python 3 uses true division (/) and floor division (//), while Python 2 does integer division by default.
● Unicode Support: Strings in Python 3 are Unicode by default.

Follow-up tip: Emphasize Python 3's advantages and its current industry relevance.

10. What are Python's popular frameworks and libraries?

Answer:

● Web Development: Django, Flask, FastAPI


● Data Analysis and Machine Learning: NumPy, pandas, Scikit-learn, TensorFlow, PyTorch
● Automation and Scripting: Selenium, PyAutoGUI
● Game Development: Pygame

Follow-up tip: Mention the framework/library you have experience with and provide a short example or use case.

Additional Tips for Python Interviews:

● 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.

11. How is Python's is operator different from ==?

Answer:

● is operator: Checks if two variables reference the same object in memory.


● == operator: Checks if the values of two variables are equal.

Example:

a = [1, 2, 3]
b = [1, 2, 3]
c=a

print(a == b) # True, values are the same


print(a is b) # False, different objects in memory
print(a is c) # True, same memory reference

12. What are Python's comprehensions?

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:

squares = [x**2 for x in range(5)]


print(squares) # [0, 1, 4, 9, 16]

Dictionary comprehension:

squares_dict = {x: x**2 for x in range(5)}


print(squares_dict) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Set comprehension:

unique_squares = {x**2 for x in range(5)}


print(unique_squares) # {0, 1, 4, 9, 16}

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.")

15. What is a metaclass in Python?

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.

16. Explain @staticmethod and @classmethod in Python.

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}")

MyClass.static_method() # I don't access instance or class.


MyClass.class_method() # I can access the class: <class '__main__.MyClass'>

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

18. What is the difference between Python's isinstance() and type()?

Answer:

● isinstance(): Checks if an object belongs to a class or its subclass.


● type(): Checks the exact type of an object.

Example:

class Parent: pass


class Child(Parent): pass

obj = Child()
print(isinstance(obj, Parent)) # True
print(type(obj) == Parent) # False

19. What are Python's magic methods?

Answer: Magic methods (dunder methods) are special methods surrounded by double underscores and used to define object behavior.

Common examples:

● __init__: Constructor for initializing objects.


● __str__: Defines string representation.
● __add__: Overloads the + operator.
● __len__: Returns the length of an object.

Example:

class Point:
def __init__(self, x, y):
self.x = x
self.y = y

def __add__(self, other):


return Point(self.x + other.x, self.y + other.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)

20. How does Python's with statement work?

Answer: The with statement ensures proper acquisition and release of resources using context managers.

Example:

with open('file.txt', 'w') as f:


f.write('Hello, world!')
# File is automatically closed after the block

Follow-up tip: Discuss how with simplifies exception handling when dealing with file I/O or database connections.

21. What is the purpose of Python's global and nonlocal keywords?

Answer:

● global: Declares a variable as global, allowing modification inside a function.


● nonlocal: Declares a variable in the nearest enclosing scope that is not global.

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

async def greet():


print("Hello")
await asyncio.sleep(1)
print("World")

asyncio.run(greet())

Django interview questions

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:

● Built-in admin interface.


● ORM for database interaction.
● Scalability and reusability.

Follow-up tip: Highlight Django's ability to integrate with other libraries and its wide use in e-commerce, social networks, and CMS development.

2. Explain the MVT architecture in Django.

Answer:

● Model: Represents the database structure and handles data access.


● View: Handles business logic and processes user requests.
● Template: Defines the structure and layout of the webpage displayed to the user.

Follow-up tip: Use a real-world example, such as a blog application:

● Model: Defines the blog posts.


● View: Fetches and renders posts to the template.
● Template: Displays the posts on a web page.
3. How does Django handle database migrations?

Answer: Django uses migrations to manage database schema changes. Key commands include:

● makemigrations: Detects model changes and creates migration files.


● migrate: Applies migrations to the database.

Example:

python manage.py makemigrations


python manage.py migrate

Follow-up tip: Mention that migrations ensure consistency across development and production environments.

4. How does Django handle forms?

Answer: Django provides forms to handle user input, including form validation and rendering.

Example:

from django import forms

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})

5. How does Django handle static files and media files?


Answer:

● Static Files: Used for CSS, JavaScript, and images.


● Media Files: Used for user-uploaded content.

Settings:

# settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / 'static']

MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'

Example for URLs:

# urls.py
from django.conf import settings
from django.conf.urls.static import static

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

6. How does Django's ORM work?

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.

7. What are middleware in Django?

Answer: Middleware are components executed during request/response processing. Common examples include:
● SecurityMiddleware: Handles security headers.
● AuthenticationMiddleware: Adds user authentication.

Example of custom middleware:

class MyCustomMiddleware:
def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):


print("Before view")
response = self.get_response(request)
print("After view")
return response

8. How does Django handle authentication?

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.

9. What is the difference between @login_required and permission_required decorators?

Answer:

● @login_required: Ensures the user is authenticated before accessing a view.


● @permission_required: Checks if a user has a specific permission.

Example:

from django.contrib.auth.decorators import login_required, permission_required

@login_required
def profile_view(request):
pass

@permission_required('app_name.permission_name')
def special_view(request):
pass

10. How do you create a REST API in Django?

Answer: Using Django REST Framework (DRF), you can build APIs easily.

Example:

Install DRF:

pip install djangorestframework

1.

Serializer:

from rest_framework import serializers


from .models import Blog

class BlogSerializer(serializers.ModelSerializer):
class Meta:
model = Blog
fields = '__all__'

2.

Views:

from rest_framework.views import APIView


from rest_framework.response import Response
from .models import Blog
from .serializers import BlogSerializer

class BlogList(APIView):
def get(self, request):
blogs = Blog.objects.all()
serializer = BlogSerializer(blogs, many=True)
return Response(serializer.data)

3.

URLs:

from django.urls import path


from .views import BlogList

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.

11. How does Django handle CSRF protection?

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>

12. How do you optimize Django queries?

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:

from django.db.models.signals import post_save


from django.dispatch import receiver
from .models import Blog

@receiver(post_save, sender=Blog)
def notify_admin(sender, instance, created, **kwargs):
if created:
print(f"New blog created: {instance.title}")

14. What are Django's deployment best practices?

Answer:

● Use Gunicorn or uWSGI as a WSGI server.


● Use Nginx for serving static files.
● Set DEBUG = False in production.
● Use a secure SECRET_KEY and environment variables.
● Optimize database performance using indexing and query optimization.

15. How do you test Django applications?

Answer: Django provides a testing framework based on Python’s unittest.

Example:

from django.test import TestCase


from .models import Blog

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:

user = User.objects.get(id=1) # Returns a single User object

● filter():
○ Retrieves a QuerySet of all objects matching the query.
○ Returns an empty QuerySet if no objects are found.

Example:

users = User.objects.filter(is_active=True) # Returns a QuerySet of active users

17. How does Django's select_related differ from prefetch_related?

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:

blogs = Blog.objects.select_related('author').all() # Fetches blog and author data in one query

● prefetch_related:
○ Executes multiple queries and performs Python-level joins.
○ Best for many-to-many or reverse foreign key relationships.

Example:

blogs = Blog.objects.prefetch_related('tags').all() # Fetches blogs and related tags in separate queries


18. What are Django's built-in signals, and how are they used?

Answer: Django provides several built-in signals, including:

● pre_save / post_save: Triggered before/after a model instance is saved.


● pre_delete / post_delete: Triggered before/after a model instance is deleted.
● m2m_changed: Triggered when a many-to-many relationship is modified.

Example:

from django.db.models.signals import post_save

from django.dispatch import receiver

from .models import Blog

@receiver(post_save, sender=Blog)

def notify_on_blog_save(sender, instance, created, **kwargs):

if created:

print(f"New blog created: {instance.title}")

else:

print(f"Blog updated: {instance.title}")

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):

return render(request, 'home.html', {'message': 'Welcome!'})

● CBVs:
○ Use Python classes to handle views.
○ More reusable and modular.

Example:

from django.views import View

class HomeView(View):

def get(self, request):

return render(request, 'home.html', {'message': 'Welcome!'})

20. What is Django's ContentType framework, and how is it used?

Answer: The ContentType framework allows you to work with models in a generic way. It’s commonly used in permissions and generic relationships.

Example:

from django.contrib.contenttypes.models import ContentType

from django.contrib.auth.models import Permission

content_type = ContentType.objects.get(app_label='myapp', model='blog')

permission = Permission.objects.create(

codename='can_publish',

name='Can Publish Blogs',

content_type=content_type

21. How does Django handle caching?

Answer: Django supports multiple caching backends:

● File-based caching
● Database caching
● Memcached
● Redis

Example (File-based caching):

# settings.py

CACHES = {

'default': {

'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',

'LOCATION': '/var/tmp/django_cache',

Using cache in views:

from django.views.decorators.cache import cache_page

@cache_page(60 * 15) # Cache for 15 minutes

def my_view(request):

return HttpResponse("This is a cached response.")

22. What is the difference between ForeignKey, OneToOneField, and ManyToManyField in Django?

Answer:

● ForeignKey:

○ Defines a one-to-many relationship.


○ Example: A blog post belongs to one author, but an author can have multiple blog posts.

class Blog(models.Model):

author = models.ForeignKey(User, on_delete=models.CASCADE)


● OneToOneField:

○ Defines a one-to-one relationship.


○ Example: A user has one profile.

class Profile(models.Model):

user = models.OneToOneField(User, on_delete=models.CASCADE)


● ManyToManyField:

○ Defines a many-to-many relationship.


○ Example: A blog can have multiple tags, and a tag can belong to multiple blogs.

class Blog(models.Model):

tags = models.ManyToManyField(Tag)

23. How can you implement custom user models in Django?

Answer: Django allows creating custom user models using AbstractUser or AbstractBaseUser.

Example using AbstractUser:

from django.contrib.auth.models import AbstractUser

from django.db import models

class CustomUser(AbstractUser):

phone_number = models.CharField(max_length=15, unique=True)

# 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).

24. How does Django implement file uploads?

Answer: Django uses FileField or ImageField to handle file uploads.

Example:
class Document(models.Model):

name = models.CharField(max_length=100)

file = models.FileField(upload_to='documents/')

# settings.py

MEDIA_URL = '/media/'

MEDIA_ROOT = BASE_DIR / 'media'

# Accessing the uploaded file

document = Document.objects.get(id=1)

print(document.file.url)

25. How do you secure a Django application?

Answer:

● Set DEBUG = False in production.


● Use SECRET_KEY securely:
○ Avoid hardcoding; use environment variables.
● Enable CSRF protection.
● Validate user inputs: Prevent SQL injection and XSS attacks.

Use Django's security middleware:


MIDDLEWARE = [

'django.middleware.security.SecurityMiddleware',

'django.middleware.csrf.CsrfViewMiddleware',

Set secure headers:


SECURE_HSTS_SECONDS = 3600

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:

from rest_framework import serializers

class BlogSerializer(serializers.Serializer):

title = serializers.CharField(max_length=200)

content = serializers.CharField()

● ModelSerializer:
○ Automatically generates fields based on the model.

Example:

from rest_framework import serializers

from .models import Blog

class BlogModelSerializer(serializers.ModelSerializer):

class Meta:

model = Blog

fields = '__all__'

27. How does Django's admin interface work, and how can it be customized?

Answer: Django's admin interface provides a web-based UI for managing models.

Customizing Admin:
from django.contrib import admin

from .models import Blog

class BlogAdmin(admin.ModelAdmin):

list_display = ('title', 'author', 'published_date')

search_fields = ('title', 'content')

list_filter = ('published_date', 'author')

admin.site.register(Blog, BlogAdmin)

28. How do you implement pagination in Django?

Answer: Django provides a built-in Paginator class.

Example:

from django.core.paginator import Paginator

from django.shortcuts import render

def blog_list(request):

blogs = Blog.objects.all()

paginator = Paginator(blogs, 10) # 10 blogs per page

page_number = request.GET.get('page')

page_obj = paginator.get_page(page_number)

return render(request, 'blog_list.html', {'page_obj': page_obj})

HyperText Markup Language


1. What is HTML?

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>

<title>My First Webpage</title>

</head>

<body>

<h1>Welcome to My Webpage</h1>

<p>This is a paragraph.</p>

</body>

</html>

2. What are semantic tags in HTML?

Answer: Semantic tags clearly define the meaning of the content they contain, improving accessibility and SEO.

Examples:

● <header>: Defines the header of a page.


● <footer>: Defines the footer of a page.
● <article>: Represents a self-contained content block.
● <section>: Groups related content.

Example:

<header>

<h1>Website Title</h1>

</header>
<section>

<article>

<h2>Article Title</h2>

<p>Article content goes here.</p>

</article>

</section>

<footer>

<p>Copyright © 2024</p>

</footer>

3. What is the difference between <div> and <span>?

Answer:

● <div>:
○ A block-level element.
○ Used for structuring large sections of content.

Example:

<div>

<h2>Block Content</h2>

<p>This is a paragraph inside a div.</p>

</div>

● <span>:
○ An inline element.
○ Used for styling small portions of text.

Example:

<p>This is a <span style="color: red;">red text</span> inside a paragraph.</p>


4. What are the different types of lists in HTML?

Answer:

1. Ordered List (<ol>):


○ A list with numbered items.

Example:

<ol>

<li>First item</li>

<li>Second item</li>

</ol>

2. Unordered List (<ul>):


○ A list with bullet points.

Example:

<ul>

<li>First item</li>

<li>Second item</li>

</ul>

3. Definition List (<dl>):


○ A list of terms and their definitions.

Example:

<dl>

<dt>HTML</dt>

<dd>HyperText Markup Language</dd>

</dl>

5. What is the purpose of the <meta> tag?


Answer: The <meta> tag provides metadata about the HTML document, such as character encoding, viewport settings, or author information.

Examples:

Set character encoding:

<meta charset="UTF-8">

Responsive design settings:

<meta name="viewport" content="width=device-width, initial-scale=1.0">

Description for SEO:

<meta name="description" content="Learn about HTML basics.">

6. What is the difference between inline, block, and inline-block elements?

Answer:

● Inline:
○ Occupies only the width of its content.
○ Does not start a new line.
○ Examples: <span>, <a>

Example:

<p>This is an <span>inline</span> element.</p>

● Block:
○ Occupies the entire width of its container.
○ Starts on a new line.
○ Examples: <div>, <p>

Example:

<div>This is a block element.</div>

<p>This is another block element.</p>


● Inline-block:
○ Behaves like an inline element but allows setting width and height.
○ Example: <img>

Example:

<div style="display: inline-block; width: 100px; height: 50px; background-color: lightblue;"></div>

7. What are attributes in HTML?

Answer: Attributes provide additional information about an HTML element. They are always defined in the opening tag.

Example:

<a href="https://example.com" target="_blank" title="Visit Example">Visit Example</a>

● href: Specifies the link's URL.


● target: Opens the link in a new tab.
● title: Tooltip text.

8. How do you include JavaScript in an HTML document?

Answer: JavaScript can be included in three ways:

Inline:

<button onclick="alert('Button clicked!')">Click Me</button>

1.

Internal:

<script>

console.log('Hello, world!');

</script>

2.

External:

<script src="script.js"></script>
3.

9. What is the purpose of the <canvas> element in HTML?

Answer: The <canvas> element is used to draw graphics dynamically using JavaScript.

Example:

<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000;"></canvas>

<script>

const canvas = document.getElementById('myCanvas');

const ctx = canvas.getContext('2d');

ctx.fillStyle = 'blue';

ctx.fillRect(10, 10, 150, 75);

</script>

10. What is the difference between <iframe> and <embed>?

Answer:

● <iframe>:
○ Embeds another HTML document into the current one.

Example:

<iframe src="https://example.com" width="500" height="300"></iframe>

● <embed>:
○ Embeds external resources like PDFs, videos, or audio.

Example:

<embed src="sample.pdf" width="500" height="300" type="application/pdf">

11. What is the difference between <link> and <a> tags?


Answer:

● <link>:
○ Used to link external resources, such as stylesheets.

Example:

<link rel="stylesheet" href="styles.css">

● <a>:
○ Used to create hyperlinks.

Example:

<a href="https://example.com">Visit Example</a>

12. What are void elements in HTML?

Answer: Void elements are self-closing tags that don’t require a closing tag.

Examples:

<img src="image.jpg" alt="Image">

<input type="text">

<br>

13. What is the difference between id and class attributes?

Answer:

● id:

○ Unique identifier for a single element.

Example:
<div id="header">Header</div>


● class:
○ Reusable identifier for multiple elements.

Example:
<div class="menu">Menu 1</div>

<div class="menu">Menu 2</div>

14. What are data attributes in HTML?

Answer: Data attributes store custom data in an element and are prefixed with data-.

Example:

<div data-user-id="123" data-role="admin">User Info</div>

<script>

const div = document.querySelector('div');

console.log(div.dataset.userId); // Output: 123

console.log(div.dataset.role); // Output: admin

</script>

15. What is the purpose of the <fieldset> and <legend> tags?

Answer:

● <fieldset>:
○ Groups related form elements.
● <legend>:
○ Provides a caption for the <fieldset>.

Example:

<fieldset>

<legend>Personal Information</legend>

<label>Name: <input type="text"></label>

<label>Age: <input type="number"></label>

</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;

font-family: Arial, sans-serif;

</style>

2. What are the different types of CSS?

Answer:

1. Inline CSS:

○ Applied directly to an HTML element using the style attribute.

<p style="color: blue;">This is inline CSS.</p>

2.
3. Internal CSS:

○ Defined within a <style> tag in the <head> section.

<style>

p{

color: green;

}
</style>

4.
5. External CSS:

○ Stored in an external file with a .css extension and linked using the <link> tag.

<link rel="stylesheet" href="styles.css">

6.

3. What is the difference between relative, absolute, fixed, and sticky positioning in CSS?

Answer:

● relative:

○ Positioned relative to its normal position.

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:

○ Positioned relative to the viewport, remains fixed during scrolling.

div {

position: fixed;

top: 10px;
}


● sticky:

○ Switches between relative and fixed depending on the scroll position.

div {

position: sticky;

top: 10px;

4. What are pseudo-classes in CSS?

Answer: Pseudo-classes define the state of an element, such as hover, focus, or visited.

Examples:

:hover: Styles when an element is hovered over.

a:hover {

color: red;

:nth-child(n): Styles the nth child of a parent.

tr:nth-child(even) {

background-color: lightgray;

5. What are pseudo-elements in CSS?

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 {

content: "Note: ";

font-weight: bold;

::first-letter: Styles the first letter of a paragraph.

p::first-letter {

font-size: 2em;

color: blue;

6. What is the difference between em, rem, %, and px in CSS?

Answer:

px: Absolute unit; fixed size.

font-size: 16px;

em: Relative to the font size of its parent.

font-size: 1.5em; /* 1.5 times the parent font size */

rem: Relative to the root element's font size.

font-size: 1.5rem; /* 1.5 times the root font size */

%: Relative to the parent element's size.

width: 50%; /* 50% of the parent element's width */


7. What is the difference between id and class selectors in CSS?

Answer:

● id:

○ Unique, applied to one element.


○ Defined with #.

#header {

background-color: lightblue;


● class:

○ Reusable, applied to multiple elements.


○ Defined with ..

.menu {

color: green;

Example:

<div id="header">Header</div>

<div class="menu">Menu 1</div>

<div class="menu">Menu 2</div>

8. What is the difference between inline, block, and inline-block elements?

Answer:

● Inline:

○ Takes up only as much width as the content.


○ Examples: <span>, <a>
● Block:

○ Takes up the full width of the container.


○ Examples: <div>, <p>
● Inline-block:

○ Behaves like an inline element but allows setting width and height.

Example:

div {

display: inline-block;

width: 100px;

height: 50px;

background-color: lightblue;

9. What are CSS media queries?

Answer: Media queries make a website responsive by applying styles based on device properties like screen size or resolution.

Example:

@media (max-width: 768px) {

body {

background-color: lightgray;

10. What are CSS Grid and Flexbox?

Answer:
Flexbox: Used for 1-dimensional layouts (row or column).

.container {

display: flex;

justify-content: center;

align-items: center;

Grid: Used for 2-dimensional layouts (rows and columns).

.container {

display: grid;

grid-template-columns: 1fr 2fr;

grid-gap: 10px;

11. What is the z-index in CSS?

Answer: z-index controls the stacking order of elements. Higher values appear on top.

Example:

div {

position: absolute;

z-index: 10;

12. What are CSS transitions and animations?

Answer:
Transitions: Smoothly change properties over time.

div {

transition: background-color 0.5s ease;

div:hover {

background-color: lightblue;

Animations: Define complex movements using keyframes.

@keyframes slide {

0% { transform: translateX(0); }

100% { transform: translateX(100px); }

div {

animation: slide 2s infinite;

13. How does the box-sizing property work?

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:

console.log("Hello, World!"); // Outputs: Hello, World!

2. Explain the difference between let, const, and var.

Answer:

● var:

○ Function-scoped.
○ Can be redeclared and updated.

var x = 10;

var x = 20; // No error


● 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

3. What are JavaScript data types?

Answer: JavaScript has 8 data types:

1. Primitive Types:
○ String
○ Number
○ Boolean
○ BigInt
○ Symbol
○ Undefined
○ Null
2. Non-Primitive Type:
○ Object

Example:

let name = "John"; // String

let age = 30; // Number

let isActive = true; // Boolean

let bigInt = 123n; // BigInt

let data = null; // Null

let obj = { key: "value" }; // Object

4. What is the difference between == and ===?

Answer:

== (Abstract Equality): Compares values after type conversion.

console.log("5" == 5); // true


=== (Strict Equality): Compares values without type conversion.

console.log("5" === 5); // false

5. What is a closure in JavaScript?

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;

return function inner() {

count++;

return count;

};

const counter = outer();

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

const addArrow = (a, b) => a + b;

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.

7. What is the difference between synchronous and asynchronous JavaScript?

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");

setTimeout(() => console.log("Async Task"), 1000);

console.log("End");

// Output: Start, End, Async Task

8. What are promises in JavaScript?

Answer: A promise represents the eventual completion or failure of an asynchronous operation.

Example:

const promise = new Promise((resolve, reject) => {

setTimeout(() => resolve("Success!"), 1000);


});

promise.then(result => console.log(result)); // Success!

9. What is this in JavaScript?

Answer: this refers to the object that is currently executing the function. Its value depends on how the function is called:

● In a method, this refers to the object the method belongs to.


● In a function, this refers to the global object (window in browsers, global in Node.js) or undefined in strict mode.

Example:

const obj = {

value: 42,

getValue: function () {

return this.value;

};

console.log(obj.getValue()); // 42

10. What is event delegation in JavaScript?

Answer: Event delegation is a technique where a parent element handles events for its child elements using event bubbling.

Example:

document.getElementById("parent").addEventListener("click", function (event) {

if (event.target.tagName === "BUTTON") {

console.log("Button clicked:", event.target.textContent);

});
11. Explain the call(), apply(), and bind() methods.

Answer:

call(): Invokes a function with a specific this value and arguments.

function greet(greeting) {

console.log(`${greeting}, ${this.name}`);

const person = { name: "John" };

greet.call(person, "Hello"); // Hello, John

apply(): Similar to call(), but accepts arguments as an array.

greet.apply(person, ["Hi"]); // Hi, John

bind(): Returns a new function with this bound to the provided value.

const greetPerson = greet.bind(person);

greetPerson("Hey"); // Hey, John

12. What are JavaScript prototypes?

Answer: Prototypes are objects from which other objects inherit properties and methods.

Example:

function Person(name) {

this.name = name;

Person.prototype.greet = function () {

return `Hello, ${this.name}`;

};
const john = new Person("John");

console.log(john.greet()); // Hello, John

13. What is hoisting in JavaScript?

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;

console.log(b); // ReferenceError: Cannot access 'b' before initialization

let b = 20;

14. What is the difference between shallow copy and deep copy?

Answer:

● Shallow Copy: Copies only the first level of an object.


● Deep Copy: Recursively copies all levels of an object.

Example (Shallow Copy):

const obj = { a: 1, b: { c: 2 } };

const shallowCopy = { ...obj };

shallowCopy.b.c = 3;

console.log(obj.b.c); // 3

Example (Deep Copy):

const deepCopy = JSON.parse(JSON.stringify(obj));

deepCopy.b.c = 4;
console.log(obj.b.c); // 2

15. What is the event loop in JavaScript?

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");

setTimeout(() => console.log("Callback"), 0);

console.log("End");

// Output: Start, End, Callback

You might also like