KEMBAR78
Basic Python Interview Questions | PDF | Python (Programming Language) | Object Oriented Programming
0% found this document useful (0 votes)
4 views13 pages

Basic Python Interview Questions

The document provides a comprehensive list of basic and intermediate Python interview questions and answers, covering topics such as data types, control flow, functions, and memory management. It also includes a section on Django interview questions, detailing its features, architecture, and ORM. This resource is aimed at freshers and those preparing for entry-level Python roles.

Uploaded by

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

Basic Python Interview Questions

The document provides a comprehensive list of basic and intermediate Python interview questions and answers, covering topics such as data types, control flow, functions, and memory management. It also includes a section on Django interview questions, detailing its features, architecture, and ORM. This resource is aimed at freshers and those preparing for entry-level Python roles.

Uploaded by

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

Basic Python Interview Questions

1. What is Python?

Answer:
Python is a high-level, interpreted, general-purpose programming language. It
emphasizes code readability and has a simple, easy-to-learn syntax.

2. What are the key features of Python?

Answer:

Easy to learn and read

Interpreted language

Dynamically typed

Supports OOP (Object-Oriented Programming)

Large standard library

Cross-platform

3. What is the difference between a list and a tuple in Python?

Answer:

Feature List Tuple


Mutability Mutable Immutable
Syntax [1, 2, 3] (1, 2, 3)
Performance Slower Faster
4. What are Python's data types?

Answer:

Numeric: int, float, complex

Sequence: list, tuple, range

Text: str

Set: set, frozenset

Mapping: dict

Boolean: bool

None: NoneType

5. How is memory managed in Python?

Answer:
Python uses:

Automatic garbage collection

Reference counting

Private heap space for memory allocation


6. What is PEP 8?

Answer:
PEP 8 is Python's style guide for writing clean, readable, and consistent code.

7. What are Python functions?

Answer:
Functions in Python are defined using the def keyword and are used to encapsulate
reusable blocks of code.

def greet(name):
return f"Hello, {name}"

8. What is the difference between is and == in Python?

Answer:

== compares values.

is compares identities (memory addresses).

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

a == b # True
a is b # False

9. What are Python’s control flow statements?

Answer:

Conditional: if, elif, else

Loops: for, while

Loop control: break, continue, pass

10. What are lambda functions?

Answer:
Anonymous functions defined using the lambda keyword.

add = lambda x, y: x + y
print(add(3, 4)) # Output: 7

🔹 Intermediate-Level Questions (Still for Freshers)


11. What is a Python module and package?

Answer:

Module: A single Python file (e.g. math.py)

Package: A folder containing __init__.py and one or more modules

12. What is a dictionary in Python?

Answer:
A collection of key-value pairs.

person = {'name': 'Alice', 'age': 25}


print(person['name']) # Output: Alice

13. What are list comprehensions?

Answer:
A concise way to create lists.

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


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

14. What is the difference between append() and extend()?

Answer:

append() adds a single item.

extend() adds all items from another iterable.

a = [1, 2]
a.append([3, 4]) # [1, 2, [3, 4]]
a.extend([5, 6]) # [1, 2, [3, 4], 5, 6]

15. What is exception handling in Python?

Answer:
Use try, except, finally blocks to handle runtime errors.

try:
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
finally:
print("Done")

Would you like:

An MCQ-style version?

More advanced questions?

A PDF download of these questions?

Questions specifically for a job role (like Data Analyst, Backend Dev, etc.)?

Let me know!

You said:
is python object oriented language
ChatGPT said:

Yes, Python is an object-oriented programming (OOP) language.

✅ Explanation:

Python supports object-oriented programming, which means it allows you to:


Define classes

Create objects

Use concepts like inheritance, encapsulation, polymorphism, and abstraction

🔹 Example of OOP in Python:


class Person:
def __init__(self, name, age): # Constructor
self.name = name
self.age = age

def greet(self): # Method


print(f"Hello, my name is {self.name} and I am {self.age} years old.")

# Creating an object
p1 = Person("Alice", 25)
p1.greet()

Output:

Hello, my name is Alice and I am 25 years old.

🔸 OOP Concepts Supported by Python:


Concept Supported in Python? Example
Class ✅ Yes class MyClass:
Object ✅ Yes obj = MyClass()
Inheritance ✅ Yes class B(A):
Polymorphism ✅ Yes Method overriding, duck typing
Encapsulation ✅ Yes Using _ and __ for privacy
Abstraction ✅ Yes Via abstract base classes
❗ Note:

Python is multi-paradigm — it supports:

Procedural programming

Object-oriented programming

Functional programming (like using map(), lambda, etc.)

Would you like a comparison of Python vs Java in OOP style? Or a quiz to test your
OOP knowledge?

You said:
core python basic interview questions and answers
ChatGPT said:

Here’s a list of Core Python Basic Interview Questions and Answers — perfect for
freshers or anyone preparing for an entry-level Python role.

✅ Core Python – Basic Interview Questions and Answers


1. What is Python?

Answer:
Python is a high-level, interpreted, general-purpose programming language. It is
known for its clean syntax and readability, making it suitable for beginners and
professionals.

2. What are the key features of Python?

Answer:

Easy to learn and use

Interpreted language

Dynamically typed

Object-oriented

Extensive standard libraries

Open-source and community-driven

Cross-platform compatibility

3. What is the difference between a variable and a constant?

Answer:

Variable: Value can change during execution.

Constant: Value remains the same throughout the program (by convention, use
uppercase names, but Python doesn't enforce true constants).

4. What are Python’s basic data types?

Answer:

int – Integer

float – Floating point number

str – String

bool – Boolean (True/False)

list, tuple, set, dict – Collections

5. What is the difference between a list and a tuple?

Answer:

Feature List ([]) Tuple (())


Mutability Mutable Immutable
Performance Slower Faster
Use Case Dynamic data Fixed data
6. What is a dictionary in Python?

Answer:
A dictionary is an unordered collection of key-value pairs.

person = {'name': 'Alice', 'age': 25}


print(person['name']) # Output: Alice
7. What is the use of type() and id() in Python?

Answer:

type() → Returns the data type of an object.

id() → Returns the memory address (identity) of an object.

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

Answer:

== checks if values are equal.

is checks if identities (memory locations) are the same.

9. What are conditional statements in Python?

Answer:
Used to make decisions:

if x > 0:
print("Positive")
elif x < 0:
print("Negative")
else:
print("Zero")

10. What is a loop in Python?

Answer:
Loops allow repeated execution of code:

for loop

while loop

for i in range(3):
print(i) # 0 1 2

11. What is the difference between break, continue, and pass?

Answer:

Keyword Description
break Exits the loop
continue Skips to next iteration
pass Placeholder, does nothing
12. What are functions in Python?

Answer:
Functions are reusable blocks of code defined using the def keyword.

def greet(name):
return "Hello " + name

13. What is a lambda function?

Answer:
A lambda is an anonymous (unnamed) function.

add = lambda x, y: x + y
print(add(2, 3)) # Output: 5

14. How is memory managed in Python?

Answer:

Python uses automatic garbage collection.

Memory is managed using reference counting and generational GC.

15. What is a module and a package in Python?

Answer:

Module: A Python file (.py) containing functions and classes.

Package: A directory with __init__.py and modules.

16. What are Python keywords?

Answer:
Reserved words that have special meaning, like if, for, while, def, class, import,
etc. You can't use them as variable names.

17. What is the use of *args and **kwargs?

Answer:

*args → Allows function to accept variable number of positional arguments.

**kwargs → Accepts variable number of keyword arguments.

def func(*args, **kwargs):


print(args)
print(kwargs)

18. What is exception handling in Python?

Answer:
Used to handle runtime errors using:

try:
# risky code
except ExceptionType:
# handle error
finally:
# always executes

19. What are Python’s built-in data structures?

Answer:

List

Tuple
Set

Dictionary

20. What is the purpose of the self keyword in Python?

Answer:

self represents the instance of the class.

It is used to access instance variables and methods inside the class.

Would you like:

This content as a PDF?

MCQs or coding questions too?

A version specific to job roles like Data Analyst, Backend Developer, etc.?

Let me know how you'd like to continue.

You said:
more questions
ChatGPT said:

Absolutely! Here's another set of core Python interview questions — still beginner-
friendly but with a slight increase in depth to help you prepare better.

✅ More Core Python Interview Questions and Answers


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

Answer:

Feature Python 2 Python 3


Print Statement print "Hello" print("Hello")
Division Integer division True division
Unicode Not default Default for strings
End of life Yes (Jan 2020) Actively supported
22. What is a set in Python?

Answer:
A set is an unordered, mutable collection of unique elements.

s = {1, 2, 2, 3}
print(s) # Output: {1, 2, 3}

23. What is the difference between remove() and pop() in a list?

Answer:

remove(x) → Removes the first occurrence of value x.

pop(i) → Removes the item at index i (default is last item).

24. What are Python’s built-in functions?

Answer:
Some common built-in functions:
len()

type()

int(), str(), float()

input(), print()

range()

sum(), min(), max()

sorted(), reversed()

25. What are Python decorators?

Answer:
A decorator is a function that takes another function as input and extends or
modifies its behavior.

def decorator(func):
def wrapper():
print("Before")
func()
print("After")
return wrapper

@decorator
def say_hello():
print("Hello")

say_hello()

26. What is slicing in Python?

Answer:
Slicing is used to extract parts of sequences (strings, lists, tuples).

s = "Python"
print(s[0:3]) # Output: Pyt

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

Answer:

copy() → Shallow copy (copies outer object, not nested ones).

deepcopy() → Deep copy (copies everything, including nested objects).

import copy
copy.copy() # Shallow copy
copy.deepcopy() # Deep copy

28. How to handle exceptions in Python?

Answer:

try:
x = int("abc")
except ValueError:
print("Invalid input")

**29. What are *args and kwargs used for?

Answer:

*args: Allows you to pass a variable number of positional arguments.

**kwargs: Allows you to pass a variable number of keyword arguments.

30. What is the difference between a class and an object?

Answer:

Class: Blueprint for creating objects.

Object: An instance of a class.

31. What is recursion in Python?

Answer:
Recursion is a function that calls itself.

def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)

32. What are global and local variables?

Answer:

Local: Defined inside a function.

Global: Defined outside all functions and can be accessed everywhere.

33. How do you open and read a file in Python?

Answer:

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


content = f.read()
print(content)

34. What is list comprehension?

Answer:
A compact way to create lists.

squares = [x*x for x in range(5)] # [0, 1, 4, 9, 16]

35. What is the use of __init__() in a class?

Answer:
It is the constructor method — automatically called when an object is created.

class Person:
def __init__(self, name):
self.name = name

36. What are Python’s logical operators?

Answer:

and: True if both are true

or: True if at least one is true

not: Inverts the truth value

37. What is a docstring?

Answer:
A documentation string written as the first statement in a function/class/module.

def greet():
"""This function greets the user."""
print("Hello")

38. What are Python namespaces?

Answer:
A namespace is a container where names are mapped to objects. Python uses
namespaces to avoid name collisions.

39. What is the use of zip() in Python?

Answer:
Combines multiple iterables into one.

a = [1, 2]
b = ['a', 'b']
print(list(zip(a, b))) # [(1, 'a'), (2, 'b')]

40. What is the map() function in Python?

Answer:
Applies a function to each item in an iterable.

nums = [1, 2, 3]
squared = list(map(lambda x: x**2, nums)) # [1, 4, 9]

Would you like:

A PDF file of all these questions?

A set of Python MCQs or coding challenges?

Questions tailored for a specific role or company?

Let me know how you want to continue!

You said:
django questions
ChatGPT said:
Great! Here's a set of Django interview questions and answers tailored for freshers
or junior-level developers.

✅ Basic Django Interview Questions and Answers


1. What is Django?

Answer:
Django is a high-level Python web framework that allows rapid development of secure
and maintainable websites. It follows the Model-View-Template (MVT) architecture.

2. What are the key features of Django?

Answer:

Fast development

Secure (prevents SQL injection, CSRF, etc.)

Scalable

ORM (Object-Relational Mapping)

Admin interface

Built-in authentication system

Large community & extensive documentation

3. What is the MVT architecture in Django?

Answer:

Component Description
Model Represents database schema (tables)
View Contains business logic
Template Handles presentation (HTML output)
4. What is a Django model?

Answer:
A model is a Python class that maps to a table in the database. Django models
define the structure of stored data.

from django.db import models

class Student(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()

5. How do you create a Django project?

Answer:

django-admin startproject project_name

6. How do you create a Django app?

Answer:
python manage.py startapp app_name

7. What is the purpose of manage.py?

Answer:

It’s a command-line utility to interact with the Django project.

Used for tasks like running the server, migrations, and database operations.

8. What is Django ORM?

Answer:
ORM (Object Relational Mapper) allows you to interact with the database using
Python objects instead of writing SQL queries.

Example:

Student.objects.all() # SELECT * FROM student;

You might also like