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

Karthikeyan Rathinam
11 min readNov 29, 2023

Just in touch with Karthikeyan Rathinam: Linkedin, GitHub, Youtube

Introduction to Python

Welcome to the Introduction to Python section! In this section, we’ll cover the fundamental concepts and basics of Python programming language.

here’s a general list of topics or chapters commonly found in Python learning materials:

  • Introduction to Python
  • Variables and Data Types
  • Operators
  • Control Flow (if, else, elif, loops)
  • Functions
  • Data Structures (lists, tuples, dictionaries, sets)
  • File Handling
  • Modules and Packages
  • Exception Handling
  • Object-Oriented Programming (Classes and Objects)
  • Inheritance and Polymorphism
  • Regular Expressions
  • Working with Libraries (e.g., NumPy, Pandas)
  • GUI Programming (using Tkinter or other frameworks)
  • Database Access (SQL, SQLite, etc.)
  • Web Development (using frameworks like Django or Flask)
  • Concurrency and Parallelism
  • Testing and Debugging
  • Best Practices and Tips

What is Python?

Python is a high-level, interpreted programming language known for its simplicity and readability. It’s versatile and can be used for various applications, including web development, data analysis, artificial intelligence, and more.

Why Learn Python?

  • Readability: Python emphasizes readability and simplicity, making it easier to write and understand code.
  • Versatility: It supports multiple programming paradigms and has a vast ecosystem of libraries and frameworks.
  • Community and Support: Python has a large and active community, offering support, resources, and numerous third-party packages.

What We’ll Cover:

  1. Variables and Data Types: Understanding how to work with different data types such as integers, floats, strings, lists, tuples, dictionaries, etc.
  2. Control Flow: Learning about conditional statements (if, else, elif) and loops (for, while).
  3. Functions: Defining and using functions to encapsulate reusable pieces of code.
  4. Data Structures: Exploring built-in data structures like lists, tuples, sets, and dictionaries.
  5. File Handling: Reading from and writing to files.
  6. Modules and Packages: Organizing code into modules and using external packages.
  7. Exception Handling: Managing errors and exceptions in Python programs.

Variables and Data Types

Welcome to the Variables and Data Types section! This section will cover the essentials of working with variables and different data types in Python.

Understanding Variables

In Python, variables are used to store data values. They can hold different types of data and can be reassigned throughout the program.

Variable Declaration

Variables in Python are declared by assigning a value to them using the assignment operator (=).

Example:

# Variable declaration
x = 5
name = "Alice"

Variable Naming Rules

  • Variable names can contain letters, numbers, and underscores but cannot start with a number.
  • They are case-sensitive.
  • Python has some reserved keywords that cannot be used as variable names.

Data Types in Python

Python supports various data types, allowing flexibility in representing different kinds of data.

Common Data Types

  • Numeric Types: Integers (int), floating-point numbers (float), and complex numbers (complex).
  • Strings : Sequences of characters, defined within single, double, or triple quotes.
  • Lists: Ordered, mutable collections of elements enclosed in square brackets ([]).
  • Tuples: Similar to lists but immutable, enclosed in parentheses (()).
  • Dictionaries: Unordered collections of key-value pairs enclosed in curly braces ({}).
  • Sets: Unordered collections of unique elements enclosed in curly braces ({}).

Checking Data Types

In Python, you can use the type() function to determine the data type of a variable.

Example:

num = 10
print(type(num)) # Output: <class 'int'>

Operators

Welcome to the Operators section! This section will introduce you to different types of operators available in Python.

Arithmetic Operators

Arithmetic operators are used to perform mathematical operations in Python.

Common Arithmetic Operators:

  1. Addition (+): Adds two operands.
  2. Subtraction (-): Subtracts the second operand from the first.
  3. Multiplication (*): Multiplies two operands.
  4. Division (/): Divides the first operand by the second (results in a float value).
  5. Floor Division (//): Divides and returns the integer value of the quotient.
  6. Modulus (%): Returns the remainder of the division.
  7. Exponentiation ()**: Raises the first operand to the power of the second.

Example:

a = 10
b = 3
print(a + b) # Output: 13
print(a - b) # Output: 7
print(a * b) # Output: 30
print(a / b) # Output: 3.3333333333333335
print(a // b) # Output: 3
print(a % b) # Output: 1
print(a ** b) # Output: 1000

Comparison Operators

Comparison operators are used to compare values and return a Boolean result (True or False).

Common Comparison Operators:

  • Equal (==): Checks if two operands are equal.
  • Not Equal (!=): Checks if two operands are not equal.
  • Greater Than (>): Checks if the left operand is greater than the right.
  • Less Than (<): Checks if the left operand is less than the right.
  • Greater Than or Equal To (>=): Checks if the left operand is greater than or equal to the right.
  • Less Than or Equal To (<=): Checks if the left operand is less than or equal to the right.

Example:

x = 5
y = 10
print(x == y) # Output: False
print(x != y) # Output: True
print(x > y) # Output: False
print(x < y) # Output: True
print(x >= y) # Output: False
print(x <= y) # Output: True

Just in touch with Karthikeyan Rathinam: Linkedin, GitHub, Youtube

Logical Operators

Logical operators are used to combine conditional statements.

Common Logical Operators:

  • and: Returns True if both statements are true.
  • or: Returns True if one of the statements is true.
  • not: Returns the opposite of the result.

Example:

a = True
b = False
print(a and b) # Output: False
print(a or b) # Output: True
print(not a) # Output: False

Control Flow (if, else, elif, loops)

Welcome to the Control Flow section! This section will cover control structures in Python, including if statements, else statements, elif statements, and loops.

If Statements

If statements are used for conditional execution of code blocks based on certain conditions.

Syntax:

if condition:
# Code block to execute if the condition is True
else:
# Code block to execute if the condition is False

Example

x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")

Elif Statements

Elif statements are used to check multiple conditions after the initial if statement.

Syntax:

if condition1:
# Code block to execute if condition1 is True
elif condition2:
# Code block to execute if condition2 is True
else:
# Code block to execute if neither condition1 nor condition2 is True

Example:

x = 10
if x > 10:
print("x is greater than 10")
elif x < 10:
print("x is less than 10")
else:
print("x is equal to 10")

Loops (for and while)

Loops are used to iterate over a sequence of elements or execute a block of code repeatedly.

For Loop

The for loop is used to iterate over a sequence (such as a list, tuple, or string).

Syntax:

for element in sequence:
# Code block to execute for each element in the sequence

Example:

fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)

While Loop

The while loop is used to execute a block of code repeatedly as long as a specified condition is True.

Syntax:

while condition:
# Code block to execute while the condition is True

Example:

count = 0
while count < 5:
print(count)
count += 1

Functions

Welcome to the Functions section! Functions are essential in Python for organizing and reusing code. This section covers the creation and usage of functions in Python.

What are Functions?

Functions in Python are named blocks of code that perform a specific task. They allow you to break down complex tasks into smaller, reusable parts.

Function Declaration

Functions in Python are defined using the def keyword followed by the function name and parentheses containing optional parameters.

Syntax:

def function_name(parameters):
# Code block or statements
# Return statement (optional)

Functions

Welcome to the Functions section! Functions are essential in Python for organizing and reusing code. This section covers the creation and usage of functions in Python.

What are Functions?

Functions in Python are named blocks of code that perform a specific task. They allow you to break down complex tasks into smaller, reusable parts.

Function Declaration

Functions in Python are defined using the def keyword followed by the function name and parentheses containing optional parameters.

Syntax:

def function_name(parameters):
# Code block or statements
# Return statement (optional)

Example:

def greet(name):
print(f"Hello, {name}!")
# Calling the function
greet("Alice")

Return Statement

Functions can return values using the return statement. If no return statement is specified, the function returns None by default.

Example:

def add_numbers(a, b):
return a + b
result = add_numbers(5, 7)
print(result) # Output: 12

Parameters and Arguments

Functions can accept parameters (inputs) that are specified when the function is called. These parameters can have default values.

Example:

def greet_with_message(name, message="Welcome"):
print(f"{message}, {name}!")
greet_with_message("Alice") # Output: Welcome, Alice!
greet_with_message("Bob", "Good morning")# Output: Good morning, Bob!

Scope of Variables

Variables defined inside a function have local scope and are only accessible within that function unless explicitly declared as global.

Just in touch with Karthikeyan Rathinam: Linkedin, GitHub, Youtube

Data Structures

Welcome to the Data Structures section! Data structures in Python are fundamental for organizing and storing data efficiently. This section covers lists, tuples, dictionaries, and sets.

Lists

Lists in Python are ordered collections of items, and they can contain elements of different data types.

Creating a List:

my_list = [1, 2, 3, 'apple', 'banana', 'cherry']

Accessing Elements:

Elements in a list can be accessed using index numbers (starting from 0) or negative indices from the end of the list.

Example:

print(my_list[0])       # Output: 1
print(my_list[-1]) # Output: 'cherry'

List Methods:

  • append(): Adds an element to the end of the list.
  • remove(): Removes the first occurrence of a specified value.
  • pop(): Removes and returns the element at the specified index.
  • len(): Returns the number of elements in the list.

Tuples

Tuples are ordered, immutable collections of elements, and they are defined using parentheses.

Creating a Tuple:

my_tuple = (1, 2, 'apple', 'banana')

#Accessing Elements: Similar to lists, elements in a tuple can be accessed using index numbers.

Example:

print(my_tuple[2])      # Output: 'apple'

Tuple Methods:

Tuples are immutable, so they have fewer methods compared to lists.

Dictionaries

Dictionaries are unordered collections of key-value pairs enclosed in curly braces.

Creating a Dictionary:

my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}

Accessing Elements: Elements in a dictionary are accessed using keys.

Example:

print(my_dict['age'])   # Output: 25

Dictionary Methods:

  • keys(): Returns a list of keys in the dictionary.
  • values(): Returns a list of values in the dictionary.
  • items(): Returns a list of key-value pairs as tuples.

Sets

Sets are unordered collections of unique elements enclosed in curly braces.

Creating a Set:

my_set = {1, 2, 3, 'apple', 'banana'}

Accessing Elements:

Sets do not support indexing as they are unordered and have no duplicates.

Set Methods:

  • add(): Adds an element to the set.
  • remove(): Removes a specified element from the set.
  • union(): Returns a new set with elements from both sets.
  • intersection(): Returns a new set with elements common to both sets.

File Handling

File handling is essential for working with data stored in files. Python offers built-in functions and modules that make file handling intuitive and efficient.

Opening and Closing Files

Python’s open() function is used to open files in different modes:

file = open('example.txt', 'r')  # 'r' for reading, 'w' for writing, 'a' for appending
# Perform operations on the file
file.close()

Reading from a File

To read the contents of a file:

file = open('example.txt', 'r')
content = file.read() # Read the entire file
print(content)
file.close()

Writing to a File

Writing content to a file:

file = open('example.txt', 'w')
file.write('Hello, this is a sample text.')
file.close()

Appending to a File

Appending content to an existing file:

file = open('example.txt', 'a')
file.write('\nAppending more text.')
file.close()

Using with Statement (Context Manager)

with statement for automatic file closing:

Copy code
with open('example.txt', 'r') as file:
content = file.read()
print(content)
# File is automatically closed after the block

Handling Exceptions

Consider handling exceptions for file operations:

try:
file = open('example.txt', 'r')
content = file.read()
print(content)
except FileNotFoundError:
print("File not found!")
finally:
file.close()

File Navigation and Properties

Using os module for file properties and navigation:

import os
# Get current working directory
print(os.getcwd())
# Check if a file exists
if os.path.exists('example.txt'):
print("File exists!")
else:
print("File not found.")
# Get file size
file_size = os.path.getsize('example.txt')
print(f"File size: {file_size} bytes")

Modules

A module in Python is a file containing Python definitions, statements, functions, and classes. It allows you to logically organize your Python code. To use a module, you need to import it using the import statement.

Creating a Module

Create a Python file (e.g., my_module.py) containing functions or variables:

# my_module.py
def greet(name):
return f"Hello, {name}!"
my_variable = 123

Using a Module

Import the module into your Python script:

import my_module
message = my_module.greet("Alice")
print(message)
print(my_module.my_variable)

Packages

A package in Python is a collection of related modules organized in a directory structure. It contains an _ _init_ _. py file that signifies the directory as a Python package. Packages help in organizing and hierarchically structuring a larger codebase.

Just in touch with Karthikeyan Rathinam: Linkedin, GitHub, Youtube

Creating a Package

Let’s assume we have a package named my_package structured as follows:

my_package/
__init__.py
module1.py
module2.py

__init__.py can be an empty file or can contain initialization code for the package. module1.py and module2.py contain Python code defining functions, classes, or variables.

Using a Package

Import modules from the package using dot notation:

from my_package import module1, module2
result1 = module1.function1()
result2 = module2.function2()
print(result1, result2)

Benefits

  • Organization: Modules and packages help organize code into reusable components.
  • Encapsulation: Modules encapsulate code, reducing namespace collisions.
  • Reusability: Code in modules/packages can be reused across multiple projects.

Exception Handling

Exception handling in Python allows you to gracefully manage errors that might occur during the execution of your code. It prevents the program from crashing by handling exceptional situations. Python provides a try, except, else, and finally block structure for handling exceptions.

try and except The try block is used to wrap code that might raise an exception. The except block catches and handles specific exceptions.

try:
result = 10 / 0 # Division by zero raises an exception
except ZeroDivisionError as e:
print("Error:", e)
# Handle the exception, perform recovery, or show an appropriate message

Handling Multiple Exceptions

You can handle different exceptions using multiple except blocks.

try:
value = int(input("Enter a number: "))
result = 10 / value
except ValueError:
print("Please enter a valid number.")
except ZeroDivisionError:
print("Cannot divide by zero.")

Using else and finally

else The else block executes if no exceptions are raised in the try block.

try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero.")
else:
print("Result:", result)

finally The finally block always executes, regardless of whether an exception occurred.

try:
file = open("example.txt", "r")
# Perform file operations
except FileNotFoundError:
print("File not found.")
finally:
file.close() # Close the file, even if an exception occurs

Raising Custom Exceptions

You can raise exceptions based on certain conditions using the raise statement.

def validate_age(age):
if age < 0:
raise ValueError("Age cannot be negative.")
# Perform other checks
return True
try:
user_age = int(input("Enter your age: "))
validate_age(user_age)
except ValueError as e:
print("Error:", e)

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/
https://www.youtube.com/@linkagethink

Sign up to discover human stories that deepen your understanding of the world.

No responses yet

Write a response