0% found this document useful (0 votes)
113 views9 pages

TCS Interview Questions Must

The document provides a comprehensive list of interview questions and answers related to Python programming, covering topics such as introduction, variables, data types, operators, control statements, loops, functions, OOP concepts, exception handling, and practical aspects. Key features of Python, its applications, and coding examples are included to illustrate concepts. Additionally, it emphasizes best practices like PEP8 for writing clean code.

Uploaded by

Monisha Jain
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)
113 views9 pages

TCS Interview Questions Must

The document provides a comprehensive list of interview questions and answers related to Python programming, covering topics such as introduction, variables, data types, operators, control statements, loops, functions, OOP concepts, exception handling, and practical aspects. Key features of Python, its applications, and coding examples are included to illustrate concepts. Additionally, it emphasizes best practices like PEP8 for writing clean code.

Uploaded by

Monisha Jain
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

TCS INTERVIEW QUESTIONS MUST

🟢 Introduction & Basics

1. Who developed Python, when was it released, and where was it created?
Python was developed by Guido van Rossum in the late 1980s at CWI (Centrum Wiskunde &
Informatica) in the Netherlands. The first release was in 1991.

2. What are some key features of Python that make it popular?

o Simple and easy to learn

o Interpreted language

o Dynamically typed

o Extensive standard library

o Object-oriented

o Cross-platform support

3. List a few real-world applications where Python is widely used.

o Web development (Django, Flask)

o Data science and machine learning

o Automation and scripting

o Desktop applications

o Networking and cloud services

4. How do you write a comment in Python? Explain the difference between single-line and multi-line
comments.

o Single-line comment: start with #

python

CopyEdit

# This is a comment

o Multi-line comment: Use multiple # or triple quotes (''' or """)

python

CopyEdit

'''

This is a

multi-line comment

'''
5. What is the significance of indentation in Python?
Indentation defines code blocks. It replaces braces {} used in other languages. Improper indentation
leads to errors.

🟢 Variables, Data Types, and Keywords

6. How do you declare and assign a variable in Python? Does Python require explicit type declaration?
Just write:

python

CopyEdit

x = 10

name = "Alice"

No need for explicit type declaration; Python is dynamically typed.

7. What are the basic data types available in Python? Give examples.

o int (e.g., 5)

o float (e.g., 3.14)

o str (e.g., "Hello")

o bool (e.g., True)

o list (e.g., [1, 2, 3])

o tuple (e.g., (1, 2))

o dict (e.g., {"a": 1})

o set (e.g., {1, 2, 3})

8. What are Python keywords? Can you name at least five?


Keywords are reserved words with special meaning.
Examples: if, else, for, while, def, return, import

9. How do you check the data type of a variable?


Use the type() function:

python

CopyEdit

x=5

print(type(x)) # Output: <class 'int'>

🟢 Operators

10. What are the different types of operators in Python? Explain with examples.

o Arithmetic: +, -, *, /, //, %, **

o Comparison: ==, !=, >, <, >=, <=


o Logical: and, or, not

o Assignment: =, +=, -=

o Bitwise: &, |, ^, ~, <<, >>

11. What is the difference between == and is operators?

o == compares values.

o is compares identity (memory location).

Example:

python

CopyEdit

a = [1, 2]

b = [1, 2]

print(a == b) # True (values same)

print(a is b) # False (different objects)

🟢 Control Statements

12. How does the if...elif...else statement work in Python? Give an example.
It checks conditions in order:

python

CopyEdit

x = 10

if x > 0:

print("Positive")

elif x == 0:

print("Zero")

else:

print("Negative")

13. Does Python have a switch statement? If not, how do you implement switch-like behavior?
No, Python doesn’t have a switch. Use if-elif-else or a dictionary mapping:

python

CopyEdit

def switch(case):

return {

1: "One",

2: "Two"
}.get(case, "Default")

🟢 Loops

14. How is a while loop different from a for loop in Python?

o while: runs as long as a condition is True.

o for: iterates over a sequence (list, range, etc.).

15. Write a Python for loop to print numbers from 1 to 5.

python

CopyEdit

for i in range(1, 6):

print(i)

16. How do you iterate over a list using a for each loop?

python

CopyEdit

items = [10, 20, 30]

for item in items:

print(item)

🟢 Break, Continue, Pass

17. What is the purpose of break, continue, and pass statements? Explain with examples.

o break: exits loop immediately.

python

CopyEdit

for i in range(5):

if i == 3:

break

print(i)

o continue: skips current iteration.

python

CopyEdit

for i in range(5):

if i == 3:

continue
print(i)

o pass: does nothing (placeholder).

python

CopyEdit

def func():

pass

🟢 Functions

18. How do you define a function in Python? Provide a basic example.

python

CopyEdit

def greet():

print("Hello!")

19. What is the difference between a function and a method in Python?

o Function: standalone block of code.

o Method: function that belongs to an object (e.g., list methods).

20. Can a Python function return multiple values? How?


Yes, by returning a tuple:

python

CopyEdit

def get_data():

return 1, 2, 3

x, y, z = get_data()

EXTRA BUT IMP

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

o List: mutable, can be changed (e.g., list[0]=10).

o Tuple: immutable, cannot be changed once created.

2. What is slicing? Show an example of slicing a list.

o Slicing extracts parts of a sequence:


python

CopyEdit

nums = [0, 1, 2, 3, 4]

slice = nums[1:4] # [1, 2, 3]

3. How does Python handle memory management and garbage collection?

o Python has automatic memory management using reference counting and a


garbage collector to clean unused objects.

4. What is list comprehension? Write an example.

o Concise way to create lists:

python

CopyEdit

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

5. How can you reverse a list in Python?

o Using reverse() method or slicing:

python

CopyEdit

nums.reverse()

# or

rev = nums[::-1]

6. What is a dictionary? How do you add and remove key-value pairs?

o Dictionary: unordered collection of key-value pairs.

python

CopyEdit

d = {'a':1}

d['b'] = 2 # Add

del d['a'] # Remove

7. Explain the difference between append() and extend() methods in lists.

o append(): adds one element to the end.

o extend(): adds all elements from another iterable.

8. How can you copy objects in Python? Explain shallow copy and deep copy.

o Shallow copy: copies references (use copy.copy()).


o Deep copy: copies nested objects (use copy.deepcopy()).

9. What are lambda functions? Give an example of usage.

o Anonymous, one-line functions:

python

CopyEdit

add = lambda x,y: x+y

print(add(2,3)) # 5

10. What is the map() function? How does it work?

o Applies a function to all items in an iterable:

python

CopyEdit

nums = [1,2,3]

squares = list(map(lambda x:x*x, nums))

🟢 OOP Concepts in Python

11. How do you define a class in Python?

python

CopyEdit

class MyClass:

pass

12. What is self in Python classes?

o A reference to the current instance of the class; used to access attributes and
methods.

13. What is inheritance? Show an example of single inheritance.

o A class inherits attributes/methods from another class:

python

CopyEdit

class Parent:

pass

class Child(Parent):

pass
14. What is the difference between __init__ and __str__ methods?

o __init__: constructor, runs when object is created.

o __str__: returns string representation when you print the object.

🟢 Exception Handling

15. How do you handle exceptions in Python? Show an example using try and except.

python

CopyEdit

try:

x = 1/0

except ZeroDivisionError:

print("Cannot divide by zero.")

16. What is the purpose of the finally block?

o Runs always, even if there is an error or return statement. Used for cleanup.

python

CopyEdit

try:

x=5/1

finally:

print("Cleanup code runs.")

17. How do you read and write files in Python? Show basic syntax.
✅ Reading a file:

python

CopyEdit

f = open("file.txt", "r")

content = f.read()

f.close()

✅ Writing to a file:

python

CopyEdit
f = open("file.txt", "w")

f.write("Hello World")

f.close()

✅ Using with (auto-closes the file):

python

CopyEdit

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

content = f.read()

18. What are modules and packages in Python?

 Module: A single .py file containing functions, classes, or variables you can reuse.
Example: math, random, or your own mymodule.py.

 Package: A collection of modules organized in a directory with an __init__.py file.

19. How can you import specific functions from a module?


Use from ... import ... syntax:

python

CopyEdit

from math import sqrt, pi

print(sqrt(16))

🟢 Miscellaneous & Practical

20. What is PEP8 and why is it important?

 PEP8 is the Python Enhancement Proposal 8.

 It is the style guide for writing clean, readable Python code (e.g., naming conventions,
indentation, line length).

 Following PEP8 makes your code consistent and easier to read and maintain.

You might also like