Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

python

Python is a high-level programming language known for its simplicity and versatility in various domains like web development and data science. The document covers essential concepts such as data types, functions, conditionals, loops, and string manipulation, providing examples and explanations for each topic. Additionally, it introduces key functions and programming practices, including the use of lambda functions and recursion.

Uploaded by

kielderjohn524
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

python

Python is a high-level programming language known for its simplicity and versatility in various domains like web development and data science. The document covers essential concepts such as data types, functions, conditionals, loops, and string manipulation, providing examples and explanations for each topic. Additionally, it introduces key functions and programming practices, including the use of lambda functions and recursion.

Uploaded by

kielderjohn524
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 21

1.

Python:

Python is a high-level programming language created by Guido van Rossum in 1991 at


CWI, Netherlands. It is known for its simplicity and is widely used in web
development, data science, automation, and AI. The name comes from Monty Python's
Flying Circus, a comedy show.

2. Important things to learn python


IDE: Integrated Development Environment
PVM: Python Virtual Machine

Fundamental data types

1.Int
2.float
3.boolean
4.string
5.Complex

Collection data types= list, tuple, dictionary, set, forzenset, byte, bytearray,
none, range etc.

OOps concenpt:

Class & object, inheritance, Polymorphism , Datahiding,


Encapsulation(datahiding+Abstraction), multi-threading,
exception handling=>error handling

tips💡(function will be studied deeply later)


some important function to know =>
bin()=> it changes the decimal or other form of number in binary.
oct()=> it changes the decimal or other form of number in the octal number.
hex()=> it changes the decimal or other form of number in the hexadecimal.
print()=> It helps to print the what you want to show to the user.
input()=> it helps to take the data from the user.

chapter 0: Functions and variables with I/O system

I/O system:
1. we can take input through eval and input.
result = eval(input("Enter a mathematical expression: "))
eval doesn't took number as a string. Another Tip💡= eval treat float as
float , int as int and etc.

2. we can take output by using print function:

name = 'sandip k.c.'


print("Hello, {}".format(name))

3.command line argument for giving input

from sys import argv


for var in argv[1:]:
print(var)
4.we can also print
number=7
hora=10
print("%d %d "%(number,hora))

# this helps to take the data from the user.


Name= input("what is your Name? ")

#strip() helps to remove the white space of str


Name = Name.strip().title() #even we can use this in same line with the input

#split() user name into first name and last name


first, last=Name.split(" ")
there is small difference between split() and split(" ")
"sandip kc".split() # ['sandip', 'kc']
"sandip kc".split(" ") # ['sandip', '', '', 'kc']

print("hello, "+first) #this doesnot add space coz here we are just concatinating
two string. so, we had to create a space by ourself.
print("hello,",Name) # this helps to give the space automatically.
print("hello,", sep=" ",end="") # it doesn't work because it needs to be multiple
arguement

#escape sequence:

print('hello, "my friend"')


print("hello, \"friend \"")

#special string:
print(f"hello, {Name}")
#capitlize()=> this helps to capitalize 1st letter of the 1st word of the str

#title()=> this helps to capitalize the 1sst letter of the every word

#if you want to do code into the terminal just type the python in the terminal.

# x= input("what's x?") this will give 12 as output so we have to use int( ) or


float( )outside of the input
# y= input("what's y?")
# z= x+y
# print(z)

# round()=> it helps to helps to round the decimal to the nearest integer


roound(nummber[,digits])

x= float(input("what's x?"))
y= float(input("what's y?"))
z=round(x+y,2)
print (f"{z:,}")

print (f"{z:.2f}") #this also helps ot round the number to the two digits

def main():
Name= input("what's your Name?")
def hello(to):
print("hello,", to)

hello(Name)

main()

def main():
x=int(input(" enter a number to get the square: "))
print(f"square of the {x} is ",square(x))

def square(x):
return x**2 #pow(n,2)

main()

chapter 1: conditionals

Conditionals in python means if the condition is true then do something if false


then don't do this search for else condition.
for e.g:
a=10
b=20
if (a<b):
print("a is not greater than b")
else:
print("a is greater than b")

we can do this in python:


score=int(input("enter your marks"))

if 80<= score <=100:


print("hora dai")
elif 50<=score <80:
print("you pass")
else:
print("you fail")

Ternary operator:

number1=int(input("1st number"))
number2=int(input("2nd number"))

greaterNumber= True if number1>number2 else True if number1==number2 else False

print(greaterNumber)
match(switch):

name=input("what's your name?")

match name:
case 'harry'| 'ram' | 'sita':
print("bhamake")
case 'arjun':
print("dang")
case 'sandip':
print("kamalPhokhari")
case _:
print("i don't have information.")

def main():
return True if n%2==0 else False or return n%2==0

Tip💡:
even we can return the boolean from the expression so, it can make short
and good practice of code

CHAPTER 2: lOOPS

Loops: It is a special structuree which helps to do same type of work many times in
short and quick period of time.

while loop:

I=3
WHILE I!=0:
PRINT("MOMO")
I-=1

for loop:
eg: of for loop:
str="string"
count=0
for i in str:
if i==str[count]:
print(f"{i}")
count+=1

chapter 3: function()

A function is a block of code which helps of execute the specific task


syntax:

def Sandip():
....
....

function based on the argument and return value


1.with Argument and with return value

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

result = add(5, 3) # With argument and return value


print(result) # Output: 8

2.without argument and with return value

code:
def greet():
return "Hello, World!"

message = greet() # Without argument, with return value


print(message) # Output: Hello, World!

3.without both argument and return value

code:

def say_hello():
print("Hello, World!") # No return value

say_hello() # Output: Hello, World!

4.with argument and but not with return value

code:
def display_message(name):
print(f"Hello, {name}!") # No return value

display_message("Alice") # Output: Hello, Alice!

function based on the types


1.built in function/library function
2.user-defined function
1. Positional Arguments

Arguments are passed in the order they appear in the function definition.

Example:

def greet(name, age):


print(f"Hello {name}, you are {age} years old.")

greet("Alice", 25) # Output: Hello Alice, you are 25 years old.

2. Keyword Arguments

Arguments are passed using the parameter name, regardless of their order.

Example:

def greet(name, age):


print(f"Hello {name}, you are {age} years old.")

greet(age=25, name="Alice") # Output: Hello Alice, you are 25 years old.

3. Default Arguments

Arguments have default values, and you can override them if needed.

Example:

def greet(name, age=18):


print(f"Hello {name}, you are {age} years old.")

greet("Alice") # Output: Hello Alice, you are 18 years old.


greet("Bob", 30) # Output: Hello Bob, you are 30 years old.

4. Variable-Length Arguments

Used to pass an arbitrary number of arguments.


a. *args (Non-Keyworded)

Allows passing multiple positional arguments as a tuple.


Example:

def add(*numbers):
print(sum(numbers))

add(1, 2, 3, 4) # Output: 10

b. **kwargs (Keyworded)

Allows passing multiple keyword arguments as a dictionary.


Example:
def greet(**details):
for key, value in details.items():
print(f"{key}: {value}")

greet(name="Alice", age=25, city="New York")


# Output:
# name: Alice
# age: 25
# city: New York

library module function:

Local Variable

Defined inside a function, accessible only within that function.

def func():
x = 10 # Local variable
print(x)

func()
# print(x) # Error: x is not accessible outside the function

Global Variable

Defined outside any function, accessible throughout the program.

y = 20 # Global variable

def func():
print(y) # Accessible inside the function

func()
print(y) # Accessible outside the function

Recursive function: A recursive function is a function that calls itself to solve


smaller instances of a problem until a base condition is met.
Example: Factorial Calculation

def factorial(n):
if n == 0 or n == 1: # Base case
return 1
else:
return n * factorial(n - 1) # Recursive call

# Example usage
print(factorial(5)) # Output: 120

An anonymous function, also known as a lambda function in Python, is a function


defined without a name. It is typically used for short, simple operations and
written using the lambda keyword.
Syntax:

lambda arguments: expression

Example:
1. Basic Lambda Function

square = lambda x: x ** 2
print(square(5)) # Output: 25

2. Lambda Function with Multiple Arguments

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

3. Using Lambda in a map() Function

nums = [1, 2, 3, 4]
squares = list(map(lambda x: x ** 2, nums))
print(squares) # Output: [1, 4, 9, 16]

Key Characteristics:

Anonymous: No name; often assigned to a variable or used directly.


Single Expression: Can only contain one expression.
Use Case: Ideal for short, throwaway functions (e.g., sorting, filtering, or
mapping).

1. map()

Definition: Applies a given function to each item in an iterable and returns a


new iterable with the results.
Syntax: map(function, iterable)

Example:

nums = [1, 2, 3, 4]
squares = list(map(lambda x: x ** 2, nums))
print(squares) # Output: [1, 4, 9, 16]

2. filter()

Definition: Filters elements from an iterable based on a function that returns


True or False.
Syntax: filter(function, iterable)
Example:

nums = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens) # Output: [2, 4, 6]

3. reduce()

Definition: Repeatedly applies a function to elements in an iterable, reducing


it to a single cumulative value.
Requires: reduce() is not built-in; it must be imported from functools.
Syntax: reduce(function, iterable)

Example:

from functools import reduce

nums = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, nums)
print(product) # Output: 24 (1 * 2 * 3 * 4)

function aliasing:
Function aliasing in Python refers to the practice of creating an alternative name
(or alias) for a function. Both the original function name and the alias can be
used interchangeably to call the function.
Example:

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

# Create an alias for the 'greet' function


say_hello = greet

chapter 4= string

Ways of representation of string:


a=' '
a=" "
a="' '"
str(input())
str()
eval()
accessing=> slicing and Indexing both concept are used in string

mathematical operator=>+ and * only these two are applicable


for eg
s='sandip'
k='k.c.'
sk= s+k which is sandipk.c.

skc=s*3 which is sandipsandipsandip

membersip operator=>
s='kathmandu'
if 'kath' in s: it will result in True

tips💡:
like in string during the comparison, pvm compares three things that is case,
length, order so, to be equal all these three should be equal. ascii value of A is
65 and a is 97

some important function used in string function:

len(): Returns the length (number of characters) of a string or the number of


elements in an iterable (like a list, tuple, or dictionary).
Example: len("Python") → 6.

strip(): Removes leading and trailing whitespace (or specified characters) from a
string.
Example: " hello ".strip() → "hello".

lstrip(): Removes leading (left-side) whitespace (or specified characters) from a


string.
Example: " hello ".lstrip() → "hello ".

rstrip(): Removes trailing (right-side) whitespace (or specified characters) from a


string.
Example: " hello ".rstrip() → " hello".

index(): Returns the first index of a specified substring in a string. Raises a


ValueError if the substring is not found.
Example: "Python".index("t") → 2.

find(): Returns the first index of a specified substring in a string. Returns -1 if


the substring is not found.
Example: "Python".find("t") → 2.

rindex(): Returns the last index of a specified substring in a string. Raises a


ValueError if the substring is not found.
Example: "Python Python".rindex("t") → 9.
rfind(): Returns the last index of a specified substring in a string. Returns -1 if
the substring is not found.
Example: "Python Python".rfind("t") → 9.

rjust(): Right-aligns a string within a specified width, padding with spaces (or a
specified character).
Example: "Python".rjust(10) → " Python".

ljust(): Left-aligns a string within a specified width, padding with spaces (or a
specified character).
Example: "Python".ljust(10) → "Python ".

count(): Returns the number of non-overlapping occurrences of a specified substring


in a string.
Example: "Python".count("o") → 1.

replace(): Replaces all occurrences of a specified substring with another


substring.
Example: "hello world".replace("world", "Python") → "hello Python".

join(): Concatenates elements of an iterable (like a list) into a single string,


with each element separated by the string it is called on.
Example: ", ".join(["Python", "is", "fun"]) → "Python, is, fun".

splitlines(): Splits a string into a list of lines, breaking at line boundaries (\


n, \r, etc.).
Example: "line1\nline2\rline3".splitlines() → ["line1", "line2", "line3"].

startswith(): Returns True if the string starts with the specified prefix,
otherwise False.
Example: "Python".startswith("Py") → True.

endswith(): Returns True if the string ends with the specified suffix, otherwise
False.
Example: "Python".endswith("on") → True.

changing case of the string:

lower(): Converts all uppercase characters in a string to lowercase.


Example: "PYTHON".lower() → "python".

upper(): Converts all lowercase characters in a string to uppercase.


Example: "python".upper() → "PYTHON".

swapcase(): Converts all uppercase characters to lowercase and all lowercase


characters to uppercase.
Example: "PyThOn".swapcase() → "pYtHoN".

capitalize(): Converts the first character of the string to uppercase and the rest
to lowercase.
Example: "python programming".capitalize() → "Python programming".

title(): Converts the first character of each word to uppercase and the rest to
lowercase.
Example: "python programming".title() → "Python Programming".
to check the type of character present in the string:
isalnum(): True if all characters are alphanumeric and not empty.
Example: "Python123".isalnum() → True.

isalpha(): True if all characters are alphabetic and not empty.


Example: "Python".isalpha() → True.

isdigit(): True if all characters are digits and not empty.


Example: "12345".isdigit() → True.

isspace(): True if all characters are whitespace and not empty.


Example: " ".isspace() → True.

islower(): True if all alphabetic characters are lowercase.


Example: "python".islower() → True.

isupper(): True if all alphabetic characters are uppercase.


Example: "PYTHON".isupper() → True.

istitle(): True if string is in title case (first letter uppercase).


Example: "Python Programming".istitle() → True.

chapter 5= List

denoted by square bracket '[]'


insert order is preserved indexing and slicing
dynamically growable and shrinkable
support mutability
support homogenous and heterogenous

ways of creation of list

empty list=> l=[]


list with known element l=[1,2,4,5,5]
dynamically (eval)
list() function
split()

Accessing:
accessing list element:
slicing concept and indexing concept

len(): Returns the number of items in a list.

my_list = [1, 2, 3]
print(len(my_list)) # Output: 3
count(): Counts occurrences of a specific element in a list.

my_list = [1, 2, 2, 3]
print(my_list.count(2)) # Output: 2

index(): Returns the index of the first occurrence of an element.

my_list = [1, 2, 3]
print(my_list.index(2)) # Output: 1

append(): Adds an element to the end of a list.

my_list = [1, 2]
my_list.append(3)
print(my_list) # Output: [1, 2, 3]

insert(): Inserts an element at a specified position.

my_list = [1, 3]
my_list.insert(1, 2)
print(my_list) # Output: [1, 2, 3]

extend(): Adds all elements of an iterable to the end of the list.

my_list = [1, 2]
my_list.extend([3, 4])
print(my_list) # Output: [1, 2, 3, 4]

remove(): Removes the first occurrence of a specific element.

my_list = [1, 2, 3]
my_list.remove(2)
print(my_list) # Output: [1, 3]

pop(): Removes and returns the element at a specified position (default is the last
element).

my_list = [1, 2, 3]
print(my_list.pop()) # Output: 3
print(my_list) # Output: [1, 2]

reverse(): Reverses the list in place.

my_list = [1, 2, 3]
my_list.reverse()
print(my_list) # Output: [3, 2, 1]

sort(): Sorts the list in ascending order (can use reverse=True for descending).

my_list = [3, 1, 2]
my_list.sort()
print(my_list) # Output: [1, 2, 3]

clear(): Removes all elements from the list.

my_list = [1, 2, 3]
my_list.clear()
print(my_list) # Output: []
List Aliasing: List aliasing occurs when multiple variables reference the same list
object in memory. Changes made through one variable affect the other(s).
Example:

list1 = [1, 2, 3]
list2 = list1 # Both refer to the same list
list2.append(4)
print(list1) # Output: [1, 2, 3, 4]
print(list2) # Output: [1, 2, 3, 4]

list comprehensive: A concise way to create lists using a single line of code,
often with a for loop and an optional condition.

Syntax:
[expression for item in iterable if condition]

Examples:

Basic Comprehension:

nums = [1, 2, 3, 4]
squares = [x**2 for x in nums]
print(squares) # Output: [1, 4, 9, 16]

With Condition:

nums = [1, 2, 3, 4]
even_nums = [x for x in nums if x % 2 == 0]
print(even_nums) # Output: [2, 4]

chapter 6=Tuple

denoted by()
insertion order is preserved
indexing
slicing
dynamically growable and shrinkable (X)=> it is not possible
not support mutability
support homogenous and heterogenous element

way of creation tuple


empty tuple

t=()
t=tuple()
tuple with known element
t=(10,20,30,40,50,60)
t=tuple()

eval()
t=eval(input('enter any tuple: ')

tuple()
t=tuple(l)
(10,20,30,40)

function used in tuple:

1. len()

Definition: Returns the total number of elements in the tuple.


Example: For the tuple (1, 2, 3), len() will return 3.

2. count()

Definition: Returns the number of times a specific element appears in the tuple.
Example: For the tuple (1, 2, 2, 3), calling count(2) will return 2.

3. index()

Definition: Returns the index of the first occurrence of a specified element in the
tuple. If the element does not exist, an error is raised.
Example: For the tuple (4, 5, 6, 5), calling index(5) will return 1.

4. sorted()

Definition: Returns a new list containing the sorted elements of the tuple in
ascending order (does not modify the original tuple).
Example: For the tuple (3, 1, 4, 2), sorted() will return [1, 2, 3, 4].

5. min()

Definition: Returns the smallest element in the tuple.


Example: For the tuple (8, 3, 7), min() will return 3.

6. max()

Definition: Returns the largest element in the tuple.


Example: For the tuple (8, 3, 7), max() will return 8.

packing and unpacking:


Packing

Definition: Packing is the process of combining multiple values into a single


tuple.
Example:
Imagine you have the numbers 1, 2, and 3. Packing them into a tuple would look like
this: (1, 2, 3).
Unpacking
Definition: Unpacking is the process of breaking a tuple into individual values.
Example:
If you have a tuple (1, 2, 3), unpacking would give you the individual values 1, 2,
and 3.
Unpacking with *

Definition: You can use the * symbol to collect extra elements into a list during
unpacking.
Example:
For a tuple (1, 2, 3, 4), if you unpack it with *, you can get 1, a list of middle
values [2, 3], and 4.
Nested Unpacking

Definition: Unpacking a tuple that contains another tuple inside it.


Example:
For a tuple (1, (2, 3), 4), unpacking would give you 1, the values 2 and 3 from the
nested tuple, and 4.

note: tuple doesnot accept tuple comprehension

single value tuple:


t=(10,)

chapter 7= set and dictionary


set
properties:
denoted by {}
insertion order is not preserved(indexing and slicing is not used)
support mutability
grownable and shrinkable dynamically
supports homogeneous and heterogeneous data
can't support duplicate elements

way of creation of set

empty set:
s={} not valid in set coz the data type will say this is dict
s=set{} this is valid

set with known element


s={10,20,30,40}

eval()= it also helps to create the set

set():
l=[10,10,20,3,5,5]
s= set(l) the output will be 10,20,3,5

note💡=only subtraction symbol can be used in this set '-'


set can't be compared.
while comparing only double equals is applicable

set operation

union=> s|s1
intersection=>s&s1
difference=>s-s1
symmetric difference=>s^s1

some useful function used in set:


Add()
s={10,20,30,40,5}
s.add{100}

print(s)=>{10,20,100,30,40,5}

update():

Adds elements from another iterable to the set.

s = {1, 2, 3}
s.update([4, 5])
# Result: {1, 2, 3, 4, 5}

copy():

Creates a copy of the set.

s = {1, 2, 3}
new_set = s.copy()
# Result: new_set = {1, 2, 3}

pop():

Removes and returns a random element from the set.

s = {1, 2, 3}
popped_item = s.pop()
# Result: popped_item = 1 (could be any element), s = {2, 3}

remove():

Removes a specific element from the set, raises a KeyError if not found.

s = {1, 2, 3}
s.remove(2)
# Result: s = {1, 3}

discard():

Removes a specific element from the set, but does nothing if not found.
s = {1, 2, 3}
s.discard(2)
# Result: s = {1, 3}

clear():

Removes all elements from the set.

s = {1, 2, 3}
s.clear()
# Result: s = set()

A set comprehension is a concise way to create sets in Python using a single line
of code. It follows the syntax:

{expression for item in iterable if condition}

expression: The value or transformation to add to the set.


item: Each element of the iterable (such as a list, tuple, string, etc.).
iterable: The object that can be iterated (like a list or range).
condition (optional): A condition that filters elements to be included.

Dictionary:
properties:
denoted by '{}'=> key-value pair
indexing & slicing not applicable
supports mutability
value duplicate

way of defining dict:


empty dict
d={}
d=dict{}

set with the known elements


dynamically dict=> eval()
by using dict()
l=[(5,6),(10,11)]
d=dict(l)

some useful function used in dictionary


with the ways of accessing as well

. clear()

Removes all items from the dictionary, making it empty.

d = {'a': 1, 'b': 2}
d.clear()
print(d) # Output: {}

2. get(key, default=None)
Returns the value for the specified key. If the key is not found, returns the
default value (or None if not provided).

d = {'a': 1, 'b': 2}
print(d.get('a')) # Output: 1
print(d.get('z')) # Output: None
print(d.get('z', 'NA')) # Output: NA

3. pop(key, default=None)

Removes the specified key and returns its value. If the key is not found, returns
the default value (or raises a KeyError if no default is provided).

d = {'a': 1, 'b': 2}
print(d.pop('a')) # Output: 1
print(d) # Output: {'b': 2}
print(d.pop('z', 'NA')) # Output: NA

4. popitem()

Removes and returns the last key-value pair as a tuple. Raises a KeyError if the
dictionary is empty (in Python 3.7+).

d = {'a': 1, 'b': 2}
print(d.popitem()) # Output: ('b', 2)
print(d) # Output: {'a': 1}

5. keys()

Returns a view of all the keys in the dictionary.

d = {'a': 1, 'b': 2}
print(d.keys()) # Output: dict_keys(['a', 'b'])

To convert to a list:

keys_list = list(d.keys())
print(keys_list) # Output: ['a', 'b']

6. values()

Returns a view of all the values in the dictionary.

d = {'a': 1, 'b': 2}
print(d.values()) # Output: dict_values([1, 2])

To convert to a list:

values_list = list(d.values())
print(values_list) # Output: [1, 2]

7. copy()

Returns a shallow copy of the dictionary.

d = {'a': 1, 'b': 2}
copy_d = d.copy()
print(copy_d) # Output: {'a': 1, 'b': 2}
# Modifying the copy won't affect the original
copy_d['a'] = 99
print(d) # Output: {'a': 1, 'b': 2}

8. setdefault(key, default=None)

If the key exists, returns its value. If the key does not exist, adds the key with
the specified default value and returns the default.

d = {'a': 1, 'b': 2}
print(d.setdefault('a', 10)) # Output: 1
print(d.setdefault('z', 10)) # Output: 10
print(d) # Output: {'a': 1, 'b': 2, 'z': 10}

9. update([other])

Updates the dictionary with the key-value pairs from another dictionary or an
iterable of key-value pairs. If a key already exists, its value is updated.

d = {'a': 1, 'b': 2}
d.update({'b': 20, 'c': 30})
print(d) # Output: {'a': 1, 'b': 20, 'c': 30}

# Using an iterable of tuples


d.update([('d', 40), ('e', 50)])
print(d) # Output: {'a': 1, 'b': 20, 'c': 30, 'd': 40, 'e': 50}

del keyword

1. Deleting a Specific Key-Value Pair

Use del with the key you want to remove from the dictionary.

d = {'a': 1, 'b': 2, 'c': 3}


del d['b']
print(d) # Output: {'a': 1, 'c': 3}

dictionary comprehension:
Basic Syntax:

{key_expression: value_expression for item in iterable if condition}

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


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

chapter 8= file handling


f=open(filename,mode)
f.close()=> closes the text file
r=read
w=write (overwrite)
a=append
r+=read and write
w+= read and write but overwrite also
a+= read write and don't do overwrite
rb= read binary
r+b=read and write binary (same as other)

write() helps to write only one data


writelines() function helps to write the group of data

these two function only takes the data as string

read() Reads entire file content.


read(n) Reads n characters from the file.
readline() Reads one line at a time.
readlines() Reads all lines and returns a list.

Tip💡:
✅file.write("\n".join(lines)) # Joins list with newlines
✅seek() → Moves the cursor.
✅ tell() → Shows where the cursor is.

You might also like