> For the complete documentation index, see [llms.txt](https://va9ab0nd.gitbook.io/notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://va9ab0nd.gitbook.io/notes/programming-and-scripting/python-notes.md).

# Python  Notes

### Python?

HL programming Language

Interpreted Language

Can be Used in Interactive and scripting mode

#### Uses

* Web development Backend
* Math and complex Problem solving, Big data
* system Scripting & Automation
* ML and AI
* Databases

***

### Basics

Print Python version

```python
Python --version
```

Run a python script

```python
Python code.py 
```

Exit the Interactive mode

```python
exit()
```

***

### Basics Syntax

* **Python Indentation**

  * Indentation refers to the spaces at the beginning of a code line. Gaps After sub code

  ```bash
  def greet(name):
      if name:
          print("Hello, " + name + "!")
      else:
          print("Hello, there!")

  greet("Alice")
  greet("Bob")
  greet("")
  ```
* comments

  ```python
  # single line comment
  """
  * This is a multiline comment
  * Can also be used for __doc__ string in Funcntion
  """
  ```
* No Type Declaration needed in Python

***

### Variables

Variables are containers for storing data values.

No need to Declare the Variable type in python. A variable is created the moment you first assign a value to it.

```python
		x = 5         # x contains value 5 of type "int "
		x = 8         # now x = 8 of type "int"
		x = "jeevan"  # now is "jeevan" of type string
		
		print(x)
		>>> jeevan
		
		# the below statement prints the type of the variable (int/float/string/list.....)
		print(type(x))
		>>> <class "int">
```

#### Type Casting

Process of converting One datatype to other data type

```python
x = str(3)      # x will be '3'
y = int(3)      # y will be 3
z = float(3)    # z will be 3.0 
a = complex(6)  # a will be 6+0j
# Note: You cannot convert complex numbers into another number type.

```

#### **Many Values to Multiple Variables**

```python
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z) 
```

#### **One Value to Multiple Variables**

```python
x = y = z = "Orange"
print(x)
print(y)
print(z) 
```

#### **Unpack a Collection(list)**

```python
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
```

#### **Output Variables**

```python
x = "Python"
y = "is"
z = "awesome"
# best way to output multiple variables in the print() is to separate them with commas
print(x, y, z)
	>>> Python is awesome 
# not this
print(x + y + z)
	>>> Pythonisawesome 

-------------------------------------------------------------------------------------

# cant concatinate str and int type , we get error ,so typecast or format it(referString Interpolation ) 
x = 5
y = "John"
print(x + y)
>>> typeerror: unsupported operand type(s) for +: 'int' and 'str'
```

#### Global Variables

A global variable is a variable declared outside of any function or class definition. Global variables can be accessed from any part of the code, including inside functions or classes, without having to pass them as parameters.

However, if you want to modify a global variable from within a function, you need to use the `global` keyword to explicitly declare it.

```python
# Define a global variable
global_var = 10

def my_function():
    # Access the global variable
    print("Inside the function, global_var is:", global_var)

def modify_global():
    # Access and modify the global variable using the global keyword
    global global_var
    global_var = 20
    print("Inside modify_global function, global_var is now modified to:", global_var)

# Access global variable outside of any function
print("Outside of any function, global_var is:", global_var)

# Call the function
my_function()

# Modify global variable
modify_global()

# Verify the modification
print("After modification, global_var is:", global_var)
```

***

### **Data Types**

Variables can store data of different types, and different types can do different things.

Python has the following data types built-in by default, in these categories:

| Text Type:      | str                          |
| --------------- | ---------------------------- |
| Numeric Types:  | int, float,complex           |
| Sequence Types: | list, tuple, range           |
| Mapping Type:   | dict                         |
| Set Types:      | set, frozenset               |
| Boolean Type:   | bool                         |
| Binary Types:   | bytes, bytearray, memoryview |
| None Type:      | NoneType                     |

| Example                                      | Data Type  |
| -------------------------------------------- | ---------- |
| x = "Hello World"                            | str        |
| x = 20                                       | int        |
| x = 20.5                                     | float      |
| x = 1j                                       | complex    |
| x = \["apple", "banana", "cherry"]           | list       |
| x = ("apple", "banana", "cherry")            | tuple      |
| x = range(6)                                 | range      |
| x = {"name" : "John", "age" : 36}            | dict       |
| x = {"apple", "banana", "cherry"}            | set        |
| x = frozenset({"apple", "banana", "cherry"}) | frozenset  |
| x = True                                     | bool       |
| x = b"Hello"                                 | bytes      |
| x = bytearray(5)                             | bytearray  |
| x = memoryview(bytes(5))                     | memoryview |
| x = None                                     | NoneType   |

Getting the datatype

```python
x = 5
print(type(x)) 
```

***

### Numbers

There are three numeric types in Python:

* `int`
* `float`
* `complex`

```python
x = 1      # int
y = 2.8    # float
z = 3+5j   # complex
```

Print Random

```python
import random
print(random.randrange(1, 10)) 
```

***

### Strings

#### Creating Strings

Strings in Python can be created using either single quotes (`'`) or double quotes (`"`). Both methods are equivalent.

```python
string1 = "Hello"
string2 = 'World'

```

#### Concatenation

Strings can be concatenated using the `+` operator.

```python
string3 = string1 + " " + string2

```

#### Getting String Length

The `len()` function is used to get the length of a string.

```python
length = len(string3)

```

#### Accessing Characters

Strings can be indexed like arrays to access individual characters.

```python
name = "jeevan"
first_char = name[0]  # returns 'j'
last_char = name[-1]  # returns 'n'

```

#### Slicing

Slicing allows you to extract a substring from a string.

```python
substring = name[6:11]  # Extracts characters from index 6 to 10
substring = name[:11]   # From beginning to index 10
substring = name[6:]    # From index 6 to the end
substring = name[-5:-1] # From 5th character from the end to the 2nd character from the end
```

#### String Repetition

Strings can be repeated using the `*` operator.

```python
repeated_string = string1 * 3  # Repeats the string three times
```

#### Checking Substrings

You can check if a substring is present in a string using the `in` or `not in` operators.

```python
text = "hello, can you book a ticket ?"
contains_hello = "Hello" in text
contains_hello = "Hello" not in text

```

#### String Interpolation

String interpolation allows you to embed variables within strings for dynamic content.

```python
name = "jeevan"
age = 24
formatted_string = f"My name is {name} and I'm {age} years old."

```

#### Padding

Strings can be padded with spaces or other characters using `rjust()`, `ljust()`, or `center()` methods.

```python
text = "Python"

right_aligned_text = text.rjust(10)
print(right_aligned_text)  # Output: '    Python'

left_aligned_text = text.ljust(10, '-')
print(left_aligned_text)  # Output: 'Python----'

centered_text = text.center(10, '.')
print(centered_text)  # Output: '..Python..'
```

#### Trimming

Leading and trailing whitespace can be removed using the `strip()` method.

```python
trimmed_string = "   spaces   ".strip()

```

#### Split

```python
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!'] 
```

#### Case Conversion

Strings can be converted to uppercase or lowercase using `upper()` and `lower()` methods respectively.

```python
uppercase_string = string1.upper()
lowercase_string = string1.lower()

```

#### Capitalizing First Letter

The `capitalize()` method capitalizes the first letter of a string.

```python
capitalized_string = concatenated_string.capitalize()

```

These are some of the fundamental operations and methods used for string manipulation in Python. They allow for versatile handling of textual data.

#### Modify string

The `replace()` method replaces a string with another string:

```python
a = "Hello, World!"
print(a.replace("H", "J"))
```

[Python - String Methods](https://www.w3schools.com/python/python_strings_methods.asp)

***

### Booleans

Booleans represent one of two values: `True` or `False`.

Conditionals return booleans

Below things always return False

```python
bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({}) 
```

Check the Type

```python
x = 200
	print(isinstance(x, int)) 
```

### Operators

***

```python
# Arithmetic operators
num1 = 10
num2 = 5

addition = num1 + num2
subtraction = num1 - num2
multiplication = num1 * num2
division = num1 / num2
floor_division = num1 // num2
modulo = num1 % num2
exponentiation = num1 ** num2
----------------------------------------------------------------------------
# Comparison operators
equal_to = num1 == num2
not_equal_to = num1 != num2
greater_than = num1 > num2
less_than = num1 < num2
greater_than_or_equal_to = num1 >= num2
less_than_or_equal_to = num1 <= num2
----------------------------------------------------------------------------
# Logical operators
logical_and = (num1 > 0) and (num2 > 0)
logical_or = (num1 > 0) or (num2 > 0)
logical_not = not (num1 > 0)
----------------------------------------------------------------------------
# Assignment operators
result = 0
result += 5  # equivalent to result = result + 5
result -= 3  # equivalent to result = result - 3
result *= 2  # equivalent to result = result * 2
result /= 4  # equivalent to result = result / 4
result %= 2  # equivalent to result = result % 2
result **= 3  # equivalent to result = result ** 3
----------------------------------------------------------------------------
# Bitwise operators
bitwise_and = num1 & num2
bitwise_or = num1 | num2
bitwise_xor = num1 ^ num2
bitwise_not_num1 = ~num1
left_shift = num1 << 2
right_shift = num1 >> 1
----------------------------------------------------------------------------
# Identity operators[T/F]
is_equal = num1 is num2
is_not_equal = num1 is not num2
----------------------------------------------------------------------------
# Membership operators[T/F]
list_example = [1, 2, 3, 4, 5]
in_list = 3 in list_example
not_in_list = 6 not in list_example
```

## List data type \[ordered, changeable, Allows duplicate]

```python
# Creating a list
lis_T=[]      #empty list creation
my_list = [1, 4, 2, 8, 5]
my_list = [1,]
----------------------------------------------------------------------------
# Accessing elements,indexable
first_element = my_list[0]
last_element = my_list[-1]    #negative way
----------------------------------------------------------------------------
# Slicing
subset = my_list[1:4]  # Returns elements at index 1, 2, 3
----------------------------------------------------------------------------
# Modifying elements in list with index no.
my_list[2] = 10
----------------------------------------------------------------------------
# Adding elements
my_list.append(6)  # Adds 6 at the end
my_list.insert(2, 7)  # Inserts 7 at index 2
----------------------------------------------------------------------------
# Extending a list
another_list = [8, 9, 10]
my_list.extend(another_list)
----------------------------------------------------------------------------
# deleting,removeing,clearing items in list
# Deleting elements
del my_list[2]  # Deletes the element at index 2

# Removing elements
removed_element = my_list.pop(3)  # Removes and returns element at index 3
my_list.remove(9)  # Removes the first occurrence of 9

# Clearing the list
my_list.clear()
----------------------------------------------------------------------------
# Sorting the list
my_list.sort()  # Sorts the list in ascending order
my_list.sort(reverse=True) # sort in decending order
----------------------------------------------------------------------------
# List operations
sum_of_list = sum(my_list)
length_of_list = len(my_list)
max_value = max(my_list)
min_value = min(my_list)
----------------------------------------------------------------------------
# List comprehension
squared_numbers = [x**2 for x in my_list]
----------------------------------------------------------------------------
# Checking membership
is_present = 3 in my_list
not_present = 7 not in my_list
----------------------------------------------------------------------------
# Count occurrences
	count_of_2 = my_list.count(2)
```

### **Tuples data type \[ordered, unchangeable, Allows duplicate]**

```python
# Creating tuples
empty_tuple = ()
my_tuple = (1, 2, 3, 'a', 'b', 'c')
single_element_tuple = (42,)
----------------------------------------------------------------------------
# Accessing elements
first_element = my_tuple[0]
last_element = my_tuple[-1]
subset = my_tuple[1:4]  #  refer string slicing , same applies here
----------------------------------------------------------------------------
# as we cant change tuples we update tuple by converting to list and then back
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
----------------------------------------------------------------------------
#creating new tuple with updated item
thistuple = ("apple", "banana", "cherry")
y = ("orange",)
thistuple += y
print(thistuple)
----------------------------------------------------------------------------
# Tuple operations
length = len(my_tuple)
concatenated_tuple = my_tuple + (4, 5, 6)
repeated_tuple = my_tuple * 2
----------------------------------------------------------------------------
# Tuple methods
count_of_2 = my_tuple.count(2)
index_of_a = my_tuple.index('a')
----------------------------------------------------------------------------
# Unpacking a tuple
a, b, c = my_tuple[:3]

```

### set data type \[unordered, unchangeable\*, unindexed, No duplicate]

```python
# Creating sets
empty_set = set()
my_set = {1, 2, 3, 'a', 'b', 'c'}
list_to_set = set([1, 2, 3, 2, 1])  # Duplicates are automatically removed
----------------------------------------------------------------------------
# Basic operations
my_set.add(4)
my_set.remove('a')
my_set.discard('z')  # Removes 'z' if present, does nothing if not
my_set.clear()
----------------------------------------------------------------------------
# Set operations
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
intersection_set = set1.intersection(set2)
difference_set = set1.difference(set2)
symmetric_difference_set = set1.symmetric_difference(set2)

```

### Dictionary\[ordered\*\* and changeable No duplicates allowed]

```python
# Creating dictionaries
empty_dict = {}
my_dict = {'name': 'jeevan', 'age': 24, 'city': 'palamaner'}
----------------------------------------------------------------------------
# Accessing and modifying elements
name_value = my_dict['name']
print(name_value)
>>> jeevan
my_dict['age'] = 26
----------------------------------------------------------------------------
# Adding new key-value pair to dict
my_dict['occupation'] = 'cybersec'
----------------------------------------------------------------------------
# Removing elements
removed_value = my_dict.pop('city', None)
# Removes 'city' key and returns its value, or returns None if key not found
----------------------------------------------------------------------------
# Checking membership
is_name_present = 'name' in my_dict
is_height_present = 'height' in my_dict
----------------------------------------------------------------------------
# Dictionary methods
keys_list = list(my_dict.keys())  # var contains all then keys
values_list = list(my_dict.values()) # var contains all the values
items_list = list(my_dict.items()) # var contains all the key-value pairs
----------------------------------------------------------------------------
# Iterating through a dictionary
for key, value in my_dict.items():
    print(f"{key}: {value}")
----------------------------------------------------------------------------
# Dictionary comprehension
squared_values = {key: value**2 for key, value in my_dict.items() if isinstance(value, int)}

```

### If, while and for

```python
# Conditional statements (if)
x = 10
y = 20
----------------------------------------------------------------------------
if x < y:
    print("x is less than y")
elif x > y:
    print("x is greater than y")
else:
    print("x is equal to y")
----------------------------------------------------------------------------
# While loop
counter = 0
while counter < 5:
    print(f"Counter value: {counter}")
    counter += 1
----------------------------------------------------------------------------
# For loop (with range)
for i in range(5):
    print(f"Value of i: {i}")

# For loop (iterating through a list)
fruits = ['apple', 'banana', 'orange']
for fruit in fruits:
    print(f"Current fruit: {fruit}")

# For loop (iterating through a dictionary)
person = {'name': 'John', 'age': 25, 'city': 'New York'}
for key, value in person.items():
    print(f"{key}: {value}")
----------------------------------------------------------------------------
# Break and Continue in a loop
for i in range(10):
    if i == 5:
        break  # Exit the loop when i is 5
    if i % 2 == 0:
        continue  # Skip even numbers
    print(f"Value of i: {i}")

```

## Python?

High Level programming Language unlike c/c++ Interpreted Language Can be Used in Interactive and scripting mode

#### Uses

* Web development Backend
* Math and complex Problem solving, Big data
* system Scripting & Automation
* ML and AI
* Databases

***

### Basics

Print Python version

```python
Python --version

```

Run a python script

```python
Python code.py

```

Exit the Interactive mode

```python
exit()

```

***

### Basics Syntax

* **Python Indentation**

  * Indentation refers to the spaces at the beginning of a code line.

  ```python
  def greet(name):
      if name:
          print("Hello, " + name + "!")
      else:
          print("Hello, there!")

  greet("Alice")
  greet("Bob")
  greet("")

  ```
* **Comments**

  ```python
  # single line comment
  """
  * This is a multiline comment
  * Can also be used for __doc__ string in Funcntion
  """

  ```
* **No Type Declaration needed in Python**

***

## Input and Output in Python

#### 1. Printing Output:

Python's `print()` function is used to display output to the standard output device, typically the console. Example:

```python
print("Hello, World!")  # Prints "Hello, World!"

```

#### 2. Reading Input:

Python's `input()` function is used to take user input from the standard input device, typically the keyboard. It reads a line from the input and converts it into a string. Example:

```python
name = input("Enter your name: ")  # Prompts user to enter their name

# if input is int convert to int as by default python takes input as string
name = int(input("Enter your name: "))

```

#### 3. Formatted Output:

Python supports formatted output using the `print()` function with formatted string literals (f-strings) or using the `format()` method. Example:

```python
name = "Alice"
age = 30
print(f"Name: {name}, Age: {age}")

```

#### 4. Reading Multiple Inputs:

For reading multiple inputs on the same line, you can use the `split()` method to split the input string into separate values. Example:

```python
# Input: 1 2 3
values = input("Enter multiple values separated by space: ").split()
# values = ['1', '2', '3']

```

***

## Variables

* Variables are containers for storing data values.
* No need to Declare the Variable type in python. A variable is created the moment you first assign a value to it.

```python
x = 5         # x contains value 5 of type "int "
x = 8         # now x = 8 of type "int"
x = "jeevan"  # now is "jeevan" of type string
print(x)
>>> jeevan

# the below statement prints the type of the variable
print(type(x))
>>> <class "int">

```

#### Type Casting

Process of converting One datatype to other data type

```python
x = str(3)      # x will be '3'
y = int(3)      # y will be 3
z = float(3)    # z will be 3.0
a = complex(6)  # a will be 6+0j
# Note: You cannot convert complex numbers into another number type.

```

#### **Many Values to Multiple Variables**

```python
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)

```

#### **One Value to Multiple Variables**

```python
x = y = z = "Orange"
print(x)
print(y)
print(z)

```

#### **Unpack a Collection(list)**

```python
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)

```

#### **Output Variables**

```python
x = "Python"
y = "is"
z = "awesome"
# best way to output multiple variables in the print() is to separate them with commas
print(x, y, z)
	>>> Python is awesome
# not this
print(x + y + z)
	>>> Pythonisawesome

-----------------------------------------------------------------------------

# cant concatinate str and int type , we get error ,so typecast or format it(referString Interpolation )
x = 5
y = "John"
print(x + y)
>>> typeerror: unsupported operand type(s) for +: 'int' and 'str'

```

#### Global Variables

A global variable is a variable declared outside of any function or class definition. Global variables can be accessed from any part of the code, including inside functions or classes, without having to pass them as parameters.

However, if you want to modify a global variable from within a function, you need to use the `global` keyword to explicitly declare it.

```python
# Define a global variable
global_var = 10

def my_function():
    # Access the global variable
    print("Inside the function, global_var is:", global_var)

def modify_global():
    # Access and modify the global variable using the global keyword
    global global_var
    global_var = 20
    print("Inside modify_global function, global_var is now modified to:", global_var)

# Access global variable outside of any function
print("Outside of any function, global_var is:", global_var)

# Call the function
my_function()

# Modify global variable
modify_global()

# Verify the modification
print("After modification, global_var is:", global_var)

```

***

## **Data Types**

* Variables can store data of different types, and different types can do different things.
* Python has the following data types built-in by default, in below categories:

| Text Type:      | str                          |
| --------------- | ---------------------------- |
| Numeric Types:  | int, float,complex           |
| Sequence Types: | list, tuple, range           |
| Mapping Type:   | dict                         |
| Set Types:      | set, frozenset               |
| Boolean Type:   | bool                         |
| Binary Types:   | bytes, bytearray, memoryview |
| None Type:      | NoneType                     |

| Example                                      | Data Type  |
| -------------------------------------------- | ---------- |
| x = "Hello World"                            | str        |
| x = 20                                       | int        |
| x = 20.5                                     | float      |
| x = 1j, 1j+5                                 | complex    |
| x = \["apple", "banana", "cherry"]           | list       |
| x = ("apple", "banana", "cherry")            | tuple      |
| x = range(6)                                 | range      |
| x = {"name" : "John", "age" : 36}            | dict       |
| x = {"apple", "banana", "cherry"}            | set        |
| x = frozenset({"apple", "banana", "cherry"}) | frozenset  |
| x = True                                     | bool       |
| x = b"Hello"                                 | bytes      |
| x = bytearray(5)                             | bytearray  |
| x = memoryview(bytes(5))                     | memoryview |
| x = None                                     | NoneType   |
| Getting the datatype                         |            |

```python
x = 5
print(type(x))

```

***

## Numbers

There are three numeric types in Python:

* `int`
* `float`
* `complex`

```python
x = 1      # int
y = 2.8    # float
z = 3+5j   # complex

```

### Print Random Number in the Given range

```python
import random
print(random.randrange(1, 10))

```

***

## Strings and Operations on them.

#### Creating Strings

Strings in Python can be created using either single quotes (`'`) or double quotes (`"`). Both methods are equivalent.

```python
string1 = "Hello"
string2 = 'World'

```

#### Concatenation

Strings can be concatenated using the `+` operator.

```python
string3 = string1 + " " + string2

```

#### Getting String Length

The `len()` function is used to get the length of a string.

```python
length = len(string3)

```

#### Accessing Characters

Strings can be indexed like arrays to access individual characters.

```python
name = "jeevan"
first_char = name[0]  # returns 'j'
last_char = name[-1]  # returns 'n'

```

#### Slicing

Slicing allows you to extract a substring from a string.

```python
name = "HelloWorld"

substring = name[6:11]  # substring = "World"
substring = name[:11]   # substring = "HelloWorld"
substring = name[6:]    # substring = "World"
substring = name[-5:-1] # substring = "Worl"

```

#### String Repetition

Strings can be repeated using the `*` operator.

```python
repeated_string = string1 * 3  # Repeats the string three times
print(repeated_string )        # HelloHelloHello

```

#### Checking Substrings

You can check if a substring is present in a string using the `in` or `not in` operators.

```python
text = "hello, can you book a ticket ?"
contains_hello = "Hello" in text
contains_hello = "Hello" not in text

```

#### String Interpolation

String interpolation allows you to embed variables within strings for dynamic content.

```python
name = "jeevan"
age = 24
formatted_string = f"My name is {name} and I'm {age} years old."

```

#### Padding

Strings can be padded with spaces or other characters using `rjust()`, `ljust()`, or `center()` methods.

```python
text = "Python"

right_aligned_text = text.rjust(10)
print(right_aligned_text)             # Output: '    Python'

left_aligned_text = text.ljust(10, '-')
print(left_aligned_text)              # Output: 'Python----'

centered_text = text.center(10, '.')
print(centered_text)                  # Output: '..Python..'

```

#### Trimming

Leading and trailing whitespace can be removed using the `strip()` method.

```python
trimmed_string = "   spaces   ".strip()   # trimmed_string = "spaces"

```

#### Split

```python
# The split() method divides a string into substrings based on a delimiter.
# In this example, we're splitting the string based on the comma (',') character.
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']

```

#### Case Conversion

Strings can be converted to uppercase or lowercase using `upper()` and `lower()` methods respectively.

```python
uppercase_string = string1.upper()
lowercase_string = string1.lower()

```

#### Capitalizing First Letter

The `capitalize()` method capitalizes the first letter of a string.

```python
capitalized_string = concatenated_string.capitalize()

```

These are some of the fundamental operations and methods used for string manipulation in Python. They allow for versatile handling of textual data.

#### Modify string

The `replace()` method replaces a string with another string:

```python
a = "Hello, World!"
print(a.replace("H", "J"))

```

Refer below page for more details on string methods

[Python - String Methods](https://www.w3schools.com/python/python_strings_methods.asp)

***

### Booleans

Booleans represent one of two values: `True` or `False`. Conditionals return Booleans

Below things always return False

```python
# True and False values
is_raining = True
is_sunny = False
--------------------------------------------------------------------------
# Evaluating conditions
temperature = 25
is_warm = temperature > 20  # Evaluates to True
--------------------------------------------------------------------------
# Conditional statements
if is_raining:
    print("Bring an umbrella")
else:
    print("Leave the umbrella at home")
--------------------------------------------------------------------------
# Logical operators: and, or, not
# Using logical operators to combine conditions
is_weekend = True
is_workday = not is_weekend

# Combining conditions with logical operators
if is_sunny and is_warm:
    print("It's a great day for outdoor activities!")
elif is_sunny and not is_warm:
    print("It's sunny but a bit chilly.")
elif not is_sunny and is_warm:
    print("It's not sunny but warm.")
else:
    print("It's neither sunny nor warm. Stay indoors.")
--------------------------------------------------------------------------
# Boolean values of different data types
# Below things always evaluate to False

bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})
--------------------------------------------------------------------------
#Check the Type
x = 200
	print(isinstance(x, int))

```

***

### Operators

```python
# Arithmetic operators
num1 = 10
num2 = 5

addition = num1 + num2
subtraction = num1 - num2
multiplication = num1 * num2
division = num1 / num2
floor_division = num1 // num2
modulo = num1 % num2
exponentiation = num1 ** num2
----------------------------------------------------------------------------
# Comparison operators
equal_to = num1 == num2
not_equal_to = num1 != num2
greater_than = num1 > num2
less_than = num1 < num2
greater_than_or_equal_to = num1 >= num2
less_than_or_equal_to = num1 <= num2
----------------------------------------------------------------------------
# Logical operators
logical_and = (num1 > 0) and (num2 > 0)
logical_or = (num1 > 0) or (num2 > 0)
logical_not = not (num1 > 0)
----------------------------------------------------------------------------
# Assignment operators
result = 0
result += 5  # equivalent to result = result + 5
result -= 3  # equivalent to result = result - 3
result *= 2  # equivalent to result = result * 2
result /= 4  # equivalent to result = result / 4
result %= 2  # equivalent to result = result % 2
result **= 3  # equivalent to result = result ** 3
----------------------------------------------------------------------------
# Bitwise operators
bitwise_and = num1 & num2
bitwise_or = num1 | num2
bitwise_xor = num1 ^ num2
bitwise_not_num1 = ~num1
left_shift = num1 << 2
right_shift = num1 >> 1
----------------------------------------------------------------------------
# Identity operators[T/F]
is_equal = num1 is num2
is_not_equal = num1 is not num2
----------------------------------------------------------------------------
# Membership operators[T/F]
list_example = [1, 2, 3, 4, 5]
in_list = 3 in list_example
not_in_list = 6 not in list_example

```

***

## Sequence Types (list,tuple,set,dict)

#### 1. List data type \[ordered, changeable, Allows duplicate]

```python
# Creating a list
lis_T=[]      #empty list creation
my_list = [1, 4, 2, 8, 5]
my_list = [1,]
----------------------------------------------------------------------------
# Accessing elements,indexable
first_element = my_list[0]
last_element = my_list[-1]    #negative way
----------------------------------------------------------------------------
# Slicing
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
subset1 = my_list[2:6]  # Returns elements at index 2, 3, 4, 5
subset2 = my_list[:6]   # Returns elements from the beginning to index 5
subset3 = my_list[6:]   # Returns elements from index 6 to the end
subset4 = my_list[-5:-1]  # Returns elements from the 5th to the 2nd last
----------------------------------------------------------------------------
# Modifying elements in list with index no.
my_list[2] = 10
----------------------------------------------------------------------------
# Adding elements
my_list.append(6)  # Adds 6 at the end
my_list.insert(2, 7)  # Inserts 7 at index 2
----------------------------------------------------------------------------
# Extending a list
another_list = [8, 9, 10]
my_list.extend(another_list)
----------------------------------------------------------------------------
# deleting,removeing,clearing items in list
# Deleting elements
del my_list[2]  # Deletes the element at index 2

# Removing elements
removed_element = my_list.pop(3)  # Removes and returns element at index 3
my_list.remove(9)  # Removes the first occurrence of 9

# Clearing the list
my_list.clear()
----------------------------------------------------------------------------
# Sorting the list
my_list.sort()  # Sorts the list in ascending order
my_list.sort(reverse=True) # sort in decending order
----------------------------------------------------------------------------
# List operations
sum_of_list = sum(my_list)
length_of_list = len(my_list)
max_value = max(my_list)
min_value = min(my_list)
----------------------------------------------------------------------------
# List comprehension
squared_numbers = [x**2 for x in my_list]
----------------------------------------------------------------------------
# Checking membership
is_present = 3 in my_list
not_present = 7 not in my_list
----------------------------------------------------------------------------
# Count occurrences
	count_of_2 = my_list.count(2)
----------------------------------------------------------------------------
# Other list methods
index_of_5 = my_list.index(5)  # retrurnsindex of the first occurrence of 5
my_list.reverse()              # Reverses the elements of the list in place
copied_list = my_list.copy()   # Creates a shallow copy of the list

```

***

#### 2. Tuples data type \[ordered, unchangeable, Allows duplicate]

```python
# Creating tuples

empty_tuple = ()  # Creates an empty tuple
my_tuple = (1, 2, 3, 'a', 'b', 'c')  # Creates a tuple with elements
single_element_tuple = (42,)  # Creates a tuple with a single element

----------------------------------------------------------------------------
# Accessing elements

first_element = my_tuple[0]  # Accesses the first element
last_element = my_tuple[-1]  # Accesses the last element
subset = my_tuple[1:4]  # Slices the tuple to get a subset of elements
----------------------------------------------------------------------------
# Updating tuples
# Since tuples are immutable, we can't change their elements directly.
# However, we can update a tuple by converting it to a list, modifying it, and then converting it back to a tuple.

x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)  # Updates the tuple by replacing the second element with 'kiwi'

# Creating a new tuple with updated item

thistuple = ("apple", "banana", "cherry")
y = ("orange",)
thistuple += y  # Concatenates thistuple and y to create a new tuple
----------------------------------------------------------------------------
# Tuple operations

length = len(my_tuple)  # Calculates the length of the tuple
concatenated_tuple = my_tuple + (4, 5, 6)  # Concatenates two tuples
repeated_tuple = my_tuple * 2  # Repeats the tuple twice
----------------------------------------------------------------------------
# Tuple methods

count_of_2 = my_tuple.count(2)  # Counts the occurrences of a specified value
index_of_a = my_tuple.index('a')  # Returns the index of the first occurrence of a specified value
----------------------------------------------------------------------------
# Unpacking a tuple

a, b, c = my_tuple[:3]  # Unpacks the first three elements of the tuple into variables a, b, and c
# Example:
# a = 1, b = 2, c = 3

```

***

#### 3. Set data type \[unordered, unchangeable\*, unindexed, No duplicate]

```python
# Creating sets
empty_set = set()                   # Creates an empty set
my_set = {1, 2, 3, 'a', 'b', 'c'}   # Creates a set with elements
list_to_set = set([1, 2, 3, 2, 1])  # Converts a list to a set, removing duplicates
----------------------------------------------------------------------------
# Basic operations
my_set.add(4)         # Adds an element to the set
my_set.remove('a')    # Removes a specified element from the set, raises KeyError if the element is not present
my_set.discard('z')   # Removes a specified element from the set if it is present, does nothing otherwise
my_set.clear()        # Removes all elements from the set

# Example:
# my_set = {1, 2, 3, 'b', 'c'}
----------------------------------------------------------------------------
# Set operations
set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Returns a new set containing all unique elements from both sets
union_set = set1.union(set2)
# Returns a new set containing common elements from both sets
intersection_set = set1.intersection(set2)
difference_set = set1.difference(set2)
# Returns a new set containing elements that are in either of the sets, but not in both
symmetric_difference_set = set1.symmetric_difference(set2)
--------------------------------------------------------------------------
# Additional set methods
subset_check = set1.issubset(set2)  # Checks if set1 is a subset of set2
superset_check = set1.issuperset(set2)  # Checks if set1 is a superset of set2
disjoint_check = set1.isdisjoint(set2)  # Checks if set1 has no common elements with set2

# Example outputs for above :

# union_set = {1, 2, 3, 4, 5}
# intersection_set = {3}
# difference_set = {1, 2}
# symmetric_difference_set = {1, 2, 4, 5}
# subset_check = False
# superset_check = False
# disjoint_check = False

```

!\[\[Pasted image 20240329115152.png]]

***

#### 4. Dictionary\[ordered\*\* and changeable No duplicates allowed]

```python
# Creating dictionaries
empty_dict = {}               # Creates an empty dictionary
my_dict = {'name': 'jeevan', 'age': 24, 'city': 'palamaner'} # key-value pairs
----------------------------------------------------------------------------
# Accessing and modifying elements
name_value = my_dict['name']  # Accesses the value with the 'name' key
my_dict['age'] = 26  # Modifies the value associated with the 'age' key

# Adding new key-value pair to dictionary
my_dict['occupation'] = 'cybersec'  # Adds a new key-value pair to the dictionary

# Example:
# my_dict = {'name': 'jeevan', 'age': 26, 'city': 'palamaner', 'occupation': 'cybersec'}

----------------------------------------------------------------------------
# Removing elements
removed_value = my_dict.pop('city', None)  # Removes the 'city' key and returns its value, or returns None if key not found

----------------------------------------------------------------------------
# Checking membership
is_name_present = 'name' in my_dict  # Checks if 'name' key is present in the dictionary
is_height_present = 'height' in my_dict  # Checks if 'height' key is present in the dictionary
----------------------------------------------------------------------------
# Dictionary methods
keys_list = list(my_dict.keys())  # Returns a list of all keys in the dictionary
values_list = list(my_dict.values())  # Returns a list of all values in the dictionary
items_list = list(my_dict.items())  # Returns a list of all key-value pairs in the dictionary
----------------------------------------------------------------------------
# Iterating through a dictionary
for key, value in my_dict.items():
    print(f"{key}: {value}")  # Prints each key-value pair in the dictionary

# Dictionary comprehension
squared_values = {key: value**2 for key, value in my_dict.items() if isinstance(value, int)}
# Generates a new dictionary where the values are squared for keys with integer values

# Example:
# squared_values = {'age': 676}

```

***

## If, while and for

```python
# Conditional statements (if)
x = 10
y = 20
----------------------------------------------------------------------------
if x < y:
    print("x is less than y")
elif x > y:
    print("x is greater than y")
else:
    print("x is equal to y")
----------------------------------------------------------------------------
# While loop
counter = 0
while counter < 5:
    print(f"Counter value: {counter}")
    counter += 1
----------------------------------------------------------------------------
# For loop (with range)
for i in range(5):
    print(f"Value of i: {i}")

# For loop (iterating through a list)
fruits = ['apple', 'banana', 'orange']
for fruit in fruits:
    print(f"Current fruit: {fruit}")

# For loop (iterating through a dictionary)
person = {'name': 'John', 'age': 25, 'city': 'New York'}
for key, value in person.items():
    print(f"{key}: {value}")
----------------------------------------------------------------------------
# Break and Continue in a loop
for i in range(10):
    if i == 5:
        break  # Exit the loop when i is 5
    if i % 2 == 0:
        continue  # Skip even numbers
    print(f"Value of i: {i}")

```

***

## Functions in python

```python
# Function definition
def greet(name):
    """This function greets the person passed in as a parameter."""
    print(f"Hello, {name}!")
----------------------------------------------------------------------------
# Function with default parameter
def add_numbers(x, y=0):
    """Adds two numbers."""
    return x + y
----------------------------------------------------------------------------

# Function with return statement
def square(x):
    """Returns the square of a number."""
    return x ** 2
----------------------------------------------------------------------------
# Function with global and local scope
global_var = 10

def my_function():
    local_var = 5
    print(f"Global variable + Local variable: {global_var + local_var}")

# Function with keyword arguments
def person_info(name, age, city="Unknown"):
    print(f"Name: {name}, Age: {age}, City: {city}")
----------------------------------------------------------------------------
# Function with *args and **kwargs
"""
- *args: Accepts any number of positional arguments as a tuple.
- **kwargs: Accepts any number of keyword arguments as a dictionary.
ex:-
print_args(1, 2, 3, name="Alice", age=30)
"""

def print_args(*args, **kwargs):
    for arg in args:
        print(arg)
    for key, value in kwargs.items():
        print(f"{key}: {value}")
print_args(1, 2, 3, name="Alice", age=30)
----------------------------------------------------------------------------
# Lambda function
'''
A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have one expression.'''

multiply = lambda x, y: x * y
print(multiply(5,6))
----------------------------------------------------------------------------
# Recursive function - function that calls itself
def factorial(n):
    if n == 0 or n == 1:
        return 1
    else:
        return n * factorial(n - 1)

```

***

## Arrays In python

Arrays are used to store multiple values in one single variable:

```python
cars = ["Ford", "Volvo", "BMW"]

```

#### Access

```python
x = cars[0]

```

#### Modify

```python
cars[0] = "Toyota"

```

#### Get Length

```python
x = len(cars)

```

#### Looping Array Elements

```python
for x in cars:
  print(x)

```

#### Adding Array Elements

```python
cars.append("Honda")

```

#### Removing Array Elements

```python
cars.pop(1)
cars.remove("Volvo")

```

***

## Python modules ?

* Consider a module to be the same as a code library.
* A file containing a set of functions you want to include in your code/application.

### Creating our own modules and accessing it ?

```python
# filename - module_example.py

# Creating a module with functions and variables
def greet(name):
    print(f"Hello, {name}!")

def add(x, y):
    return x + y
----------------------------------------------------------------------------
# Executing module as a script
if __name__ == "__main__":
    print("Executing module as a script:")
    greet("World")
    result = add(5, 3)
    print("Result of addition:", result)
----------------------------------------------------------------------------
# Importing the module in another script
import module_example as mod

mod.greet("Alice")
result = mod.add(8, 2)
print("Result of addition:", result)
----------------------------------------------------------------------------
# Importing specific items from the module
from module_example import greet as custom_greet

custom_greet("Bob")
----------------------------------------------------------------------------
# Renaming the imported module
import module_example as m

m.greet("Charlie")
----------------------------------------------------------------------------
# Using standard library modules
import math

sqrt_result = math.sqrt(25)
print("Square root result:", sqrt_result)
----------------------------------------------------------------------------
# Creating a package with modules
# mypackage/__init__.py (can be empty)
# mypackage/module1.py
def func1():
    print("Function 1 in module1")

# mypackage/module2.py
def func2():
    print("Function 2 in module2")
----------------------------------------------------------------------------
# Using the package and modules
from mypackage import module1, module2

module1.func1()
module2.func2()

```

### Datetime module

```python
import datetime
x=datetime.datetime.now()
print(x)
print(x.year)
print(x.strftime("%A"))

```

### Math module

```python
import math

# Constants in math module
pi_value = math.pi
e_value = math.e

print(f"Value of pi: {pi_value}")
print(f"Value of e: {e_value}")
----------------------------------------------------------------------------
# Basic math operations
x = 4
y = 2

# Square root
sqrt_result = math.sqrt(x)
print(f"Square root of {x}: {sqrt_result}")
----------------------------------------------------------------------------
# Exponential (e ** x)
exp_result = math.exp(x)
print(f"e raised to the power {x}: {exp_result}")
----------------------------------------------------------------------------
# Logarithms
log_result_base_10 = math.log10(x)
log_result_base_e = math.log(x)  # Natural logarithm (base e)
print(f"Log base 10 of {x}: {log_result_base_10}")
print(f"Natural logarithm of {x}: {log_result_base_e}")
----------------------------------------------------------------------------
# Trigonometric functions (input in radians)
angle_in_radians = math.radians(30)
sin_result = math.sin(angle_in_radians)
cos_result = math.cos(angle_in_radians)
tan_result = math.tan(angle_in_radians)
----------------------------------------------------------------------------
# Degrees to radians and vice versa
angle_in_degrees = 45
angle_in_radians = math.radians(angle_in_degrees)
converted_degrees = math.degrees(angle_in_radians)

print(f"{angle_in_degrees} degrees in radians: {angle_in_radians}")
print(f"{angle_in_radians} radians in degrees: {converted_degrees}")
----------------------------------------------------------------------------
# Other mathematical functions
# Power
pow_result = math.pow(2, 3)
print(f"2 raised to the power 3: {pow_result}")

# Absolute Value
abs_value = math.fabs(-10)
print(f"Absolute value of -10: {abs_value}")

# Ceiling and Floor
ceil_result = math.ceil(4.3)
floor_result = math.floor(4.9)
print(f"Ceiling of 4.3: {ceil_result}")
print(f"Floor of 4.9: {floor_result}")

# Finding minimum and maximum of a sequence
numbers = [2, 5, 1, 8, 3]
min_value = min(numbers)
max_value = max(numbers)
print(f"Minimum value: {min_value}")
print(f"Maximum value: {max_value}")

```

### Base64 module

```python
import base64

# String to be encoded
original_string = "Hello, World!"
----------------------------------------------------------------------------
# Encoding the string
encoded_bytes = base64.b64encode(original_string.encode('utf-8'))
encoded_string = encoded_bytes.decode('utf-8')

print("Original String:", original_string)
print("Encoded String:", encoded_string)
----------------------------------------------------------------------------
# Decoding the string
encoded_string = "SGVsbG8sIFdvcmxkIQ=="
decoded_bytes = base64.b64decode(encoded_string)
decoded_string = decoded_bytes.decode('utf-8')

print("Encoded String:", encoded_string)
print("Decoded String:", decoded_string)

```

### Json module

JSON is a syntax for storing and exchanging data.

JSON is text, written with JavaScript object notation.

```python
import json

# Creating a Python dictionary
person_info = {
    "name": "John Doe",
    "age": 30,
    "city": "New York",
    "is_student": False,
    "grades": [95, 87, 92]
}
----------------------------------------------------------------------------
# Convert Python dictionary to JSON string
json_data = json.dumps(person_info, indent=2)  # indent for pretty printing

print("Original Python Dictionary:")
print(person_info)

print("\\\\\\\\nJSON String:")
print(json_data)
----------------------------------------------------------------------------
# Save JSON string to a file
with open("person_info.json", "w") as json_file:
    json.dump(person_info, json_file, indent=2)
----------------------------------------------------------------------------
# Read JSON from a file
with open("person_info.json", "r") as json_file:
    loaded_data = json.load(json_file)

print("\\\\\\\\nLoaded Data from JSON File:")
print(loaded_data)

```

***

## Exception handling in Python

Exception handling in Python allows you to handle errors gracefully, preventing your program from crashing when unexpected situations occur. Python provides a mechanism to catch and deal with exceptions using `try`, `except`, `else`, and `finally` blocks.

#### 1. `try` block:

* The `try` block is used to enclose the code that might raise an exception.
* It is the block where you anticipate potential errors.

#### 2. `except` block:

* The `except` block catches and handles exceptions raised in the corresponding `try` block.
* You can have multiple `except` blocks to handle different types of exceptions.
* If an exception occurs in the `try` block, Python looks for an appropriate `except` block to handle it.

#### 3. `else` block (optional):

* The `else` block is executed if no exceptions are raised in the `try` block.
* It is often used to perform actions that should only occur if the code in the `try` block runs successfully.

#### 4. `finally` block (optional):

* The `finally` block is always executed, whether an exception occurred or not.
* It is typically used to perform cleanup operations, such as closing files or releasing resources.

#### Syntax

```python
try:
    # Code that might raise an exception
except ExceptionType1:
    # Handling specific type of exception
except ExceptionType2:
    # Handling another specific type of exception
else:
    # Code to be executed if no exception occurred
finally:
    # Cleanup code (always executed)

```

#### Ex:-

```python
try:
    num = int(input("Enter a number: "))
    result = 10 / num
except ValueError:
    print("Please enter a valid number.")
except ZeroDivisionError:
    print("Cannot divide by zero.")
else:
    print("Division result:", result)
finally:
    print("End of the program.")

```

#### Custom Error

```python
# Define a custom exception class
class CustomError(Exception):
    def __init__(self, message, error_code):
        super().__init__(message)
        self.error_code = error_code

# Function that raises a custom exception
def process_data(data):
    if not data:
        raise CustomError("No data provided", 404)

# Example of using the custom exception
try:
    data = []  # Sample data
    process_data(data)
except CustomError as e:
    print("Custom error occurred:", e)
    print("Error Code:", e.error_code)
else:
    print("Data processing successful.")
finally:
    print("End of program.")

```

### Built-in error Types

Below are the Built-in error Types that we can add in `except` statement

1. **`Exception`**: The base class for all built-in exceptions. You can use it to catch any exception.
2. **`SyntaxError`**: Raised when there is a syntax error in the code.
3. **`IndentationError`**: Raised when indentation is incorrect.
4. **`NameError`**: Raised when a local or global name is not found.
5. **`TypeError`**: Raised when an operation or function is applied to an object of inappropriate type.
6. **`ValueError`**: Raised when a function receives an argument of the correct type but with an inappropriate value.
7. **`ZeroDivisionError`**: Raised when the second argument of a division or modulo operation is zero.
8. **`IndexError`**: Raised when a sequence subscript is out of range.
9. **`KeyError`**: Raised when a dictionary key is not found.
10. **`FileNotFoundError`**: Raised when a file or directory is requested but cannot be found.
11. **`IOError`**: Raised when an I/O operation (such as opening or reading a file) fails for an I/O-related reason.
12. **`OSError`**: Raised for operating system-related errors.
13. **`ImportError`**: Raised when an import statement fails to find the module definition.
14. **`ModuleNotFoundError`**: Raised when a module could not be found.
15. **`AttributeError`**: Raised when an attribute reference or assignment fails.
16. **`RuntimeError`**: Raised when an error occurs that does not belong to any specific category.
17. **`KeyboardInterrupt`**: Raised when the user interrupts the execution of the program, usually by pressing Ctrl+C.
18. **`AssertionError`**: Raised when an `assert` statement fails.
19. **`ArithmeticError`**: Base class for arithmetic errors like `OverflowError`, `ZeroDivisionError`, etc.
20. **`LookupError`**: Base class for lookup errors like `IndexError` and `KeyError`.
21. **`EnvironmentError`**: Base class for exceptions that are raised for errors related to the environment (e.g., `IOError`, `OSError`).
22. **`NotImplementedError`**: Raised when an abstract method that needs to be implemented in a derived class is not actually implemented.
23. **`EOFError`**: Raised when the `input()` function hits an end-of-file condition without reading any data.
24. **`StopIteration`**: Raised by built-in functions like `next()` to signal that there are no further items to be returned by an iterator. <https://docs.python.org/3/library/exceptions.html>

***

## File Handling in Python

File handling in Python allows you to work with files on your computer. Python provides several built-in functions and modules to manipulate files. File handling consists of various operations such as

* Opening files,
* Reading from them,
* Writing to them, and
* Closing them. Additionally, Python offers advanced file handling techniques like working with file modes, context managers, and file system operations.

#### File Modes:

* **Read Mode ("r")**: Opens the file for reading (default mode).
* **Write Mode ("w")**: Opens the file for writing. If the file doesn't exist, it creates a new file; if it exists, it truncates the file.
* **Append Mode ("a")**: Opens the file for appending. The data will be added to the end of the file.
* **Binary Mode ("b")**: Opens the file in binary mode.
* **Text Mode ("t")**: Opens the file in text mode (default mode).

#### Context Managers(short and proper way to open files ):

Python's `with` statement ensures proper acquisition and release of resources. It's commonly used with file handling to automatically close files after usage.

```python
# when used 'with' statement,python automatically closes the file,no need to specify the file.close() statement

with open("example.txt", "r") as file:
content = file.read()
print(content)

```

#### Basic File Operations:

#### 1. Opening a File:

To open a file, you use the `open()` function, specifying the file path and the mode in which you want to open the file.

```python
# Use raw string literals (prefixing the string with `r`) to avoid escaping special characters.
file = open(r"example.txt", "r")  # Opens the file in read mode

```

#### 2. Reading from a File, No changes made:

You can read the contents of a file using methods like `read()`, `readline()`, or `readlines()`.

```python
# Example of reading from a file using the read() method
with open("example.txt", "r") as file:
    content1 = file.read()
	line = file.readline()
	lines = file.readlines() # reads all lines into list (try on own)
    print(content) # Reads the entire content of the file
	print(line)    # Reads single line from the file using readline()
	print(lines)   # Reads & gives a list where each line as a list element.
	file.close()   # clear the memory after using the file

```

#### 3. Writing to a File:

To write data to a file, you open it in write mode ("w") or append mode ("a") and then use methods like `write()`.

```python
with open("example.txt", "w") as file:
file.write("Hello, World!")

```

#### 4. Closing a File:

It's important to close the file after performing operations to free up system resources.

```python
file.close()

```

### Advanced File operations in python

#### File System Operations:

Python's `os` module provides functions for interacting with the file system, such as creating, deleting, and renaming files or directories.

```python
import os

# Creating a Directory
directory = "new_directory_name"
os.mkdir(directory)

# Creating a File and wrting a string to it.
file_path = os.path.join(directory, "new_file.txt")
with open(file_path, "w") as file:
    file.write("This is a new file.")
----------------------------------------------------------------------------
# Deleting a File
file_to_delete = "file_to_delete.txt"
os.remove(file_to_delete)

# Deleting a Directory (if empty)
directory_to_delete = "directory_to_delete"
os.rmdir(directory_to_delete)
----------------------------------------------------------------------------
# Renaming a File
current_name = "old_file.txt"
new_name = "new_file.txt"
os.rename(current_name, new_name)

# Renaming a Directory
current_directory_name = "old_directory"
new_directory_name = "new_directory"
os.rename(current_directory_name, new_directory_name)

```

#### File Pointer / File seek():

The file pointer indicates the current position in the file. After reading or writing, the file pointer moves to the end of the data. You can use `seek()` to change the file pointer's position.

#### 1. Moving the File Pointer to the Beginning:

**Use Case**: When you need to read the first line of the file after reading its entire content.

```python
with open("example.txt", "r") as file:
	content = file.read()  # Read the entire content
	file.seek(0)  # Move the file pointer to the beginning
	first_line = file.readline()  # Read the first line
	print(first_line)

```

#### 2. Moving the File Pointer to a Specific Position:

**Use Case**: When you need to read a specific portion of the file, starting from a certain byte offset.

* We open the file "example.txt" in read mode (`"r"`).
* Using `file.seek(50)`, we move the file pointer to the 50th byte in the file.
* Then, `file.read(100)` reads 100 bytes from the current position, starting from the 50th byte.
* Finally, we print the partial content read from the file.

```python
with open("example.txt", "r") as file:
	file.seek(50)  # Move the file pointer to the 50th byte
	partial_content = file.read(100)  # Read 100 bytes from the current position
	print(partial_content)

```

#### 3. Moving the File Pointer Relative to Current Position:

**Use Case**: When you need to skip a certain number of bytes or characters from the current position and then read data.

```python
with open("example.txt", "r") as file:
	line = file.readline()  # Read the first line
	file.seek(10, 1)  # Move the file pointer 10 bytes ahead from the current position
	partial_content = file.read(20)  # Read 20 bytes from the current position
	print(partial_content)

```

#### 4. Moving the File Pointer Relative to End of File:

**Use Case**: When you need to read a portion of the file starting from a specific position relative to the end of the file.

```python
with open("example.txt", "r") as file:
	# Move the file pointer 100 bytes before the end of file
	file.seek(-100, 2)
	# Read from the current position till the end
	partial_content = file.read()
	print(partial_content)

```

#### Exception Handling in File Handling:

When working with files, it's essential to handle exceptions that may occur, such as file not found errors or permission errors.

```python
try:
	file = open("example.txt", "r")     # Perform file operations
except FileNotFoundError:
	print("File not found.")
except PermissionError:
	print("Permission denied.")
finally:
	file.close()  # Ensure file is closed, even if an exception occurs`

```

#### File Permission OS level

```python
import os
# Change permissions of a file to read-only for all users
os.chmod("example.txt", 0o444)

# Change owner of a file,user ID and group ID
os.chown("example.txt", uid, gid)

# Set the current process's user ID to 1000
os.setuid(1000)

```

***

## PIP Usage

**Pip** is the package installer for Python. It's a tool that allows you to install, manage, and uninstall Python packages from the Python Package Index (PyPI) and other package indexes.

#### 1. Installing Pip:

* Pip usually comes pre-installed with Python versions 3.4 and above.
* For older Python versions or to upgrade Pip, you can use the following command:

```python
     python -m ensurepip --upgrade

```

#### 2. Basic Usage:

* **Installing Packages**: You can install a package using the `pip install` command:

  ```python
  pip install package_name

  ```
* **Listing Installed Packages**: You can list all installed packages using:

  ```python
  pip list

  ```
* **Uninstalling Packages**: To uninstall a package, use:

  ```python
  pip uninstall package_name

  ```

#### 3. Installing Packages from Other Sources:

* Pip can also install packages from other sources, including version control systems like Git and Mercurial, or directly from a URL.

```python
pip install git+https://github.com/username/repository.git

```

#### 4. Specifying Package Versions:

* You can specify package versions to install using `==`, `>=`, `<=`, etc.

  ```python
  pip install package_name==1.0.0

  ```

#### 5. Requirements Files:

* You can create a requirements file (often named `requirements.txt`) listing all dependencies of your project. Then, you can install all dependencies at once using:

  ```
  requests==2.26.0
  numpy==1.21.2
  matplotlib==3.4.3

  ```

  ```python
  pip install -r requirements.txt

  ```

#### 7. Virtual Environments:

* It's recommended to use virtual environments to isolate project dependencies.
* You can create a virtual environment using:

  ```python
  python -m venv myenv

  ```
* Then, activate the virtual environment:
  * On Windows: `myenv\\\\Scripts\\\\activate`
  * On macOS and Linux: `source myenv/bin/activate`
* Install packages within the virtual environment, and they won't affect the global Python environment.

#### 8. Upgrading Pip:

* Pip can be upgraded using itself:

  ```python
  pip install --upgrade pip

  ```

#### 9. Common Pip Commands:

* `pip search package_name`: Search for a package on PyPI.
* `pip show package_name`: Display information about a specific package.
* `pip freeze`: Output all installed packages in requirements format.
* `pip check`: Verify installed packages have compatible dependencies.
* `pip wheel`: Build wheels from your requirements.

***

## Object Oriented Programming

OOPS stands for Object-Oriented Programming System, a methodology focused on designing programs using classes and objects, treating every entity as an object.

Major benefits include:

1. Reduction of code redundancy through clear and reusable code (using inheritance).
2. Enhanced visualization due to close alignment with real-world scenarios, making concepts like objects, inheritance, and abstraction easy to understand.
3. Objects represent different parts of the code with their own logic and data, simplifying code complexity and facilitating communication between components.
4. **Encapsulation**: The bundling of data (attributes) and methods that operate on the data into a single unit known as a class. Encapsulation is way to bind your data and methods together as part of Class. Encapsulation allows clients to use the exposed public methods to get the work done without knowing how it is being done. !\[\[main-qimg-d2cb0acea2d8a528020d8522407da6a1.webp]]
5. **Abstraction**: Representing essential features without including the background details. It allows programmers to focus on relevant aspects of an object and ignore non-essential details.
6. **Inheritance**: The mechanism by which one class can inherit the properties and behavior of another class. It promotes code reusability and establishes a relationship between a base class (parent) and a derived class (child).
7. **Polymorphism**: The ability of objects to take on multiple forms. In Python, this often involves using the same method name for different classes, and the appropriate method is called based on the context.

### Class vs Object vs Instance

```
* Class = blueprint(suppose an architectural drawing).
* Object is an actual thing that is built based on the ‘blueprint’ / class
* An instance is a virtual copy (but not a real copy) of the object.

```

| Aspect                                 | Object-Oriented Programming (OOP)                                                                                                                                           | Procedural Programming (C Language)                                                                                                                    |
| -------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Abstraction and Encapsulation          | Strong support through classes and objects. Allows for modeling real-world entities and hiding implementation details.                                                      | Some level of abstraction is supported, but encapsulation may be lacking. Data and functions are typically separate.                                   |
| Inheritance and Polymorphism           | Supported, promoting code reuse and flexibility. Classes can inherit properties and behaviors from other classes. Objects can be treated uniformly through polymorphism.    | Not directly supported. Code reuse is achieved through functions and libraries, but it may not be as structured or intuitive.                          |
| Code Reusability and Modularity        | Promotes code reusability and modularity through classes and objects. Components (classes) can be easily reused and extended without affecting other parts of the codebase. | Code reuse is possible through functions and libraries, but achieving modularity may be more challenging, especially in larger projects.               |
| Complexity and Learning Curve          | Can have a steeper learning curve due to complex concepts like inheritance, polymorphism, and object relationships.                                                         | Often considered more straightforward and easier to learn, especially for beginners.                                                                   |
| Performance                            | May introduce some overhead due to features like dynamic dispatch and runtime type information.                                                                             | Often offers better performance in terms of execution speed and memory usage, as it typically has simpler runtime environments and fewer abstractions. |
|                                        |                                                                                                                                                                             |                                                                                                                                                        |
| !\[\[Pasted image 20240326091922.png]] |                                                                                                                                                                             |                                                                                                                                                        |

#### Classes and Objects:

* Classes are blueprints for creating objects. They define properties (attributes) and behaviors (methods) of objects.
* Objects are instances of classes.

#### Create a class named MyClass, with a property named x:

```python
class MyClass:
  x = 5
# Creating an instance of the class
obj = MyClass()

```

#### Creating the object named p1 from class `Myclass`

```python
p1 = MyClass()
print(p1.x)

```

#### Attributes and Methods in class

```python
# Defining a class with attributes and methods
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def introduce(self):
        print(f"Hi, I'm {self.name} and I'm {self.age} years old.")

# Creating an object and using attributes/methods
person = Person("Alice", 25)
person.introduce()

```

#### The **init**() Function

All classes have a function called **init**(), which is always executed when the class is being initiated.

* `__init__` is a special method also known as the constructor. It's called automatically when a new instance of a class is created. This method is used to initialize the object's attributes. In the context of the `Book` class, `__init__` initializes the `title` and `author` attributes of each `Book` object.
* `self` is a reference to the instance of the class itself. It's similar to `this` in other programming languages. When we call `person1.introduce()`, the `self` parameter is implicitly passed to the `introduce` method, allowing it to access the attributes of the `person1` object via `self.name` and `self.age`.

```python
# Creating a class named Person, and using __init__() function to assign values for name and age:

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

p1 = Person("John", 36)

print(p1.name)
print(p1.age)

```

#### The **str**() Function

The **str**() function controls what should be returned when the class object is represented as a string.

Without Str()

```python
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

p1 = Person("John", 36)
print(p1)

```

Python will provide a default string representation of the object. This representation typically includes the class name and the memory address where the object is stored in memory.

```python
>>> <__main__.Person object at 0x15039e602100>

```

### **Inheritance:**

```python
# Defining the superclass
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def introduce(self):
        print(f"Hi, my name is {self.name} and I am {self.age} years old.")

# Creating a subclass that inherits from a superclass
class Student(Person):
    def __init__(self, name, age, student_id):
        super().__init__(name, age)
        self.student_id = student_id

    def introduce(self):
        print(f"Hi, my name is {self.name}, I am {self.age} years old, and my student ID is {self.student_id}.")

# Using the subclass
student = Student("Bob", 20, "S12345")
student.introduce()

```

### **Encapsulation:**

```python

# Using encapsulation to protect attributes
class BankAccount:
    def __init__(self, balance):
        self._balance = balance  # _ indicates a protected attribute

    def deposit(self, amount):
        self._balance += amount

    def get_balance(self):
        return self._balance

# Example usage
account = BankAccount(1000)
print("Initial balance:", account.get_balance())

account.deposit(500)
print("After deposit:", account.get_balance())

```

### **Polymorphism:**

* `Human` is the common interface with a method `introduce`.
* Both `Person` and `Student` inherit from `Human` and implement the `introduce` method specific to each class.
* The `introduce` function takes an object of any class implementing the `Human` interface and calls its `introduce` method, demonstrating polymorphism.

```python

class Human:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def introduce(self):
        pass

class Person(Human):
    def __init__(self, name, age):
        super().__init__(name, age)

    def introduce(self):
        print(f"Hello, I am {self.name}. I am {self.age} years old.")

class Student(Human):
    def __init__(self, name, age, student_id):
        super().__init__(name, age)
        self.student_id = student_id

    def introduce(self):
        print(f"Hello, I am {self.name}. I am {self.age} years old. My student ID is {self.student_id}.")

def introduce(obj):
    obj.introduce()

person = Person("Charlie", 22)
student = Student("David", 21, "S12345")

introduce(person)
introduce(student)

```

***

### **Example 1: Library System**

```python

class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author

class Library:
    def __init__(self):
        self.books = []

    def add_book(self, book):
        self.books.append(book)

    def display_books(self):
        for book in self.books:
            print(f"{book.title} by {book.author}")

# Usage
book1 = Book("The Great Gatsby", "F. Scott Fitzgerald")
book2 = Book("To Kill a Mockingbird", "Harper Lee")

library = Library()
library.add_book(book1)
library.add_book(book2)

library.display_books()

```

In this example, we have a **`Book`** class to represent books and a **`Library`** class that can add books and display them.

### **Example 2: Shape Hierarchy with Polymorphism**

```python

from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14 * self.radius**2

class Rectangle(Shape):
    def __init__(self, length, width):
        self.length = length
        self.width = width

    def area(self):
        return self.length * self.width

# Usage
circle = Circle(5)
rectangle = Rectangle(4, 6)

shapes = [circle, rectangle]

for shape in shapes:
    print(f"Area of {type(shape).__name__}: {shape.area()}")

```

This example demonstrates polymorphism by creating a hierarchy of shapes. The **`Shape`** class is abstract, and **`Circle`** and **`Rectangle`** are concrete classes that implement the **`area`** method.

### **Example 3: Employee Management System with Inheritance**

```python

class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    def display_info(self):
        print(f"Name: {self.name}, Salary: ${self.salary}")

class Manager(Employee):
    def __init__(self, name, salary, department):
        super().__init__(name, salary)
        self.department = department

    def display_info(self):
        super().display_info()
        print(f"Department: {self.department}")

# Usage
employee1 = Employee("Alice", 50000)
manager1 = Manager("Bob", 70000, "IT")

employees = [employee1, manager1]

for employee in employees:
    employee.display_info()

```

`super()` is a built-in function that returns a proxy object that allows you to refer parent class methods. It's typically used in cases where a subclass wants to extend or override the behavior of methods defined in its superclass.

This example showcases inheritance, where the **`Manager`** class inherits from the **`Employee`** class. Both classes have a **`display_info`** method, and the **`Manager`** class overrides it to include additional information.

### **Example 4: Zoo Management System**

```python

class Animal:
    def __init__(self, name, sound):
        self.name = name
        self.sound = sound

    def make_sound(self):
        print(f"{self.name} says {self.sound}")

class Bird(Animal):
    def fly(self):
        print(f"{self.name} is flying")

class Mammal(Animal):
    def run(self):
        print(f"{self.name} is running")

# Usage
parrot = Bird("Parrot", "Squawk")
lion = Mammal("Lion", "Roar")

parrot.make_sound()
parrot.fly()

lion.make_sound()
lion.run()

```

***

#### Python Regular Expressions (RegEx)

**Definition:**

A Regular Expression (RegEx) is a sequence of characters that defines a search pattern, allowing for sophisticated string matching and manipulation.

**Usage:**

RegEx can be utilized to validate, search, and manipulate strings based on specified patterns.

#### RegEx Module in Python:

**Importing the Module:**

```python
import re

```

**Basic RegEx Operations in Python:**

1. **Search for a Pattern:**

   ```python
   txt = "The rain in Spain"
   x = re.search("^The.*Spain$", txt)

   ```
2. **RegEx Functions:**
   * `findall()`: Returns a list containing all matches.
   * `search()`: Returns a Match object if there is a match anywhere in the string.
   * `split()`: Splits the string at each match.
   * `sub()`: Replaces one or many matches with a string.
3. **Using `findall()`:**

   ```python
   txt = "The rain in Spain"
   x = re.findall("ai", txt)

   ```
4. **Using `search()`:**

   ```python
   txt = "The rain in Spain"
   x = re.search("\\\\s", txt)

   ```
5. **Using `split()`:**

   ```python
   txt = "The rain in Spain"
   x = re.split("\\\\s", txt)

   ```
6. **Using `sub()`:**

   ```python
   txt = "The rain in Spain"
   x = re.sub("\\\\s", "9", txt)

   ```

#### Metacharacters:

* **`[]`**: A set of characters.
* **`\\\\`**: Signals a special sequence.
* **`.`**: Any character except newline.
* **`^`**: Starts with.
* **`$`**: Ends with.
* **\`\`**: Zero or more occurrences.
* **`+`**: One or more occurrences.
* **`?`**: Zero or one occurrences.
* **`{}`**: Exactly the specified number of occurrences.
* **`|`**: Either or.
* **`()`**: Capture and group.

```python
import re

# []: A set of characters.
txt1 = "The sun is shining brightly"
pattern1 = r'[sun]'
matches1 = re.findall(pattern1, txt1)
print(matches1)  # Output: ['s', 'u', 'n', 'n']

# \\\\: Signals a special sequence.
txt2 = "The rain in Spain"
pattern2 = r'\\\\b\\\\w+\\\\b'
matches2 = re.findall(pattern2, txt2)
print(matches2)  # Output: ['The', 'rain', 'in', 'Spain']

# .: Any character except newline.
txt3 = "hello world"
pattern3 = r'he..o'
match3 = re.search(pattern3, txt3)
print(match3.group())  # Output: hello

# ^: Starts with.
txt4 = "hello world"
pattern4 = r'^hello'
match4 = re.search(pattern4, txt4)
print(match4.group())  # Output: hello

# $: Ends with.
txt5 = "hello world"
pattern5 = r'world$'
match5 = re.search(pattern5, txt5)
print(match5.group())  # Output: world

# *: Zero or more occurrences.
txt6 = "He said heeeello!"
pattern6 = r'he*l'
matches6 = re.findall(pattern6, txt6)
print(matches6)  # Output: ['he', 'heeeel']

# +: One or more occurrences.
txt7 = "He said heeeello!"
pattern7 = r'he+l'
matches7 = re.findall(pattern7, txt7)
print(matches7)  # Output: ['heel']

# ?: Zero or one occurrences.
txt8 = "colours or colors"
pattern8 = r'colou?rs?'
matches8 = re.findall(pattern8, txt8)
print(matches8)  # Output: ['colours', 'colors']

# {}: Exactly the specified number of occurrences.
txt9 = "hellooo"
pattern9 = r'o{3}'
matches9 = re.findall(pattern9, txt9)
print(matches9)  # Output: ['ooo']

# |: Either or.
txt10 = "falls or stays"
pattern10 = r'falls|stays'
match10 = re.search(pattern10, txt10)
print(match10.group())  # Output: falls

# (): Capture and group.
txt11 = "apple banana cherry"
pattern11 = r'(apple|banana) cherry'
match11 = re.search(pattern11, txt11)
print(match11.group(1))  # Output: apple

```

#### Special Sequences:

* **`\\\\A`**: Matches if specified characters are at the beginning of the string.
* **`\\\\b`**: Matches where specified characters are at the beginning or end of a word.
* **`\\\\B`**: Matches where specified characters are present but not at the beginning or end of a word.
* **`\\\\d`**: Matches digits (0-9).
* **`\\\\D`**: Matches non-digits.
* **`\\\\s`**: Matches whitespace characters.
* **`\\\\S`**: Matches non-whitespace characters.
* **`\\\\w`**: Matches word characters (a-z, A-Z, 0-9, and \_).
* **`\\\\W`**: Matches non-word characters.
* **`\\\\Z`**: Matches if specified characters are at the end of the string.

```python
import re

# \\\\A: Matches if specified characters are at the beginning of the string.
txt1 = "The sun is shining brightly"
pattern1 = r'\\\\AThe'
match1 = re.search(pattern1, txt1)
print(match1.group())  # Output: The

# \\\\b: Matches where specified characters are at the beginning or end of a word.
txt2 = "The sun is shining brightly"
pattern2 = r'\\\\bsun\\\\b'
match2 = re.search(pattern2, txt2)
print(match2.group())  # Output: sun

# \\\\B: Matches where specified characters are present but not at the beginning or end of a word.
txt3 = "The sun is shining brightly"
pattern3 = r'\\\\Bun\\\\B'
match3 = re.search(pattern3, txt3)
print(match3.group())  # Output: un

# \\\\d: Matches digits (0-9).
txt4 = "There are 7 days in a week"
pattern4 = r'\\\\d'
matches4 = re.findall(pattern4, txt4)
print(matches4)  # Output: ['7']

# \\\\D: Matches non-digits.
txt5 = "There are 7 days in a week"
pattern5 = r'\\\\D'
matches5 = re.findall(pattern5, txt5)
print(matches5)  # Output: ['T', 'h', 'e', 'r', 'e', ' ', 'a', 'r', 'e', ' ', ' ', 'd', 'a', 'y', 's', ' ', 'i', 'n', ' ', 'a', ' ', 'w', 'e', 'e', 'k']

# \\\\s: Matches whitespace characters.
txt6 = "The sun is shining brightly"
pattern6 = r'\\\\s'
matches6 = re.findall(pattern6, txt6)
print(matches6)  # Output: [' ', ' ', ' ', ' ']

# \\\\S: Matches non-whitespace characters.
txt7 = "The sun is shining brightly"
pattern7 = r'\\\\S'
matches7 = re.findall(pattern7, txt7)
print(matches7)  # Output: ['T', 'h', 'e', 's', 'u', 'n', 'i', 's', 's', 'h', 'i', 'n', 'g', 'b', 'r', 'i', 'g', 'h', 't', 'l', 'y']

# \\\\w: Matches word characters (a-z, A-Z, 0-9, and _).
txt8 = "The sun is shining brightly"
pattern8 = r'\\\\w'
matches8 = re.findall(pattern8, txt8)
print(matches8)  # Output: ['T', 'h', 'e', 's', 'u', 'n', 'i', 's', 'i', 's', 's', 'h', 'i', 'n', 'g', 'b', 'r', 'i', 'g', 'h', 't', 'l', 'y']

# \\\\W: Matches non-word characters.
txt9 = "The sun is shining brightly"
pattern9 = r'\\\\W'
matches9 = re.findall(pattern9, txt9)
print(matches9)  # Output: [' ', ' ', ' ', ' ']

# \\\\Z: Matches if specified characters are at the end of the string.
txt10 = "The sun is shining brightly"
pattern10 = r'ly\\\\Z'
match10 = re.search(pattern10, txt10)
print(match10.group())  # Output: ly

```

#### Sets:

* **`[arn]`**: Matches one of the specified characters (a, r, or n).
* **`[a-n]`**: Matches any lowercase character alphabetically between a and n.
* **`[^arn]`**: Matches any character except specified ones.
* **`[0-9]`**: Matches any digit between 0 and 9.
* **`[a-zA-Z]`**: Matches any character alphabetically between a and z, lowercase or uppercase.

```python
import re

# [arn]: Matches one of the specified characters (a, r, or n).
txt1 = "The sun is shining brightly"
pattern1 = r'[arn]'
matches1 = re.findall(pattern1, txt1)
print(matches1)  # Output: ['n', 'a', 'n', 'n', 'n']

# [a-n]: Matches any lowercase character alphabetically between a and n.
txt2 = "The sun is shining brightly"
pattern2 = r'[a-n]'
matches2 = re.findall(pattern2, txt2)
print(matches2)  # Output: ['h', 'e', 'n', 'i', 'i', 'g', 'b', 'h', 'i', 'g', 'h', 't', 'l', 'y']

# [^arn]: Matches any character except specified ones.
txt3 = "The sun is shining brightly"
pattern3 = r'[^arn]'
matches3 = re.findall(pattern3, txt3)
print(matches3)  # Output: ['T', 'h', 'e', ' ', 's', 'u', ' ', 'i', 's', ' ', 's', 'h', 'i', 'i', 'g', ' ', 'b', 'r', 'i', 'g', 'h', 't', 'l', 'y']

# [0-9]: Matches any digit between 0 and 9.
txt4 = "There are 7 days in a week"
pattern4 = r'[0-9]'
matches4 = re.findall(pattern4, txt4)
print(matches4)

```

#### Match Object:

A Match Object contains information about the search and the result.

* **`.span()`:** Returns the start and end positions of the match.
* **`.string`:** Returns the string passed into the function.
* **`.group()`:** Returns the part of the string where there was a match.

**Note:** If no match is found, `None` will be returned instead of the Match Object.
