Wednesday, September 4, 2024

PYTHON - FILE HANDLING

 File Handling in python


File handling in Python allows you to work with files on your computer's filesystem. You can create, read, write, and manipulate files using various methods and functions provided by Python's built-in modules. Here, I'll explain the basic concepts of file handling in Python and provide a sample program for each operation.


Opening and Closing Files:
To work with a file, you must first open it using the open() function. It takes two arguments: the filename and the mode in which you want to open the file (e.g., read, write, append, etc.). After working with the file, you should close it using the close() method to free up system resources.

Sample program to open and close a file:

# Opening a file in write mode
file = open("sample.txt", "w")

# Writing data to the file
file.write("Hello, World!")

# Closing the file
file.close()


Reading from a File:

You can read the contents of a file using the read() method or by iterating over the file line by line using a loop.

Sample program to read from a file:

# Opening a file in read mode
file = open("sample.txt", "r")

# Reading the entire content
content = file.read()
print(content)

# Closing the file
file.close()


Writing to a File:
Open it in write mode ("w") to write data to a file. You can use the write() method to add content to the file. Be cautious, as opening a file in write mode will overwrite its existing content.

Sample program to write to a file:

# Opening a file in write mode
file = open("sample.txt", "w")

# Writing data to the file
file.write("Hello, World!")

# Closing the file
file.close()

Appending to a File:
If you want to add content to a file without overwriting the existing content, open the file in append mode ("a").

Sample program to append to a file:

# Opening a file in append mode
file = open("sample.txt", "a")

# Appending data to the file
file.write("\nThis is a new line.")

# Closing the file
file.close()

PYTHON - SCOPE

 Python Scope


In Python, "scope" refers to the region or context in which a variable is defined and can be accessed. Python has different levels of scope, including global scope and local scope, and the scope of a variable determines where it can be used or accessed in your code. Understanding scope is crucial for writing clean, maintainable, and bug-free Python programs. Here, I'll explain in detail about Python scope with sample code.

1. Local Scope:

Variables defined within a function have local scope. They are only accessible within that function.
A new local scope is created every time a function is called, and it is destroyed when the function exits.

def my_function():
    local_variable = 42
    print(local_variable)

my_function()  # Calls the function
print(local_variable)  # Raises a NameError because local_variable is not defined here

2. Enclosing (Non-Local) Scope:

In nested functions, variables can be in an "enclosing" scope, also known as a "non-local" scope.
Variables in the enclosing scope are not global but are accessible within the nested functions.

def outer_function():
    outer_variable = 10

    def inner_function():
        print(outer_variable)  # Accesses the outer_variable from the enclosing scope

    inner_function()

outer_function()

3. Global Scope:

Variables defined outside of any function have global scope. They can be accessed from any part of the program.

global_variable = 100

def my_function():
    print(global_variable)  # Accesses the global_variable

my_function()

4. Built-in Scope:

Python has a built-in scope that contains functions and objects provided by Python itself.
You can access built-in functions and objects like print(), len(), str, and int without importing them.

print(len("Hello, World!"))  # Accesses the len() function from the built-in scope

5. Modifying Variables in an Enclosing Scope:

To modify a variable in an enclosing scope from within a nested function, you can use the nonlocal keyword.

def outer_function():
    outer_variable = 10

    def inner_function():
        nonlocal outer_variable  # Use nonlocal to modify outer_variable
        outer_variable += 5

    inner_function()
    print(outer_variable)  # Prints 15

outer_function()

6. Global Variables:

You can declare a variable as global inside a function using the global keyword.
This allows you to modify the global variable within the function.

global_variable = 100

def modify_global():
    global global_variable  # Declare global_variable as global
    global_variable += 10

modify_global()
print(global_variable)  # Prints 110

Scope determines where a variable is visible and accessible. Python follows the LEGB (Local, Enclosing, Global, Built-in) rule for variable name resolution, which means it first looks for a variable in the local scope, then in any enclosing scopes, then in the global scope, and finally in the built-in scope.

PYTHON - DICTIONARY

 Dictionary


A Python dictionary is a data structure that stores key-value pairs. It's similar to a real-world dictionary where you look up a word (the key) to find its definition (the value). Here are some essential functions and operations associated with Python dictionaries:

1. Creating a Dictionary: You can create a dictionary using curly braces `{}` and separating key-value pairs with colons.
For example:
   python
   my_dict = {"key1": value1, "key2": value2}

Dict1 = {"Name":"Bhaskar","Desg":"Domain Lead","Age":34,"City":"Chennai"}
print(Dict1)

my_dict2 = dict(name="Bob", age=25, city="Los Angeles")
print(my_dict2)
   

2. Accessing Values: You can access the value associated with a specific key using square brackets [].
For example:
   python
   value = my_dict["key1"]


EID424 = {"Name":"Bhaskar","Desg":"Domain Lead","City":"Chennai"}
EID425 = {"Name":"Senthil","Desg":"Domain Mem","City":"Chennai"}
EID426 = {"Name":"Venkatesh","Desg":"Domain Manager","City":"Chennai"}
print(EID426)
desg = EID426["Desg"]
print(desg)

for item in EID424.values():
    print(item)

for key in E424.keys(): # iterate through keys
    print(key)
   
for value in E424.values():  # iterate through values
    print(value)
   
for key,value in E424.items():  # iterate through keys value pairs
    print(key,value)  

3. Adding or Updating Key-Value Pairs: You can add new key-value pairs or update existing ones by assigning a value to a new or existing key. For example:
   python
   my_dict["new_key"] = new_value
   

4. Removing Key-Value Pairs: You can remove key-value pairs using the del keyword or the `pop()` method. For example:
   python
   del my_dict["key1"]
   value = my_dict.pop("key2")
   

5. Dictionary Methods:
   - keys(): Returns a view object that displays a list of all the keys in the dictionary.
   - values(): Returns a view object that displays a list of all the values in the dictionary.
   - items(): Returns a view object that displays a list of key-value tuples.
   - get(key): Returns the value associated with the specified key. If the key does not exist, it returns `None` (or a default value if provided).
   - clear(): Removes all key-value pairs from the dictionary.

6. Checking Key Existence: You can check if a key exists in a dictionary using the `in` keyword. For example:
   python
   if "key1" in my_dict:
       # do something
 

7. Dictionary Comprehension: Like list comprehensions, Python supports dictionary comprehensions for creating dictionaries in a compact and efficient manner. For example:
   python
   squares = {x: x*x for x in range(1, 6)}
   

These are just some of the fundamental operations and methods associated with Python dictionaries

PYTHON - SETS

 Sets:


Sets are unordered collections of unique elements.
They are defined using curly braces {} or the set() constructor.
Sets are useful for removing duplicates and performing set operations (union, intersection, difference, etc.).

In Python, a set is an unordered collection of unique elements. Sets are defined using curly braces {} or the set() constructor. Sets do not allow duplicate values, and they are primarily used for performing mathematical set operations like union, intersection, difference, and more. Here, I'll explain in detail about sets and their operations in Python.

Example:

my_set = {1, 2, 3, 4, 4}

1. Creating Sets:
You can create a set by enclosing a sequence of elements within curly braces {} or by using the set() constructor. Sets can contain elements of any data type.

my_set1 = {1, 2, 3, 4, 5}
my_set2 = set([3, 4, 5, 6, 7])

2. Adding Elements:
You can add elements to a set using the add() method. Sets do not allow duplicate values, so adding a duplicate will have no effect.

my_set = {1, 2, 3}
my_set.add(4)  # Adds 4 to the set
my_set.add(2)  # Does not add 2 (already in the set)

3. Removing Elements:
You can remove elements from a set using the remove() or discard() method. The remove() method raises a KeyError if the element does not exist, while discard() does nothing in such cases.

my_set = {1, 2, 3, 4}
my_set.remove(3)   # Removes 3 from the set
my_set.discard(2)  # Removes 2 from the set

4. Set Operations:

Sets support various set operations like union, intersection, difference, and symmetric difference.

Union (| or union()): Combines two sets, keeping only unique elements.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2  # or set1.union(set2)
Intersection (& or intersection()): Returns elements that are common to both sets.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1 & set2  # or set1.intersection(set2)
Difference (- or difference()): Returns elements in the first set but not in the second.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = set1 - set2  # or set1.difference(set2)
Symmetric Difference (^ or symmetric_difference()): Returns elements that are in either of the sets but not in both.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
symmetric_diff_set = set1 ^ set2  # or set1.symmetric_difference(set2)

5. Checking Membership:
You can check if an element is a member of a set using the in keyword.

my_set = {1, 2, 3}
is_present = 2 in my_set  # Returns True

6. Length of a Set:
You can find the number of elements in a set using the len() function.

my_set = {1, 2, 3, 4}
length = len(my_set)  # Returns 4

7. Iterating Through Sets:
You can use a for loop to iterate through the elements of a set.

my_set = {1, 2, 3}
for item in my_set:
    print(item)

Sets are commonly used for tasks that require unique values or for performing set-related operations like checking for common elements between collections, finding unique elements, or eliminating duplicates. Sets are an essential part of Python's standard library for data manipulation.

Common operations on sets inclu
de:

Adding elements: add()
Removing elements: remove(), discard()
Set operations: union(), intersection(), difference(), symmetric_difference()
Finding length: len()
Iterating: for item in my_set

 

PYTHON - TUPLES

 Tuples:


Tuples are similar to lists but are immutable (cannot be modified once created).
They are defined using parentheses ().
Tuples are often used for data that should not change during the program's execution.

In Python, a tuple is an ordered, immutable (unchangeable), and iterable collection of elements. Tuples are similar to lists but have the key difference that once you create a tuple, you cannot modify its elements. Tuples are defined using parentheses (), and elements within the tuple are separated by commas. Here, I'll explain in detail about tuples and their operations in Python.

Example:

my_tuple = (1, 2, 3, "Python", 5.0)

1. Creating Tuples:
You can create a tuple by enclosing a sequence of values or objects within parentheses. Tuples can contain elements of any data type, including numbers, strings, other tuples, or a combination of types.

my_tuple = (1, 2, 3, "Python", 5.0)

2. Accessing Elements:
You can access individual elements in a tuple by their index, just like with lists. Python uses zero-based indexing.

first_element = my_tuple[0]  # Accesses the first element (1)
third_element = my_tuple[2]  # Accesses the third element (3)

3. Immutability:
Tuples are immutable, which means you cannot change their elements after they are created. Attempting to modify a tuple will result in an error.

my_tuple[3] = "Hello"  # This will raise a TypeError


4. Tuple Packing and Unpacking:
You can pack multiple values into a single tuple or unpack a tuple into individual variables.

# Packing values into a tuple
my_packed_tuple = 1, "Python", 3.14
print(my_packed_tuple)

# Unpacking a tuple into variables
x, y, z = my_packed_tuple

5. Finding Elements:
You can use the index() method to find the index of the first occurrence of a specific value in the tuple. If the element is not found, it raises a ValueError.

index_of_2 = my_tuple.index(2)  # Finds the index of the element 2 (1)

6. Length of a Tuple:
You can find the number of elements in a tuple using the len() function.

length = len(my_tuple)  # Returns the length of the tuple (5)

7. Iterating Through Tuples:

You can use a for loop to iterate through the elements of a tuple.

for item in my_tuple:
    print(item)

8. Concatenating Tuples:
You can concatenate two or more tuples using the + operator to create a new tuple.

tuple1 = (1, 2, 3)
tuple2 = ("a", "b", "c")
concatenated_tuple = tuple1 + tuple2

9. Repetition:
You can create a new tuple by repeating an existing tuple using the * operator.

my_tuple = (1, 2)
repeated_tuple = my_tuple * 3  # Creates (1, 2, 1, 2, 1, 2)

Tuples are commonly used when you need to represent a collection of elements that should not be modified, such as coordinates, record fields, or function return values. The immutability of tuples can help ensure data integrity in your programs.

Common operations on tuples include:

Accessing elements: indexing
Unpacking: (a, b) = (1, 2)
Finding length: len()
Iterating: for item in my_tuple

Python -Lists

 Lists:


Lists are one of the most versatile and commonly used data structures in Python.
They are ordered, mutable (modifiable), and can contain elements of different data types.
Lists are defined using square brackets [].

Example:

my_list = [1, 2, 3, "Python", 5.0]

Common operations on lists include:

Adding elements: append(), insert()
Removing elements: remove(), pop()
Accessing elements: indexing and slicing
Modifying elements: direct assignment
Finding length: len()
Iterating: for item in my_list

In Python, a list is a fundamental data structure that allows you to store and manipulate collections of data. Lists are ordered, mutable (modifiable), and can contain elements of different data types. Lists are defined using square brackets [], and elements within the list are separated by commas. Here, I'll explain in detail about lists and their operations in Python.

1. Creating Lists:
You can create a list by enclosing a sequence of values or objects within square brackets. Lists can contain elements of any data type, including numbers, strings, other lists, or even a combination of types.

my_list = [1, 2, 3, "Python", 5.0]

2. Accessing Elements:
You can access individual elements in a list by their index. Python uses zero-based indexing, meaning the first element has an index of 0, the second has an index of 1, and so on.

first_element = my_list[0]  # Accesses the first element (1)
third_element = my_list[2]  # Accesses the third element (3)

3. Modifying Elements:
Lists are mutable, which means you can change their elements by assigning new values to specific indices.

my_list[3] = "Hello"  # Modifies the fourth element

4.Adding Elements:

You can add elements to the end of a list using the append() method, or insert elements at a specific index using the insert() method.

   

my_list.append(6)        # Adds 6 to the end of the list
my_list.insert(1, "A")   # Inserts "A" at index 1


        5. Removing Elements:


You can remove elements from a list by their value using the remove() method, or by their index using the pop() method. The pop() method also returns the removed element.


my_list.remove("Python")  # Removes "Python" from the list
removed_element = my_list.pop(2)  # Removes the third element (3)

6. Slicing Lists:
Slicing allows you to create sublists by specifying a range of indices. The syntax for slicing is list[start:end], where start is the inclusive index and end is the exclusive index.

sublist = my_list[1:4]  # Creates a sublist from index 1 to 3 ([2, "Hello", 6])

7. Finding Elements:
You can use the index() method to find the index of the first occurrence of a specific value in the list. If the element is not found, it raises a ValueError.

index_of_2 = my_list.index(2)  # Finds the index of the element 2 (1)

8. Length of a List:
You can find the number of elements in a list using the len() function.

length = len(my_list)  # Returns the length of the list (4)

9. Iterating Through Lists:
You can use a for loop to iterate through the elements of a list.

for item in my_list:
    print(item)

These are some of the basic operations you can perform on lists in Python. Lists are versatile and widely used in Python for tasks such as data storage, iteration, and manipulation. Understanding how to work with lists is essential for many programming tasks.