Core Python Concepts for Interviews
Core Python Concepts for Interviews
Here’s a comprehensive list of Core Python Concepts that are frequently asked in interviews
(beginner to intermediate level) 👇
🧠 Core Python Concepts for Interview
🔹 1. Basic Syntax & Fundamentals
Python keywords and identifiers
Indentation and comments
Nested conditions
Loops:
for loop
while loop
break
continue
pass
🔹 3. Functions
Function definition and calling
Function arguments: positional, keyword, default, variable-length (*args, **kwargs)
Return values
Scope of variables (local, global)
🔹 4. Data Structures
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/44
🧩 Built-in Collections:
List → mutable, ordered
Tuple → immutable, ordered
🛠 Common Operations:
Indexing, slicing
Adding/removing elements
List comprehension
Dictionary comprehension
🔹 5. Strings
String creation and indexing
🔹 6. File Handling
Opening and closing files (open(), close())
🔹 7. Exception Handling
try, except, else, finally blocks
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/44
__init__ constructor
Decorators (@decorator_name)
Reference counting
id() function and object references
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/44
2. Explain shallow copy vs deep copy
Would you like me to make this into a PDF interview cheat sheet (1–2 pages, neatly formatted)?
It can be useful for quick revision before interviews.
Here’s a clear explanation of Variables and Data Types in Python with syntax and examples 👇
🧩 1. Variables in Python
🔹 Definition:
A variable is a name that stores a value in memory.
You don’t need to declare its type explicitly — Python assigns it automatically.
🧠 Syntax:
python
variable_name = value
💡 Examples:
python
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 4/44
Data Type Description Example Output Type
🔍 Example Code:
python
🖥️ Output:
python
10 <class 'int'>
3.14 <class 'float'>
Python <class 'str'>
True <class 'bool'>
(2+3j) <class 'complex'>
Would you like me to add a short exercise or question based on variables and data types next?
Here’s a clear and simple explanation of Type Conversion and Casting in Python with syntax and
examples 👇
🔄 Type Conversion and Casting
Python allows you to change the data type of a variable — this process is called type conversion (or
type casting).
🔹 1. Type Conversion
✅ Automatic (Implicit) Conversion — done by Python automatically.
✅ Explicit Conversion (Type Casting) — done manually using built-in functions.
🧠 1. Implicit Type Conversion
Python automatically converts one data type to another when needed, without losing data.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 5/44
💡 Example:
python
a = 5 # int
b = 2.5 # float
🖥️ Output:
javascript
7.5
<class 'float'>
💡 Examples:
python
s = "Hello"
num = int(s) # ❌ Error: cannot convert non-numeric string to int
🧩 You can only convert strings that contain numbers (e.g. "123") to int or float.
Would you like me to give a small exercise question next (like “convert given string and add numbers”)?
Here’s a clear explanation of if, elif, and else statements in Python with syntax and examples 👇
⚙️ Conditional Statements (if, elif, else)
These statements are used to make decisions in your Python program based on certain conditions.
🧠 1. Syntax:
python
if condition1:
# code to execute if condition1 is true
elif condition2:
# code to execute if condition2 is true
else:
# code to execute if all conditions are false
num = 10
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
🖥️ Output:
typescript
Positive number
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 7/44
python
marks = 85
🖥️ Output:
css
Grade B
num = 7
if num % 2 == 0:
print("Even number")
else:
print("Odd number")
🖥️ Output:
typescript
Odd number
⚠️ Notes:
Indentation (spaces or tabs) is very important in Python.
Would you like me to give a short practice question next (like “check if a number is positive, negative,
or zero”) for you to try?
Here’s a simple and clear explanation of Nested Conditions in Python with syntax and examples 👇
🧠 Nested Conditions in Python
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 8/44
A nested condition means using an if statement inside another if statement.
It helps when you need to check multiple levels of conditions.
🔹 Syntax:
python
if condition1:
if condition2:
# code runs if both condition1 and condition2 are true
else:
# code runs if condition1 is true but condition2 is false
else:
# code runs if condition1 is false
num = 8
if num > 0:
if num % 2 == 0:
print("The number is positive and even")
else:
print("The number is positive but odd")
else:
print("The number is not positive")
🖥️ Output:
csharp
marks = 92
🖥️ Output:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 9/44
nginx
You passed!
Excellent performance
⚙️ Key Points:
You can nest any number of if statements inside each other.
Proper indentation is important.
Would you like me to give a small practice question next (like checking if a number is positive,
negative, and even/odd together)?
Here’s a clear explanation of Loops in Python — both for loop and while loop — with syntax and
examples 👇
🔁 Loops in Python
Loops are used to repeat a block of code multiple times until a condition is met.
🧩 1. for loop
🔹 Definition:
The for loop is used to iterate over a sequence (like a list, tuple, string, or range of numbers).
🧠 Syntax:
python
🖥️ Output:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 10/44
1
2
3
4
5
🖥️ Output:
nginx
apple
banana
cherry
for ch in "Python":
print(ch)
🖥️ Output:
css
P
y
t
h
o
n
🔁 2. while loop
🔹 Definition:
The while loop keeps running as long as a condition is true.
🧠 Syntax:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 11/44
python
while condition:
# code to execute repeatedly
i = 1
while i <= 5:
print(i)
i += 1
🖥️ Output:
1
2
3
4
5
💡 Example 2: Countdown
python
count = 5
while count > 0:
print(count)
count -= 1
print("Blast off!")
🖥️ Output:
vbnet
5
4
3
2
1
Blast off!
⚙️ Key Differences:
Feature for loop while loop
When you know how many times to When you don’t know the exact number of
Use case
run iterations
Syntax Iterates over a sequence Runs until condition becomes False
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 12/44
Feature for loop while loop
Control
Defined automatically Must be updated manually
variable
Would you like me to add loop control statements next (like break, continue, and pass) with examples?
Here’s a clear explanation of Loop Control Statements in Python — break, continue, and pass — with
syntax and examples 👇
🔁 Loop Control Statements
These statements let you control the flow of loops — i.e., stop, skip, or do nothing inside a loop.
🔹 1. break Statement
🧠 Purpose:
Used to exit (stop) the loop immediately, even if the loop condition is still true.
💡 Syntax:
python
💡 Example:
python
🖥️ Output:
1
2
3
4
🔹 2. continue Statement
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 13/44
🧠 Purpose:
Used to skip the current iteration and move to the next one.
💡 Syntax:
python
💡 Example:
python
🖥️ Output:
1
2
4
5
🔹 3. pass Statement
🧠 Purpose:
Used as a placeholder — it does nothing, but allows code to run without an error.
It’s useful when you’re writing code that you’ll complete later.
💡 Syntax:
python
💡 Example:
python
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 14/44
pass # to be filled later
print(i)
🖥️ Output:
1
2
3
4
5
🧾 Summary Table
Statement Meaning Effect on Loop
break Exit the loop completely Stops the loop
continue Skip current iteration Goes to next iteration
pass Do nothing Placeholder (no effect)
Would you like me to give a practice exercise next (using break, continue, and pass together)?
Here’s a simple and clear explanation of Function Definition and Calling in Python with syntax and
examples 👇
🧩 Functions in Python
🔹 Definition:
A function is a block of reusable code that performs a specific task.
It helps make your program modular, readable, and reusable.
🧠 1. Function Definition
You define a function using the def keyword.
Syntax:
python
def function_name(parameters):
# block of code
return value
🧠 2. Function Calling
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 15/44
Once defined, you can call (use) the function by writing its name followed by parentheses ().
Syntax:
python
function_name(arguments)
def greet():
print("Hello, welcome to Python!")
# Function call
greet()
🖥️ Output:
css
# Function call
add(5, 10)
🖥️ Output:
ini
Sum = 15
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 16/44
product = multiply(4, 6)
print("Product =", product)
🖥️ Output:
ini
Product = 24
def greet(name="Guest"):
print("Hello,", name)
🖥️ Output:
Hello, Tanuj
Hello, Guest
⚙️ Key Points
def keyword is used to define a function.
return keyword sends back a value (optional).
Functions must be called after definition.
Would you like me to explain types of function arguments next (like positional, keyword, default, and
variable-length *args, **kwargs)?
Here’s a clear explanation of Function Arguments in Python — covering positional, keyword, default,
and variable-length (*args, **kwargs) — with syntax and examples 👇
🧠 Function Arguments in Python
When you define a function, you can pass values (arguments) to it.
Python supports different types of arguments to make functions flexible.
🔹 1. Positional Arguments
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 17/44
🧩 Definition:
Values are passed in order — the position of each argument matters.
Syntax:
python
💡 Example:
python
greet("Tanuj", 21)
🖥️ Output:
makefile
Name: Tanuj
Age: 21
🔹 2. Keyword Arguments
🧩 Definition:
You specify which parameter gets which value by using the parameter name during the call.
Syntax:
python
function_name(param1=value1, param2=value2)
💡 Example:
python
greet(age=21, name="Tanuj")
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 18/44
🖥️ Output:
makefile
Name: Tanuj
Age: 21
Syntax:
python
def function_name(param=value):
# code
💡 Example:
python
def greet(name="Guest"):
print("Hello,", name)
🖥️ Output:
Hello, Tanuj
Hello, Guest
🔹 4. Variable-Length Arguments
Sometimes you don’t know how many arguments will be passed.
You can use *args and **kwargs to handle this.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 19/44
Syntax:
python
def function_name(*args):
# args is a tuple
💡 Example:
python
def add_numbers(*args):
total = 0
for num in args:
total += num
print("Sum =", total)
add_numbers(2, 4, 6)
add_numbers(1, 2, 3, 4, 5)
🖥️ Output:
ini
Sum = 12
Sum = 15
Syntax:
python
def function_name(**kwargs):
# kwargs is a dictionary
💡 Example:
python
def show_details(**kwargs):
for key, value in [Link]():
print(f"{key}: {value}")
🖥️ Output:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 20/44
makefile
name: Tanuj
age: 21
course: Python
🧾 Summary Table
Type Symbol Description Example
Positional – Values passed in order add(2, 3)
Would you like me to explain return statement and scope of variables (local vs global) next?
Here’s a clear and simple explanation of Return Values in Python functions with syntax and examples
👇
🔙 Return Values in Python
🔹 Definition:
The return statement is used inside a function to send a result (value) back to the place where the
function was called.
If no return is used, the function returns None by default.
🧠 Syntax:
python
def function_name(parameters):
# some code
return value
result = add(5, 7)
print("Sum =", result)
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 21/44
🖥️ Output:
ini
Sum = 12
python
x, y = calculate(10, 4)
print("Sum =", x)
print("Difference =", y)
🖥️ Output:
ini
Sum = 14
Difference = 6
def greet(name):
print("Hello,", name)
result = greet("Tanuj")
print(result)
🖥️ Output:
css
Hello, Tanuj
None
def check_number(num):
if num % 2 == 0:
return "Even"
else:
return "Odd"
print(check_number(7))
print(check_number(10))
🖥️ Output:
nginx
Odd
Even
⚙️ Key Points
return ends the function immediately.
You can return any data type — number, string, list, tuple, etc.
If no return statement is given, the function returns None.
Would you like me to explain local and global variables (scope) next?
Here’s a clear and easy explanation of Scope of Variables in Python — covering Local and Global scope
with syntax and examples 👇
🌍 Scope of Variables in Python
The scope of a variable determines where in the program the variable can be accessed or modified.
Python has two main types of variable scopes:
Local Variables
Global Variables
🔹 1. Local Variables
🧠 Definition:
A local variable is defined inside a function and can only be used within that function.
Syntax:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 23/44
python
def function_name():
local_var = value # local scope
# use local_var here only
💡 Example:
python
def my_function():
message = "Hello from inside the function!" # local variable
print(message)
my_function()
❌
# Trying to access message outside will cause an error
# print(message)
🖥️ Output:
javascript
📝 You cannot access message outside the function because it’s local to my_function().
🔹 2. Global Variables
🧠 Definition:
A global variable is defined outside any function and can be used anywhere in the program.
Syntax:
python
def function_name():
print(global_var)
💡 Example:
python
def show_name():
print("Inside function:", name)
show_name()
print("Outside function:", name)
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 24/44
🖥️ Output:
bash
📝 The global variable name is accessible inside and outside the function.
💡 Example:
python
def increase():
global count # declare that we are using the global 'count'
count += 1
print("Inside function:", count)
increase()
print("Outside function:", count)
🖥️ Output:
bash
Inside function: 1
Outside function: 1
📝 Without the global keyword, Python would create a new local variable named count.
x = 10 # global variable
def test():
x = 5 # local variable (different from global x)
print("Inside function:", x)
test()
print("Outside function:", x)
🖥️ Output:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 25/44
bash
Inside function: 5
Outside function: 10
📝 The local x inside the function does not affect the global x.
🧾 Summary Table
Type Declared Accessible Keyword Needed?
Local Variable Inside a function Only inside that function ❌ No
Global Outside all Everywhere in the ✅ Use global to modify inside a
Variable functions program function
Would you like me to continue with the next topic — Lambda (anonymous) functions?
Perfect 👍
— Let’s cover both Lambda (anonymous) functions and Recursion clearly with syntax,
explanation, and examples 👇
⚡ Lambda (Anonymous) Functions
🧠 Definition:
A lambda function is a small, anonymous (unnamed) function in Python.
It is used for short, one-line functions where defining a full function using def would be unnecessary.
🧩 Syntax:
python
add = lambda a, b: a + b
print(add(5, 3))
🖥️ Output:
8
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 26/44
💡 Example 2: Square of a Number
python
square = lambda x: x ** 2
print(square(6))
🖥️ Output:
36
python
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x ** 2, numbers))
print(squares)
🖥️ Output:
csharp
python
🖥️ Output:
csharp
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 27/44
🔁 Recursion
🧠 Definition:
Recursion is when a function calls itself to solve a smaller instance of the same problem.
Every recursive function must have:
🧩 Syntax:
python
def function_name(parameters):
if base_condition:
return value
else:
return function_name(modified_parameters)
def factorial(n):
if n == 0 or n == 1: # base case
return 1
else:
return n * factorial(n - 1) # recursive call
print(factorial(5))
🖥️ Output:
120
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2)
for i in range(6):
print(fibonacci(i), end=" ")
🖥️ Output:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 28/44
0 1 1 2 3 5
⚠️ Note:
Recursive functions can cause a RecursionError if they call themselves too many times (no base case).
Perfect 👍 Here’s a clear explanation of all four important Python data structures — List, Tuple, Set,
and Dictionary — with syntax, properties, and examples 👇
🧱 1. List → Mutable, Ordered
🧠 Definition:
A list is an ordered, mutable (changeable) collection of elements.
You can store different data types in a list.
🧩 Syntax:
python
💡 Example:
python
# Modify
fruits[1] = "mango"
print(fruits) # Output: ['apple', 'mango', 'cherry']
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 29/44
[Link]("apple")
print(fruits) # Output: ['mango', 'cherry', 'orange']
✅ Key Features:
Ordered (maintains insertion order)
Mutable (can change values)
Allows duplicates
🧩 Syntax:
python
💡 Example:
python
# colors[0] = "yellow" ❌
# Trying to change will cause an error
TypeError
✅ Key Features:
Ordered
Immutable (cannot be modified)
Allows duplicates
Faster than lists (for read-only data)
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 30/44
🧩 Syntax:
python
💡 Example:
python
numbers = {1, 2, 3, 3, 4}
print(numbers) # Output: {1, 2, 3, 4} (no duplicates)
[Link](5)
[Link](2)
print(numbers) # Output: {1, 3, 4, 5}
# Set operations
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print([Link](set2)) # {1, 2, 3, 4, 5}
print([Link](set2)) # {3}
✅ Key Features:
Unordered (no indexing)
Mutable (can add/remove elements)
🧩 Syntax:
python
💡 Example:
python
student = {
"name": "Tanuj",
"age": 21,
"course": "Python"
}
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 31/44
print(student["name"]) # Output: Tanuj
# Modify
student["age"] = 22
# Remove a key
del student["course"]
print(student)
🖥️ Output:
bash
✅ Key Features:
Key-value storage
Keys must be unique and immutable (e.g., string, int)
Values can be any type
Mutable and unordered (insertion order preserved in Python 3.7+)
Would you like me to continue with String operations (indexing, slicing, methods) next?
Excellent 👏You’re covering all core Python data manipulation concepts — these are very common in
interviews.
Let’s go through them step-by-step with syntax, examples, and key notes 👇
🔹 1. Indexing and Slicing
These are used to access parts of sequences — like lists, strings, or tuples.
🧩 Indexing:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 32/44
Access a single element using its index number.
(Index starts from 0)
python
🧩 Slicing:
Extract a range of elements using [start:end:step].
python
🧠 Remember:
start = inclusive
end = exclusive
Negative index counts from the end
# Add elements
[Link]("cherry") # Adds to end
[Link](1, "mango") # Insert at position 1
[Link](["orange", "kiwi"]) # Add multiple items
print(fruits)
🖥️ Output:
['apple', 'mango', 'banana', 'cherry', 'orange', 'kiwi']
💡 Removing elements
python
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 33/44
🧠 Note:
remove() throws an error if element not found
pop() returns the removed element
nums = [5, 3, 8, 1]
[Link]() # Ascending
print(nums) # [1, 3, 5, 8]
[Link](reverse=True) # Descending
print(nums) # [8, 5, 3, 1]
python
sorted_list = sorted(nums)
💡 Searching
python
🧠 Note:
in keyword → checks existence
.index() → returns position of the first match
🔹 4. Iteration
💡 Using for loop:
python
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 34/44
python
🖥️ Output:
0 apple
1 banana
2 cherry
🔹 5. Comprehensions
Comprehensions provide a compact way to create lists, sets, or dictionaries.
✅ List Comprehension
Syntax:
python
Example 1:
python
python
✅ Dictionary Comprehension
Syntax:
python
Example:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 35/44
python
nums = [1, 2, 3, 4]
squares = {x: x**2 for x in nums}
print(squares)
🖥️ Output:
yaml
{1: 1, 2: 4, 3: 9, 4: 16}
python
🖥️ Output:
yaml
🧾 Summary Table
Operation Description Example
Indexing Access element by position list[2]
Slicing Extract range list[1:4]
Add append(), insert(), extend()
Would you like me to continue next with String Operations (indexing, slicing, methods like upper(),
replace(), etc.)?
Perfect 👍 Let’s now go over Strings — one of the most important Python concepts frequently asked in
interviews.
Here’s a clean explanation with syntax, examples, and notes 👇
💠 1. String Creation and Indexing
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 36/44
🧠 Definition:
A string is a sequence of characters enclosed in single (‘ ’), double (“ ”), or triple (“”“ ””“) quotes.
🧩 Syntax:
python
str1 = 'Hello'
str2 = "Python"
str3 = """This is
a multiline string."""
💡 Indexing Example:
python
word = "Python"
print(word[0]) # 'P' (first character)
print(word[-1]) # 'n' (last character)
🧠 Remember:
Indexing starts from 0
💠 2. String Methods
Python provides many built-in methods to manipulate strings.
Here are the most used ones:
🔹 upper()
Converts all characters to uppercase.
python
text = "hello"
print([Link]()) # Output: HELLO
🔹 lower()
Converts all characters to lowercase.
python
text = "HELLO"
print([Link]()) # Output: hello
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 37/44
🔹 split()
Splits the string into a list of words (default delimiter = space).
python
text2 = "apple,banana,orange"
print([Link](',')) # Output: ['apple', 'banana', 'orange']
🔹 replace()
Replaces part of the string with another string.
python
🔹 find()
Returns the index of the first occurrence of a substring.
python
💠 3. String Formatting
Formatting allows you to insert variables into strings neatly.
name = "Tanuj"
age = 21
print(f"My name is {name} and I am {age} years old.")
🖥️ Output:
pgsql
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 38/44
🔹 (b) .format() Method
python
name = "Tanuj"
age = 21
print("My name is {} and I am {} years old.".format(name, age))
🖥️ Output:
pgsql
python
python
name = "Tanuj"
age = 21
print("My name is %s and I am %d years old." % (name, age))
🖥️ Output:
pgsql
✅ → string
✅
%s
%d → integer
✅ %f → float
python
text = "PythonProgramming"
print(text[0:6]) # 'Python'
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 39/44
print(text[6:]) # 'Programming'
print(text[::-1]) # 'gnimmargorPnohtyP' (reverse)
🔹 Concatenation
Combine multiple strings using + or join().
python
str1 = "Hello"
str2 = "World"
print(str1 + " " + str2) # Output: Hello World
🧾 Summary Table
Operation Description Example Output
Indexing Access char by index "Python"[1] 'y'
Slicing Substring extraction "Python"[0:3] 'Pyt'
upper() Uppercase "abc".upper() 'ABC'
Would you like me to continue next with File Handling (open, read, write, close) or Exception
Handling (try-except, finally, raise)?
Excellent 👍
— File Handling is another must-know Python interview topic, especially for practical
coding rounds.
Here’s a complete and clear explanation with syntax, examples, and outputs 👇
📂 File Handling in Python
File handling allows you to read from and write to files stored on your computer.
Python provides built-in functions like open(), read(), write(), and close() to handle files safely.
💡 Example:
python
✅ Always close the file after operations to save memory and avoid data loss.
🔹 2. Reading and Writing Files
There are several ways to read file content:
python
🖥️ Output:
arduino
python
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 41/44
python
🖥️ Output:
css
python
python
🔹 3. File Modes
Mode Description Creates New File? Overwrites?
'r' Read (default mode) ❌ No ❌ No
'w' Write ✅ Yes ✅ Yes
'a' Append ✅ Yes ❌ No (adds at end)
'r+' Read and Write ❌ No ❌ No (edits existing file)
💡 Examples of File Modes
Write Mode (w)
python
f = open("[Link]", "w")
[Link]("This is write mode.")
[Link]()
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 42/44
Append Mode (a)
python
f = open("[Link]", "a")
[Link]("\nThis line is appended.")
[Link]()
python
f = open("[Link]", "r")
print([Link]())
[Link]()
python
f = open("[Link]", "r+")
print([Link]()) # Read content
[Link]("\nExtra line!") # Add new content
[Link]()
💡 Example:
python
🧾 Summary Table
Operation Function Example
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 43/44
Operation Function Example
Read line readline() Reads one line
Read all lines readlines() Returns list of lines
Write write("text") Writes to file
✅ Best Practice:
Always use with open() for file operations — it’s cleaner, safer, and preferred in interviews.
Would you like me to continue next with Exception Handling (try, except, else, finally, raise)?
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 44/44