0% found this document useful (0 votes)
10 views33 pages

Python 1

The document provides an overview of Python programming, highlighting its key features such as simplicity, readability, and extensive libraries. It covers fundamental concepts including data types, variables, control structures like loops, and data structures such as lists, tuples, sets, and dictionaries. Additionally, it introduces functions and object-oriented programming principles like classes and inheritance, making it a comprehensive guide for beginners and professionals alike.

Uploaded by

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

Python 1

The document provides an overview of Python programming, highlighting its key features such as simplicity, readability, and extensive libraries. It covers fundamental concepts including data types, variables, control structures like loops, and data structures such as lists, tuples, sets, and dictionaries. Additionally, it introduces functions and object-oriented programming principles like classes and inheritance, making it a comprehensive guide for beginners and professionals alike.

Uploaded by

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

PYTHON PROGRAMMING

"Python is a high-level and easy-to-understand programming language. It's used in


many areas like making websites, data analysis, machine learning, and software
development. Its simple syntax makes it great for beginners and also powerful for
professionals."

● Mutable means can be changed


● Immutable means cannot be changed

Key Features of Python

● Simple and readable: Easy to understand and write.

● Interpreted: Executes code line by line.

● Open-source: Free to download and use.

● Dynamically typed: No need to declare variable types.

● Extensive libraries: Offers many built-in modules and third-party packages.


(extra tools made by other developers that can be installed to add more
features, like Pandas or NumPy).

SIMPLE EXAMPLE

Input
Print(“Sara”)
Output
Sara

VARIABLE

In Python, a variable is a name that stores a value, like a number or text.

SIMPLE EXAMPLE

Input
A = 10
B=5
Print(A+B)
Output
15

DATA TYPES IN PYTHON


Numeric type

● Integer (int): Represents integers (e.g., -2, 0, 100).


● Float :Represents floating-point in numbers (e.g., 3.14, -0.5).
● Complex: Represents complex numbers (e.g., 2 + 3j)

EXAMPLE
Input
a=12
Print (type (a))
Output
<Class ‘int’>

Sequence Types:

● str: Represents strings, sequences of characters (e.g., "hello", 'world').


● list: Represents ordered, mutable sequences of items (e.g., [1, 2, 3],
['a', 'b', 'c']).
● tuple: Represents ordered, immutable sequences of items (e.g., (1, 2,
3), ('a', 'b', 'c')).
● range: Represents a sequence of numbers, often used for looping (e.g.,
range(5) generates numbers from 0 to 4).

EXAMPLE
Input
b = ‘Hello’
Print(type (b))
Output
<Class ‘str’>

Casting - converting one data type into another data type.

● Casting is mainly used in:

● Data Science

● Web/Backend Development
● Database Work

● Automation/Testing

● AI/ML

Data Science / Data Analysis

Department: Data Science / Business Intelligence

Example: CSV file-la all data string format-la irukkum. But we need to
convert salary or age to int or float to do analysis or graph.

Casting: int(row["Age"]) or float(row["Salary"])

Simple Example

a =int( ‘10’)
b =int(‘20’)
c = a+b
Print(c)
Output
30

List
A list in Python is a versatile and mutable data structure used to store an
ordered sequence of items. These items can be of different data types,
including numbers, strings, and even other lists (nested lists). Lists are
defined by enclosing comma-separated values within square brackets [].

Example
Input
X = [14,24,28]
X[2]=30
Print(X)
Output
[14,24,30]

How to Create a List?


# A list of fruits
fruits = ["apple", "banana", "orange"]
print(fruits)

Output:

['apple', 'banana', 'orange']

Accessing Items in a List

Each item has a position (called index), starting from 0.

print(fruits[0]) # Output: apple


print(fruits[1]) # Output: banana

Changing an Item

fruits[1] = "mango"
print(fruits)
Output
['apple', 'mango', 'orange']

Adding Items

fruits.append("grapes")
print(fruits)
Output
['apple', 'mango', 'orange', 'grapes']

Removing Items

fruits.remove("orange")
print(fruits)
Output
['apple', 'mango', 'grapes']

Python List Practice Worksheet

1. Create a List

Create a list named colors with these items: "red", "blue", "green”
2. Access an Item

Print the second color from your colors list.

3.Change a Value

Change "blue" to "yellow" in your list.

4. Add an Item

Add "purple" to the end of the list using .append().

5.Remove an Item

Remove "green" from the list.

Solution:

Color_list = ["red", "blue", "green"]


print(Color_list[2])

Color_list[2] ="yellow"
print(Color_list)

Color_list.append("purple")
print(Color_list)

For loop:

What is a for loop in Python?

A for loop in Python is used to repeat a block of code for each item in a sequence
like a list, string, tuple, dictionary, or range.

Syntax:

for variable in sequence:


# code to run for each item
When should you use range() in a for loop?

Use range() when you want to repeat something a specific number of times or when
you need to loop through a sequence of numbers.

Common uses of range()

1. Repeat an action a fixed number of times

for i in range(5):
print("Welcome!")

Prints “Welcome!” 5 times.

Loop through numbers with steps

for i in range(0, 10, 2): # Start at 0, stop before 10, step by 2


print(i)

Real-life job examples using range()

● Send emails to 50 users

● Data entry checks: Loop through rows 1 to 100 and validate entries.

● Web scraping: Loop through multiple pages of a site:

Multiple table using for loop: ❌2

for i in range (1,11):


print(i,'x2',i*2)

What is a Nested For Loop?

A nested for loop means one for loop inside another for loop. It is used when we
want to repeat a task inside another repeating task.

Real-Life Example: Printing Rows and Columns (like tables)

Imagine you're building a seating chart with rows and columns:


for row in range(1, 4): # 3 rows
for col in range(1, 5): # 4 columns
print(f"Seat {row}-{col}")

Output
Seat 1-1
Seat 1-2
Seat 1-3
Seat 1-4
Seat 2-1
Seat 2-2
Seat 2-3
Seat 2-4
Seat 3-1
Seat 3-2
Seat 3-3
Seat 3-4

[Program finished]

What is a While Loop?

A while loop is used when you want to repeat a task many times as long as a
condition is true.

It checks the condition before doing the task.

(Syntax):

while condition:
# do something

Simple Example 1: Count from 1 to 5

i=1
while i <= 5:
print(i)
i=i+1

Output:

1
2
3
4
5

Real-Life Example 1: Drinking Water

Problem: You drink water until your bottle is empty.

water_in_bottle = 5
while water_in_bottle > 0:
print("Take a sip")
water_in_bottle = water_in_bottle - 1

print("The bottle is empty")

Output:

Take a sip
Take a sip
Take a sip
Take a sip
Take a sip
The bottle is empty

Key Points to Remember:

● The loop runs only while the condition is true

● You must change the value inside the loop (or it will run forever!)

● It’s good for tasks where you don’t know how many times the loop should run

List:

● Any type of data can be stored


● Allows duplicate
● We can modify the list item. We can add or remove elements using this
keyword insert(), append(), extend (),pop().

example:
A= [3,4,8,sara]
B=[“ hello I hate everyone”, “i also love everything”]
A.insert(0,1)
A.append(6)
A pop()
A extend(B)
Print (a)

Tuple:

What is a Tuple in Python?

A tuple is a collection of ordered, unchangeable (immutable) items. Tuples can store


multiple items in a single variable.

Syntax:

my_tuple = (10, 20, 30)

● Allows duplicate
● Any type of data can be stored
● We cannot modify the tuple item. We cannot add or remove
● It use the () parentheses while list use [] square brackets.
● Ex. a=(1,2,3,4)
● If we want to do add or remove elements from the tuple we can convert that
tuple into list and we can modify elements easily.

Example
a=(1,2,3,4,5)
b=list(a)
print(a)
print (b)

Key Features of Tuples

Ordered: Elements have a defined order.

Immutable: You cannot change, add, or remove items after the tuple is created.
Allow duplicates: Tuples can contain duplicate values.

Can store different data types: Numbers, strings, lists, etc.

1. Creating a tuple:

fruits = ("apple", "banana", "cherry")


print(fruits)

2. Accessing items:

print(fruits[1]) # Output: banana

3. Tuple with mixed data types:

info = ("John", 25, 5.9)

4. Looping through a tuple:

for fruit in fruits:


print(fruit)

5. Tuple unpacking:

name, age, height = info


print(name) # Output: John

Set {}:

● Do not allow duplicate , duplicate values will be removed.


● Any type of data can be stored
● We cannot modify the Set item but we can add or remove items.
● Sets are unordered
● add(), update (), remove (),pop()

What is set in Python?

A set is a collection of unique items (no duplicates).

It is unordered (items have no fixed position).

Written using curly braces {} or set() function.


Basic Set Example:

my_set = {1, 2, 3, 4, 4, 5}
print(my_set)

Output:

{1, 2, 3, 4, 5} # Duplicate 4 is removed

Common Set Operations:

a = {1, 2, 3}
b = {3, 4, 5}

Union: (all unique elements from both sets)

print(a | b) # Output: {1, 2, 3, 4, 5}

Intersection: (common elements)

print(a & b) # Output: {3}

Difference: (elements only in one set)

print(a - b) # Output: {1, 2}

Symmetric Difference: (not common in both)

print(a ^ b) # Output: {1, 2, 4, 5}

Examples

1.add() – To add a single item

fruits = {"apple", "banana"}


fruits.add("orange")
print(fruits)

Output:

{'apple', 'banana', 'orange'}


---

2. update() – To add multiple items (like a list or another set)

fruits = {"apple", "banana"}


fruits.update(["grape", "mango"])
print(fruits)

Output:

{'apple', 'banana', 'grape', 'mango'}

---

3. remove() – To remove an item (error if item not found)

fruits = {"apple", "banana", "mango"}


fruits.remove("banana")
print(fruits)

Output:

{'apple', 'mango'}

Note: If you try fruits.remove("orange"), it will give an error if "orange" is not in the
set.

---

4. pop() – Removes a random item

fruits = {"apple", "banana", "mango"}


removed_item = fruits.pop()
print("Removed:", removed_item)
print("Remaining:", fruits)

Output (random):

Removed: apple
Remaining: {'banana', 'mango'}

Note: pop() removes any item because sets are unordered.


Dictionary{}

● Don't allow duplicate , duplicate value will overwrite existing value


● Any type of data can be stored
● Key: value pair {“name”:”EMC”}
● get(),keys(),values(), items (), update ().

Example

a={"Name":"sara", "Age":18 , "Location": "Habibullah road"}


print(a)
print(a.keys())
print(a.values())

1. Dictionary na enna?

● Python-la dictionary is like a real dictionary (like English-Tamil dictionary).


● It stores data in key-value pairs.

Structure:

my_dict = {
"name": "Anbu",
"age": 25,
"city": "Madurai"
}

name, age, city → keys

"Anbu", 25, "Madurai" → values

Example

employee = {
"emp_id": 1001,
"name": "Karthik",
"role": "Data Analyst",
"salary": 50000
}

# Add new data


employee.update({"experience": 3})
# Update salary
employee.update({"salary": 55000})

# Delete a key
del employee["role"]

# Loop through dictionary


for key, value in employee.items():
print(key, ":", value)

You can also update multiple keys in one line:

employee.update({
"salary": 60000,
"city": "Chennai"
})

This will:

Update salary to 60000

Add new key city with value "Chennai”

Python functions

What is a Function in Python?

A function is a block of code that does a specific task.


You create (define) it once and use (call) it whenever needed.

Why Use Functions?

To avoid repeating code

To organize your program into smaller parts

To reuse the same logic with different data

How to Create a Function

def greet():
print("Hello! Have a nice day!")
def = keyword to define a function

greet() = name of the function

print(...) = task it does

Calling the function:

greet()

Output:
Hello! Have a nice day!

Simple example.

def add():
a= int(input(“enter a:”))
b= int(input(“enter b:”))
print(a+b)
add()

Output
enter a:10
enter b:20
30

[Program finished]

Return statement in python

Definition:

● The return statement in Python is used inside a function to send back the
result to the place where the function was called.
● It also stops the function from running any more lines after the return(After
return statement anything within the function will not work)

Example:

def add(a, b):


return a + b

result = add(2, 3)
print(result) # Output: 5

Here, the function add() returns the sum of a and b, and that result is stored in the
variable result.

Example

def add(a,b):
return a+b

a=int(input("enter a number:"))
b=int(input("enter a number:"))
c=int(input("enter a number:"))

sum=add(a,b)
total= sum*c
print(total)

What is OOPs?

● OOPs stands for Object-Oriented Programming.

● It is a way of writing programs using objects.

● Objects are like real-life things – they have properties (data) and actions
(methods/functions).

“Object-Oriented Programming (OOP) is a method of programming where we design


software using objects. These objects hold data and perform actions. OOP makes
the code more organized, reusable, and easier to manage, especially in large
applications.”

It is based on four main principles:

Encapsulation – keeping data safe inside objects,

Inheritance – reusing code from one class to another,

Polymorphism – using one method in different ways,

Abstraction – hiding complex details and showing only what’s needed.”

Classes and objects


What are Classes and Objects?

Class:

A class is like a blueprint or plan.

It tells what properties (variables) and actions (functions) something will have.

Object:

An object is the real thing made using the class.

You can make many objects using one class.

Definition:

In Python, a class is a blueprint for creating objects.


An object is a real instance based on that class.

Why are Classes and Objects Useful?

● They help organize and structure code.

● Make the code reusable and scalable.

● Widely used in real-world applications like websites, apps, games, and data
processing.

Example

class Student:

def __init__(self, name, age):


self.name = name
self.age = age

def display_info(self):
print("Name: ",self.name)
print("Age:",self.age)

student1 = Student("Alice", 21)


student2 = Student("Bob", 22)

student1.display_info()
student2.display_info()

Inheritance – Simple Explanation

“Inheritance means one class can use the variables and functions of another class.
The class that gives its features is called the parent class, and the class that
receives them is called the child class.”

Example:

Single inheritance

# Parent class
class Animal:
def __init__(self):
self.name = "Animal"

def eat(self):
print(self.name + " is eating.")

# Child class
class Dog(Animal):
def bark(self):
print("Dog is barking.")

# Creating object of Dog


my_dog = Dog()

# Using function from parent class


my_dog.eat() # Output: Animal is eating.

# Using function from child class


my_dog.bark() # Output: Dog is barking.

Multiple inheritance means one class object can access other class, In this pulla
class can able to access the other two amma appa class with the object deena

class appa():
def phone(self):
print("appa oda phone")
class amma():
def sweet(self):
print("amma oda sweet")
class pulla(appa,amma):
def laptop(self):
print("paiyan oda laptop")

deena=pulla()
deena.laptop()
deena.phone()
deena.sweet()

Output

paiyan oda laptop


appa oda phone
amma oda sweet

[Program finished]

Multi level inheritance

Multilevel inheritance means a class is inheriting from a class that already inherited
from another class. It creates a chain of inheritance.

Example

class ayya():
def chcolate(self):
print("ayya's chcolate")
class amma(ayya):
def curdrice(self):
print("amma's curd rice")
class ponu(amma):
def pizza(self):
print("ponu oda pizza")

sara=ponu()
sara.pizza()
sara.curdrice()

mom=amma()
mom.chcolate()
sara.chcolate()
Output

ponu oda pizza


amma's curd rice
ayya's chcolate
ayya's chcolate

[Program finished]

Hierarchical Inheritance in Python — Simple Explanation

Definition: Hierarchical inheritance means one parent class has many child classes.

Oru common base class irukkum. Athula irundhu multiple classes inherit pannum.

Hybrid inheritance

Hybrid Inheritance in Python – Explained Simply

Hybrid Inheritance na multiple types of inheritance (like single, multilevel, and


multiple inheritance) mix aagirukkum in one program. It is called "hybrid" because it
combines more than one type.

Hybrid inheritance means using more than one type of inheritance (like single,
multiple, or multilevel) together in the same program.

It is called "hybrid" because it mixes different inheritance styles.

Example:

When one class inherits from two classes, and those two classes inherit from a
common base class, it forms a hybrid pattern.

Polymorphism na enna?

Polymorphism na oru same name vaachu multiple types of work panna mudiyum.
Poly = many, Morph = forms
So, same function or method name, but it acts differently based on the object or
class.
Polymorphism in Python means the ability of different classes to respond to the
same method name in their own way. It allows the same function or method to work
with different types of objects.

Example-style definition:

> Polymorphism allows us to write one function (like make_payment()) that can
work with different objects (like CardPayment, WalletPayment, etc.), as long as they
all have a method with the same name (like pay()).

Example

class vehicle():
def start(self):
print("vehicle started")

class car(vehicle):
def start(self):
print("car started")

c1=car()
c1.start()

car started

[Program finished]

Python Example:

class Dog:
def sound(self):
return "Bark"

class Cat:
def sound(self):
return "Meow"

# Function that accepts any animal


def make_sound(animal):
print(animal.sound())

# Create objects
dog = Dog()
cat = Cat()
# Call function
make_sound(dog) # Output: Bark
make_sound(cat) # Output: Meow

Explanation:

Dog and Cat la rendu class iruku.

Rendu class la sound() nu same method name iruku, aana different output.

make_sound() function-ku yaar object anupinalum correct-a work agum.

Encapsulation na enna?

Encapsulation na data um methods (functions) ah oru class kullaye vechurathu. Ithu


external users kitta irunthu data ah protect panrathukku use aagum.

Simple-a solla:

● Encapsulation na data hide panna oru technique.

● Only necessary details mattum show pannuvom, rest ah hide panrom.

● Ithu private, protected, public keywords use pannitu nadakum.

Definition of Encapsulation (Easy + Professional):

Encapsulation is the process of hiding the internal data of a class and only allowing
access to it through methods (functions).

This helps to:

1. Protect the data


2. Control how the data is changed or viewed
3. Keep the code safe and organized

One-line definition (very simple):

> Encapsulation means wrapping data and functions together in a class and hiding
the data from direct access.
1. Public:

● Public variables or methods na yaar vena access panna mudiyum.

● No restriction.

Example:

class Sample:
def __init__(self):
self.name = "Arun" # public

obj = Sample()
print(obj.name) # Direct-a access pannalam

2. Private:

● Private variables na class veliya access panna mudiyadhu.

● __ (double underscore) use panrom.

Example:

class Sample:
def __init__(self):
self.__age = 20 # private

def show_age(self):
print(self.__age)

obj = Sample()
obj.show_age() # OK – method use pannalam
print(obj.__age) # Error – private ah direct-a access panna mudiyadhu

3. Protected:

● Protected na classum athoda child class (subclass) kulla use panna mudiyum.

● But public-a direct-a access panna vendam nu oru warning mathiri.

● _ (single underscore) use panrom.


Example:

class Sample:
def __init__(self):
self._city = "Chennai" # protected

class SubSample(Sample):
def print_city(self):
print(self._city) # OK – subclass kulla access panna mudiyum

obj = SubSample()
obj.print_city()
print(obj._city) # This works, but not recommended (protected)

Exception handling

What is Exception Handling?

Python-la program run panna, edhavadhu mistake irundha (like divide by zero, file
not found, etc.), appo program stop agidum. Ithu error or exception nu solvom.

Exception Handling na, error varum pothu program stop aagala, instead namma
handle panna mudiyum using:

● try

● except

● else (optional)

● finally (optional)

Example
try:
a = input()
b = input()
print(a / b)
except Exception as e:
print("wrong", e)

When to use except Exception as e?

You use except Exception as e: when you don’t know what kind of error might
happen, or if you want to catch all errors in one place.
Use Exception as e when:

1. You want to catch any kind of error.

2. You’re writing a general try-except block.

3. You want to show the actual error message using e.

Simple Example 1: ZeroDivisionError

try:
a=5
b=0
print(a / b)
except ZeroDivisionError:
print("You can't divide by zero.")

Output:
You can't divide by zero.

Use specific errors (like ValueError, ZeroDivisionError) when:

1. You know the exact error that might happen.

2. You want to give different messages for different errors.

3. It helps in debugging and better control.

Example 2: Handling Multiple Errors

try:
a = int(input("Enter a number: "))
b = int(input("Enter another number: "))
print(a / b)
except ZeroDivisionError:
print("Can't divide by zero.")
except ValueError:
print("Please enter only numbers.")

Example 3: else and finally usage

try:
x = 10
y=2
result = x / y
except ZeroDivisionError:
print("Division error.")
else:
print("Division is:", result)
finally:
print("This block runs always.")

Output:

Division is: 5.0


This block runs always.

Common Exceptions:

Error Type When it happens

● ZeroDivisionError-Number divide by zero


● ValueError-Wrong type input (e.g. text instead of int)
● IndexError-List index out of range
● FileNotFoundError-File open panna file illa

1. What is File Handling?

File Handling means reading from and writing to files in your computer using
Python.

● We can do these:

● Create a file

● Write data into the file

● Read data from the file

● Add more data without deleting old data

● Delete or close the file

2. Important File Modes:


Mode Meaning Example

‘r’ Read Mode open("file.txt",


"r")

‘w’ Write
Mode(erase open("file.txt","w")
old data)

‘a’ Append open("file.txt","a")


Mode(adds
data)

‘x’ Create a open("file.txt","x")


new
file(error if
exists)

‘r+’ Read and


write both open("file.txt","r+"
)

3. Writing to a File (first time create or overwrite)

# Create a file and write into it


f = open("myfile.txt", "w")
f.write("Hello! This is my first file.")
f.close()

Output: (Creates myfile.txt and puts the text inside it)

4. Reading from a File

f = open("myfile.txt", "r")
data = f.read()
print(data)
f.close()

Output:

Hello! This is my first file.

5. Appending Data to an Existing File


f = open("myfile.txt", "a")
f.write("\nI am adding this line.")
f.close()

Then read it again:

f = open("myfile.txt", "r")
print(f.read())
f.close()

Output:

Hello! This is my first file.


I am adding this line.

6. Using with Statement (Better way)

with automatically closes the file — safe method.

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


content = f.read()
print(content)

You don’t need to write f.close() — Python does it.

7. Read Line by Line

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


for line in f:
print(line)

Concept: Using a loop to read file lines

Code:

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


for line in f:
print(line.strip())

Explanation:
with open(...) as f: is used to open a file safely (auto-closes the file).

for line in f: reads one line at a time from the file.

line.strip() removes any unwanted newlines or spaces.

Example

(A) .readline() — Reads ONE line at a time

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


line1 = f.readline()
line2 = f.readline()
print("Line 1:", line1.strip())
print("Line 2:", line2.strip())

Output (if file has):

Apple
Banana
Orange

You will get:

Line 1: Apple
Line 2: Banana

(B) .readlines() — Reads ALL lines as a list

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


lines = f.readlines()
print(lines)

Output:

['Apple\n', 'Banana\n', 'Orange']

You can use a loop to print each line:

for line in lines:


print(line.strip())
Code 1: Using writelines()

lines = ["Apple\n", "Banana\n", "Orange\n"]

with open("fruits.txt", "w") as f:


f.writelines(lines)

Code 2: Using write() inside a loop

lines = ["Apple\n", "Banana\n", "Orange\n"]

with open("fruits.txt", "w") as f:


for item in lines:
f.write(item)

Output
Apple
Banana
Orange

Point f.writelines(lines) for + f.write(lines)

Simpler Yes Slightly longer


syntax

Control over No(writes all at Yes( can add conditions in loop)


each line once)

Speed(small Almost same Almost same


files)

Speed(long Slightly faster Slightly slower


files)

seek() and .tell() — File Cursor Control

When we open a file, Python keeps a cursor (like a pointer) to track where to read or
write next. We can move or check this using:
tell() — Shows current position of the index

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


print(f.tell()) # Output: 0 (cursor is at beginning)
content = f.read()
print(f.tell()) # Output: total number of characters in the file

seek(position) — Moves the cursor to a specific position

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


f.seek(0) # Move to the beginning
print(f.read(5)) # Reads first 5 characters

File Modes in Python (with Examples)

When working with files in Python, you must open them in a specific mode to tell
Python what action you want to perform.

🔹 1. "r" — Read Mode

Opens the file to read only.

❗ File must exist, or it gives an error.

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


content = file.read()
print(content)

2. "w" — Write Mode

Opens the file to write new content.

❗ If the file exists, it will erase all old data.

If the file doesn't exist, it creates a new one.

with open("data.txt", "w") as file:


file.write("Hello, world!")
3. "a" — Append Mode

Opens the file to add new content at the end.

✅ Old content is not removed.

If the file doesn't exist, it creates a new one.

with open("data.txt", "a") as file:


file.write("\nNew line added.")

4. "r+" — Read and Write Mode

Allows you to read and update a file.

❗ File must exist.

It does not erase the content automatically.

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


content = file.read()
file.seek(0)
file.write("Updated!\n")

5. "w+" — Write and Read Mode

Clears old data, writes new data, and allows reading.

File is created if it doesn't exist.

with open("data.txt", "w+") as file:


file.write("New file content.")
file.seek(0)
print(file.read())

6. "a+" — Append and Read Mode

Adds new content at the end and also allows reading.

File is created if it doesn't exist.


with open("data.txt", "a+") as file:
file.write("\nAppended line.")
file.seek(0)
print(file.read())

You might also like