Part 2 : Learn Python for Become an AI, ML, DL Developer/Engineer’s,

Just in touch with Karthikeyan Rathinam: Linkedin, GitHub, Youtube
Object-Oriented Programming
Object-oriented programming (OOP) is a programming paradigm centered around the concept of objects, which can contain data in the form of attributes and code in the form of methods. Python supports OOP principles by allowing the creation of classes and objects.
Classes and Objects
Class Definition A class is a blueprint for creating objects. It defines attributes (data) and methods (functions) that characterize the objects.
class Dog:
# Class attribute
species = "Canine"
# Constructor method (initializer)
def __init__(self, name, age):
# Instance attributes
self.name = name
self.age = age
# Instance method
def description(self):
return f"{self.name} is {self.age} years old."
# Another instance method
def speak(self, sound):
return f"{self.name} says {sound}!"
Creating Objects (Instances)
Instantiate objects from a class:
# Creating instances of the Dog class
dog1 = Dog("Buddy", 3)
dog2 = Dog("Molly", 5)
# Accessing attributes and calling methods
print(dog1.description()) # Output: Buddy is 3 years old.
print(dog2.speak("Woof")) # Output: Molly says Woof!
Inheritance
Inheritance allows a class (child class) to inherit properties and behavior from another class (parent or base class).
# Parent class
class Animal:
def make_sound(self):
pass # Placeholder method
# Child class inheriting from Animal
class Cat(Animal):
def make_sound(self):
return "Meow"
# Creating an instance of Cat
cat = Cat()
print(cat.make_sound()) # Output: Meow
Encapsulation
Encapsulation is the bundling of data (attributes) and methods that operate on that data within a single unit, i.e., a class. It restricts direct access to some components of an object and prevents the accidental modification of data.
Example:
class Car:
def __init__(self, make, model):
self.__make = make # Private attribute
self.__model = model # Private attribute
def get_make(self):
return self.__make # Getter method to access private attribute
def set_model(self, new_model):
self.__model = new_model # Setter method to modify private attribute
In this example, make
and model
are encapsulated as private attributes, accessed and modified through getter and setter methods, respectively (get_make()
and set_model()
).
Abstraction
Abstraction focuses on hiding complex implementation details while providing a simple interface. It allows programmers to work with high-level concepts without worrying about the underlying complexities.
Example:
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass # Abstract method to calculate area
class Rectangle(Shape):
def __init__(self, length, breadth):
self.length = length
self.breadth = breadth
def area(self):
return self.length * self.breadth
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius
In this example, Shape
is an abstract class with an abstract method area()
. Rectangle
and Circle
are concrete classes implementing the area()
method. Users interact with Shape
and its subclasses without needing to know the specific implementation details.
Polymorphism
Polymorphism allows objects to be treated as instances of their parent class, enabling a single interface to represent entities of different types.
Example:
class Animal:
def make_sound(self):
pass
class Dog(Animal):
def make_sound(self):
return "Woof!"
class Cat(Animal):
def make_sound(self):
return "Meow!"
def animal_sound(animal):
return animal.make_sound()
dog = Dog()
cat = Cat()
print(animal_sound(dog)) # Output: Woof!
print(animal_sound(cat)) # Output: Meow!
Here, animal_sound()
function accepts any Animal
object and calls the make_sound()
method. This demonstrates how different subclasses (Dog
and Cat
) provide their own implementation of the method, resulting in polymorphic behavior.
Just in touch with Karthikeyan Rathinam: Linkedin, GitHub, Youtube
Regular Expressions
Regular expressions (regex) in Python are powerful tools for pattern matching within strings. The re module in Python provides support for working with regular expressions. Here are some common operations and examples:
Matching Text
import re
pattern = r"apple"
text = "I like apples and oranges."
match = re.search(pattern, text)
if match:
print("Found:", match.group())
else:
print("Pattern not found.")
Special Characters
Wildcard:
pattern = r"gr.y" # Matches 'gray', 'grey', etc.
Character Sets: []
pattern = r"[aeiou]" # Matches any vowel
Quantifiers: *, +, ?
pattern = r"ab*" # Matches 'a', 'ab', 'abb', 'abbb', etc.
Anchors and Boundaries
Start and End: ^, $
pattern = r"^Start" # Matches 'Start' at the beginning of a string
pattern = r"End$" # Matches 'End' at the end of a string
Word Boundaries: \b, \B
pattern = r"\bword\b" # Matches 'word' as a whole word
Groups and Alternation
Groups:
()
pattern = r"egg(spam)*" # Matches 'egg', 'eggspam', 'eggspamspam', etc.
Alternation: |
pattern = r"cat|dog" # Matches 'cat' or 'dog'
Using Regex for Search and Replacement
re.findall()
text = "I have 3 cats and 2 dogs."
numbers = re.findall(r'\d+', text) # Matches all sequences of digits
print(numbers) # Output: ['3', '2']
re.sub()
text = "Hello, World!"
new_text = re.sub(r"World", "Python", text)
print(new_text) # Output: Hello, Python!
Just in touch with Karthikeyan Rathinam: Linkedin, GitHub, Youtube
Working with Libraries
NumPy
NumPy is a powerful library for numerical computing in Python. It provides support for arrays, mathematical functions, linear algebra, random number generation, and much more.
Example:
import numpy as np
# Creating NumPy arrays
arr1 = np.array([1, 2, 3, 4, 5])
arr2 = np.array([[1, 2, 3], [4, 5, 6]])
# Basic array operations
print("Array 1:", arr1)
print("Array 2:\n", arr2)
print("Array 1 shape:", arr1.shape)
print("Array 2 shape:", arr2.shape)
print("Array 2 Transpose:\n", arr2.T) # Transpose of arr2
# Mathematical operations with arrays
result = arr1 * 2 # Multiply each element by 2
print("Result:", result)
Pandas
Pandas is a versatile library for data manipulation and analysis, especially for working with structured data (e.g., tables, CSV files).
Example:
import pandas as pd
#Creating a DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'San Francisco', 'Los Angeles']}
df = pd.DataFrame(data)
#Basic DataFrame operations
print(df)
print("DataFrame shape:", df.shape)
print("DataFrame columns:", df.columns)
print("DataFrame information:")
print(df.info())
#Data selection and filtering
print(df[df['Age'] > 25]) # Select rows where Age is greater than 25
Just in touch with Karthikeyan Rathinam: Linkedin, GitHub, Youtube
GUI Programming
Graphical User Interface (GUI) programming in Python enables the creation of interactive applications with buttons, menus, windows, and more. One of the commonly used GUI libraries in Python is Tkinter, which comes pre-installed with Python. Let’s cover a basic example using Tkinter:
Tkinter Example
Creating a Simple Window
import tkinter as tk
# Create the main window
root = tk.Tk()
root.title("My GUI App") # Set window title
# Add a label to the window
label = tk.Label(root, text="Hello, Tkinter!")
label.pack()
# Run the main loop
root.mainloop()
Adding Buttons and Handling Events
def on_button_click():
label.config(text="Button Clicked!")
# Create a button
button = tk.Button(root, text="Click Me", command=on_button_click)
button.pack()
# Run the main loop
root.mainloop()
Other GUI Frameworks
Apart from Tkinter, there are other popular GUI libraries for Python, such as:
- PyQt/PySide: Provides a set of Python bindings for the Qt framework. Offers a wide range of tools for creating cross-platform applications with a polished look.
- wxPython: Offers a native look and feel across platforms and provides a comprehensive set of widgets for building desktop applications.
- Kivy: Primarily used for building touch-based applications and supports multitouch.
- Tkinter with ttk: The themed widgets in the ttk module of Tkinter provide a more modern look and additional functionality compared to the standard Tkinter widgets.
Example using PyQt
Here’s a simple example using PyQt:
from PyQt5.QtWidgets import QApplication, QLabel, QPushButton, QVBoxLayout, QWidget
def on_button_click():
label.setText("Button Clicked!")
app = QApplication([])
window = QWidget()
window.setWindowTitle('My GUI App')
layout = QVBoxLayout()
label = QLabel('Hello, PyQt!')
layout.addWidget(label)
button = QPushButton('Click Me')
button.clicked.connect(on_button_click)
layout.addWidget(button)
window.setLayout(layout)
window.show()
app.exec_()
Database Access (SQL, SQLite, etc.)
Database access in Python can be accomplished using various libraries that provide interfaces to different types of databases. SQL databases like SQLite, MySQL, PostgreSQL, and others can be accessed and manipulated using these libraries.
SQLite Example
Connecting to SQLite and Executing Queries
import sqlite3
# Connect to SQLite database (creates if not exists)
conn = sqlite3.connect('example.db')
# Create a cursor object to execute SQL queries
cursor = conn.cursor()
# Create a table
cursor.execute('''CREATE TABLE IF NOT EXISTS employees
(id INTEGER PRIMARY KEY, name TEXT, age INTEGER, department TEXT)''')
# Insert data
cursor.execute("INSERT INTO employees (name, age, department) VALUES (?, ?, ?)", ('Alice', 30, 'HR'))
cursor.execute("INSERT INTO employees (name, age, department) VALUES (?, ?, ?)", ('Bob', 25, 'IT'))
# Commit changes
conn.commit()
# Fetch data
cursor.execute("SELECT * FROM employees")
data = cursor.fetchall()
for row in data:
print(row)
# Close connection
conn.close()
Using SQLAlchemy (For Various Databases)
Example with SQLAlchemy and SQLite
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# Create SQLite engine
engine = create_engine('sqlite:///example.db', echo=True)
# Create a base class for declarative class definitions
Base = declarative_base()
# Define a class that represents the table
class Employee(Base):
__tablename__ = 'employees'
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)
department = Column(String)
# Create tables in the database
Base.metadata.create_all(engine)
# Create a session
Session = sessionmaker(bind=engine)
session = Session()
# Insert data using ORM
employee1 = Employee(name='Alice', age=30, department='HR')
employee2 = Employee(name='Bob', age=25, department='IT')
session.add_all([employee1, employee2])
session.commit()
# Query data
employees = session.query(Employee).all()
for emp in employees:
print(emp.name, emp.age, emp.department)
# Close session
session.close()
Just in touch with Karthikeyan Rathinam: Linkedin, GitHub, Youtube
Web Development (using frameworks like Django or Flask)
Web development in Python is popularly facilitated by frameworks like Django and Flask. These frameworks simplify the process of creating web applications by providing tools and libraries for handling routing, templates, databases, and more.
Flask Example
Flask is a lightweight and flexible micro-framework for web development.
Setting up a Simple Web Application
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True)
Routing and Templates
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html', title='Home', content='Welcome to our website!')
if __name__ == '__main__':
app.run(debug=True)
Django Example
Django is a high-level and feature-rich framework suitable for building complex web applications.
Creating a Simple Django Application
# Create a new Django project
django-admin startproject myproject
# Create a new app inside the project
cd myproject
python manage.py startapp myapp
Configuring Routes and Views
In myapp/views.py
:
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, Django!")
In myproject/urls.py
:
from django.urls import path
from myapp import views
urlpatterns = [
path('', views.index, name='index'),
]
Just in touch with Karthikeyan Rathinam: Linkedin, GitHub, Youtube
Concurrency and Parallelism
Concurrency and parallelism are related but distinct concepts in computer science, especially in the context of executing tasks or processes.
Concurrency
Concurrency refers to the ability of a system to handle multiple tasks or processes simultaneously. In a concurrent system, tasks can start, run, and complete independently of each other. However, at any given moment, only one task is actively making progress while others may be in various states, such as waiting for I/O, sleeping, or ready to run.
Concurrency can be achieved using techniques like multitasking, multithreading, or multiprocessing.
Parallelism
Parallelism, on the other hand, involves the simultaneous execution of multiple tasks or processes to speed up computations. In a truly parallel system, multiple tasks are actively running at the same time on different processors or cores, making progress simultaneously.
Parallelism is commonly achieved in systems with multiple processors or CPU cores.
Relationship
- Concurrency without Parallelism: In some cases, a system may handle multiple tasks concurrently without truly running them simultaneously. For instance, in a single-core processor, multitasking allows tasks to run concurrently through context switching, but they are executed sequentially.
- Concurrency with Parallelism: Systems with multiple processors or cores can execute tasks concurrently and in parallel, achieving both concurrency and parallelism.
Python and Concurrency/Parallelism
- Concurrency in Python: Python offers concurrency using libraries like asyncio (for asynchronous programming), which allows handling multiple I/O-bound tasks concurrently without multiple threads.
- Parallelism in Python: For CPU-bound tasks, Python provides the multiprocessing module, which enables parallel execution by leveraging multiple CPU cores.
Testing and Debugging
Testing and debugging are crucial phases in software development to ensure the code works as expected and to identify and fix errors or bugs. Python offers various tools and techniques for testing and debugging.
Testing
Unit Testing with unittest
import unittest
def add(a, b):
return a + b
class TestAddFunction(unittest.TestCase):
def test_add(self):
self.assertEqual(add(3, 4), 7)
self.assertEqual(add(-1, 1), 0)
if __name__ == '__main__':
unittest.main()
# test_add.py
def add(a, b):
return a + b
def test_add():
assert add(3, 4) == 7
assert add(-1, 1) == 0
Debugging
Test Automation with pytest
Using pdb (Python Debugger)
import pdb
def divide(a, b):
result = a / b
return result
pdb.set_trace()
x = divide(5, 0)
print(x)
Integrated Development Environments (IDEs) IDEs like PyCharm, VSCode, or Jupyter offer built-in debugging tools with features like breakpoints, variable inspection, stepping through code, and more.
Just in touch with Karthikeyan Rathinam: Linkedin, GitHub, Youtube
Best Practices and Tips
here are some best practices and tips to enhance your Python programming experience:
Code Readability and Maintainability
Follow PEP 8: Adhering to Python Enhancement Proposal 8 ensures consistent and readable code.
Use Descriptive Names: Meaningful variable, function, and class names improve code readability.
Document Your Code: Write clear and concise comments and docstrings to explain code functionality.
Error Handling
Use Exception Handling: Wrap code that might raise exceptions in try-except blocks for graceful error handling.
Logging: Utilize the logging module to log errors and informative messages for debugging.
Performance Optimization
Profiling: Use profiling tools (cProfile, line_profiler) to identify performance bottlenecks.
Optimize Critical Sections: Employ optimized algorithms or libraries for performance-critical code sections.
Cache Results: Use caching mechanisms (functools.lru_cache) for expensive function calls.
Just in touch with Karthikeyan Rathinam: Linkedin, GitHub, Youtube
Testing and Debugging
Write Tests: Embrace unit tests (unittest, pytest) to verify code correctness and edge cases.
Debuggig Tools: Leverage debugging tools (pdb, IDE debuggers) to track and resolve issues efficiently.
Version Control and Collaboration
Use Version Control: Utilize Git or other version control systems for tracking changes and collaborating on code.
Code Reviews: Engage in code reviews to get feedback and improve code quality.
Security
Sanitize Inputs: Validate and sanitize user inputs to prevent security vulnerabilities like SQL injection or XSS attacks.
Use Secure Libraries: Employ trusted and regularly updated libraries to avoid security flaws.
Continuous Learning
Stay Updated: Keep up with Python updates, libraries, and best practices to improve skills.
Community Involvement: Participate in forums, communities, and open-source projects to learn and contribute.
Feel free to ask any query
https://github.com/karthikeyanrathinam/
https://www.linkedin.com/in/karthikeyan-rathinam/