7. Modules and Packages

Modules and packages help organize Python code into reusable files and folders.

They make programs:

  • Modular
  • Reusable
  • Easy to manage

Modules in Python

A module is a Python file containing:

  • Functions
  • Variables
  • Classes
  • Statements

Example file:

math_operations.py

Importing Modules

Python provides the import keyword.


Import Entire Module

import math

print(math.sqrt(25))

Output:

5.0

Import Specific Function

from math import sqrt

print(sqrt(49))

Import Multiple Functions

from math import sqrt, pi

print(pi)
print(sqrt(16))

Import with Alias

Use shorter names.

import math as m

print(m.factorial(5))

Import All Functions

from math import *

Not recommended in large projects.


Creating Modules

You can create your own module.


Example: Create Module

Create file:

calculator.py

Add code:

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

def subtract(a, b):
return a - b

Use Custom Module

Create another file:

import calculator

print(calculator.add(10, 5))
print(calculator.subtract(20, 5))

The __name__ Variable

Every Python module has a built-in variable called __name__.


Example

print(__name__)

If file runs directly:

__main__

Example with __main__

def greet():
print("Hello")

if __name__ == "__main__":
greet()

Python Standard Library

Python provides many built-in modules.


Common Standard Library Modules

ModulePurpose
mathMathematical functions
randomRandom values
datetimeDate and time
osOperating system tasks
sysSystem-specific parameters
reRegular expressions
jsonJSON handling

Example: random

import random

print(random.randint(1, 10))

Example: datetime

from datetime import datetime

now = datetime.now()

print(now)

Example: os

import os

print(os.getcwd())

Packages in Python

A package is a collection of modules organized in folders.

Used for larger projects.


Package Structure

mypackage/

├── __init__.py
├── math_tools.py
└── string_tools.py
  • __init__.py makes folder a package.

Example Module in Package

math_tools.py

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

Import from Package

from mypackage import math_tools

print(math_tools.add(2, 3))

pip and Package Installation

pip is Python’s package manager.

Used to install external libraries.


Check pip Version

pip --version

Install Package

pip install requests

Install Specific Version

pip install numpy==1.26.0

Upgrade Package

pip install --upgrade requests

Uninstall Package

pip uninstall requests

View Installed Packages

pip list

Requirements File

Used to store project dependencies.

Create file:

requirements.txt

Example:

numpy
pandas
requests

Install all packages:

pip install -r requirements.txt

Virtual Environments

Virtual environment creates isolated Python environments.

Helps avoid dependency conflicts.


Create Virtual Environment

python -m venv myenv

Activate Virtual Environment

Windows

myenv\Scripts\activate

Linux/macOS

source myenv/bin/activate

Deactivate Environment

deactivate

Why Use Virtual Environments?

Benefits:

  • Separate project dependencies
  • Avoid package conflicts
  • Cleaner development setup

Installing Packages Inside Virtual Environment

pip install flask

Only installed inside that environment.


Example Project Structure

project/

├── myenv/
├── app.py
├── requirements.txt
└── modules/

Practical Example

Random Password Generator

import random
import string

characters = string.ascii_letters + string.digits

password = ""

for i in range(8):
password += random.choice(characters)

print("Password:", password)

Summary

In this chapter you learned:

✅ Importing modules
✅ Creating custom modules
✅ Python standard library
✅ Packages
pip package manager
✅ Installing and uninstalling packages
✅ Requirements file
✅ Virtual environments
✅ Using external libraries

6. Functions in Python

Functions are reusable blocks of code used to perform specific tasks.

Functions help:

  • Reduce code repetition
  • Improve readability
  • Make programs modular

Defining Functions

Use the def keyword to create a function.


Syntax

def function_name():
# code

Example

def greet():
print("Hello, Welcome to Python")

Calling the function:

greet()

Output:

Hello, Welcome to Python

Function with Parameters

Parameters allow passing data to functions.

def greet(name):
print("Hello", name)

greet("Aditya")

Output:

Hello Aditya

Function Arguments

Arguments are values passed to functions.

Python supports different types of arguments.


1. Positional Arguments

Arguments are assigned based on position.

def add(a, b):
print(a + b)

add(10, 20)

Output:

30

2. Keyword Arguments

Arguments are assigned using parameter names.

def student(name, age):
print(name, age)

student(age=25, name="Aditya")

3. Default Arguments

Default values are used if argument is not provided.

def greet(name="Guest"):
print("Hello", name)

greet()
greet("Rahul")

Output:

Hello Guest
Hello Rahul

4. Variable-Length Arguments

Used when number of arguments is unknown.


*args

Accepts multiple positional arguments.

def total(*numbers):
print(numbers)

total(1, 2, 3, 4)

Output:

(1, 2, 3, 4)

Sum Using *args

def add(*numbers):
total = 0

for num in numbers:
total += num

print(total)

add(1, 2, 3)

**kwargs

Accepts multiple keyword arguments.

def details(**data):
print(data)

details(name="Aditya", age=25)

Output:

{'name': 'Aditya', 'age': 25}

Return Statement

The return statement sends value back from function.


Example

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

result = add(10, 20)

print(result)

Output:

30

Multiple Return Values

def calculation(a, b):
return a + b, a - b

sum_value, sub_value = calculation(10, 5)

print(sum_value)
print(sub_value)

Lambda Functions

Lambda functions are anonymous small functions.


Syntax

lambda arguments : expression

Example

square = lambda x: x * x

print(square(5))

Output:

25

Lambda with Multiple Arguments

add = lambda a, b: a + b

print(add(10, 20))

Recursive Functions

A recursive function calls itself.

Used for problems that can be broken into smaller similar problems.


Example: Factorial

def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)

print(factorial(5))

Output:

120

Example: Fibonacci Series

def fibonacci(n):
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)

for i in range(6):
print(fibonacci(i))

Output:

0
1
1
2
3
5

Scope and Lifetime of Variables

Scope defines where a variable can be accessed.


1. Local Variables

Declared inside function.

Accessible only inside that function.

def test():
x = 10
print(x)

test()

Example: Error Outside Function

def demo():
y = 20

demo()

# print(y) # Error

2. Global Variables

Declared outside function.

Accessible everywhere.

name = "Python"

def show():
print(name)

show()

Modifying Global Variable

Use global keyword.

count = 0

def increase():
global count
count += 1

increase()

print(count)

Output:

1

Lifetime of Variables

  • Local variables exist only during function execution.
  • Global variables exist throughout program execution.

Nested Functions

Function inside another function.

def outer():

def inner():
print("Inside Inner Function")

inner()

outer()

Practical Example

Calculator Function

def calculator(a, b):

print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)

calculator(10, 5)

Summary

In this chapter you learned:

✅ Defining functions
✅ Function arguments
✅ Positional arguments
✅ Keyword arguments
✅ Default arguments
✅ Variable-length arguments (*args, **kwargs)
✅ Return statement
✅ Lambda functions
✅ Recursive functions
✅ Scope and lifetime of variables

5. Data Structures

Data structures are used to store and organize data efficiently.

Python provides four major built-in data structures:

  • Lists
  • Tuples
  • Sets
  • Dictionaries

Lists in Python

A list is an ordered and mutable collection.

Lists allow:

  • Duplicate values
  • Different data types

Creating Lists

Empty List

numbers = []
print(numbers)

List with Values

fruits = ["Apple", "Banana", "Mango"]

print(fruits)

Mixed Data Types

data = [10, 3.14, "Python", True]

print(data)

Accessing List Elements

fruits = ["Apple", "Banana", "Mango"]

print(fruits[0])
print(fruits[2])

Negative Indexing

print(fruits[-1])

Output:

Mango

List Slicing

numbers = [10, 20, 30, 40, 50]

print(numbers[1:4])

Output:

[20, 30, 40]

Modify List Elements

fruits = ["Apple", "Banana"]

fruits[1] = "Orange"

print(fruits)

List Methods


1. append()

Adds item at end.

numbers = [1, 2, 3]

numbers.append(4)

print(numbers)

2. insert()

Adds item at specific position.

numbers.insert(1, 100)

print(numbers)

3. remove()

Removes specified item.

numbers.remove(100)

print(numbers)

4. pop()

Removes item by index.

numbers.pop(1)

print(numbers)

5. sort()

Sorts list.

values = [5, 2, 8, 1]

values.sort()

print(values)

6. reverse()

Reverses list.

values.reverse()

print(values)

7. len()

Returns length.

print(len(values))

Nested Lists

List inside another list.

matrix = [
[1, 2, 3],
[4, 5, 6]
]

print(matrix[0])
print(matrix[1][2])

Output:

[1, 2, 3]
6

Tuples in Python

A tuple is an ordered and immutable collection.

Cannot be modified after creation.


Creating Tuples

colors = ("Red", "Green", "Blue")

print(colors)

Single Element Tuple

data = (5,)

print(type(data))

Access Tuple Elements

print(colors[0])

Tuple Operations


Concatenation

a = (1, 2)
b = (3, 4)

print(a + b)

Repetition

print(a * 2)

Tuple Packing and Unpacking

Packing

person = ("Aditya", 25, "India")

Unpacking

name, age, country = person

print(name)
print(age)
print(country)

Sets in Python

A set is:

  • Unordered
  • Mutable
  • Unique elements only

Duplicates are automatically removed.


Creating Sets

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

print(numbers)

Output:

{1, 2, 3, 4}

Add Elements

numbers.add(5)

print(numbers)

Remove Elements

numbers.remove(2)

print(numbers)

Set Operations


1. Union

Combines all elements.

a = {1, 2, 3}
b = {3, 4, 5}

print(a | b)

Output:

{1, 2, 3, 4, 5}

2. Intersection

Common elements.

print(a & b)

Output:

{3}

3. Difference

Elements in first set only.

print(a - b)

Output:

{1, 2}

Dictionaries in Python

Dictionary stores data in:

key : value

format.

Dictionary is:

  • Mutable
  • Ordered (Python 3.7+)

Creating Dictionaries

student = {
"name": "Aditya",
"age": 25,
"course": "Python"
}

print(student)

Access Dictionary Values

print(student["name"])
print(student["age"])

Add or Update Values

student["age"] = 26
student["city"] = "Delhi"

print(student)

Dictionary Methods


1. keys()

Returns all keys.

print(student.keys())

2. values()

Returns all values.

print(student.values())

3. items()

Returns key-value pairs.

print(student.items())

4. get()

Safely gets value.

print(student.get("name"))

5. pop()

Removes item.

student.pop("city")

print(student)

Loop Through Dictionary

for key, value in student.items():
print(key, value)

Nested Dictionaries

Dictionary inside another dictionary.

students = {
"student1": {
"name": "Rahul",
"age": 20
},
"student2": {
"name": "Aman",
"age": 22
}
}

print(students["student1"]["name"])

Output:

Rahul

Comparison of Data Structures

TypeOrderedMutableDuplicates
ListYesYesYes
TupleYesNoYes
SetNoYesNo
DictionaryYesYesKeys No

Summary

In this chapter you learned:

✅ Lists and list methods
✅ List slicing
✅ Nested lists
✅ Tuples and tuple operations
✅ Packing and unpacking
✅ Sets and set operations
✅ Union, intersection, difference
✅ Dictionaries and dictionary methods
✅ Nested dictionaries

4. Strings in Python

Strings are used to store text data in Python.

A string is a sequence of characters enclosed in:

  • Single quotes ' '
  • Double quotes " "
  • Triple quotes ''' ''' or """ """

String Creation

Using Single Quotes

name = 'Python'
print(name)

Using Double Quotes

language = "Programming"
print(language)

Using Triple Quotes

Used for multi-line strings.

text = """Python is
easy to learn"""

print(text)

String Indexing

Each character in a string has an index number.

Example:

word = "Python"
CharacterPython
Index012345

Access Characters

word = "Python"

print(word[0])
print(word[2])

Output:

P
t

Negative Indexing

print(word[-1])
print(word[-2])

Output:

n
o

String Slicing

Slicing extracts part of a string.

Syntax

string[start:end]
  • start included
  • end excluded

Examples

text = "Python"

print(text[0:3])
print(text[2:5])

Output:

Pyt
tho

Slicing with Step

print(text[0:6:2])

Output:

Pto

Reverse String

print(text[::-1])

Output:

nohtyP

String Methods

Python provides many built-in string methods.


1. upper()

Converts string to uppercase.

name = "python"

print(name.upper())

Output:

PYTHON

2. lower()

Converts string to lowercase.

print("PYTHON".lower())

3. title()

Capitalizes first letter of each word.

text = "python programming"

print(text.title())

4. strip()

Removes extra spaces.

text = "  Python  "

print(text.strip())

5. replace()

Replaces text.

text = "I like Java"

print(text.replace("Java", "Python"))

6. split()

Splits string into list.

text = "apple,banana,mango"

print(text.split(","))

Output:

['apple', 'banana', 'mango']

7. find()

Returns position of substring.

text = "Python Programming"

print(text.find("Pro"))

8. startswith() and endswith()

text = "Python"

print(text.startswith("Py"))
print(text.endswith("on"))

9. count()

Counts occurrences.

text = "banana"

print(text.count("a"))

Output:

3

Escape Characters

Escape characters are used to include special characters inside strings.


Common Escape Characters

EscapeMeaning
\nNew line
\tTab
\\Backslash
\'Single quote
\"Double quote

Examples

print("Hello\nWorld")

Output:

Hello
World

print("Python\tProgramming")

String Formatting

String formatting inserts values into strings.


1. Using + Operator

name = "Aditya"

print("Hello " + name)

2. Using Comma

age = 25

print("Age:", age)

f-Strings

Introduced in Python 3.6.

Fast and readable method.


Syntax

f"string {variable}"

Example

name = "Aditya"
age = 25

print(f"My name is {name} and I am {age} years old")

Expressions in f-Strings

a = 10
b = 20

print(f"Sum = {a + b}")

.format() Method

Another formatting method.


Example

name = "Aditya"
age = 25

print("My name is {} and age is {}".format(name, age))

Indexed Formatting

print("{0} is learning {1}".format("Aditya", "Python"))

Named Formatting

print("{name} is {age} years old".format(name="Aditya", age=25))

Regular Expressions (re Module)

Regular expressions are used for pattern matching.

Python provides the re module.


Import re

import re

1. findall()

Returns all matches.

import re

text = "Python 123 Java 456"

result = re.findall(r'\d+', text)

print(result)

Output:

['123', '456']

2. search()

Searches first occurrence.

import re

text = "I love Python"

match = re.search("Python", text)

print(match)

3. sub()

Replaces matched text.

import re

text = "I like Java"

new_text = re.sub("Java", "Python", text)

print(new_text)

Output:

I like Python

Common Regex Patterns

PatternMeaning
\dDigit
\DNon-digit
\wWord character
\sSpace
.Any character
^Starts with
$Ends with

Example: Validate Email

import re

email = "test@gmail.com"

pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'

if re.match(pattern, email):
print("Valid Email")
else:
print("Invalid Email")

Summary

In this chapter you learned:

✅ String creation
✅ String indexing and slicing
✅ String methods
✅ Escape characters
✅ String formatting
✅ f-strings
.format() method
✅ Regular expressions using re module

3. Control Flow Statements

Control flow statements control the execution of a program based on conditions and loops.


Decision Making Statements

1. if Statement

The if statement executes code only if the condition is True.

Syntax

if condition:
# code

Example

age = 18

if age >= 18:
print("You can vote")

Output:

You can vote

2. if...else Statement

Used when there are two possible outcomes.

Syntax

if condition:
# code if true
else:
# code if false

Example

number = 5

if number % 2 == 0:
print("Even")
else:
print("Odd")

3. if...elif...else Statement

Used to check multiple conditions.

Syntax

if condition1:
# code
elif condition2:
# code
else:
# code

Example

marks = 75

if marks >= 90:
print("Grade A")
elif marks >= 60:
print("Grade B")
else:
print("Grade C")

Nested Conditions

An if statement inside another if statement is called nested condition.


Example

age = 25
citizen = True

if age >= 18:
if citizen:
print("Eligible to vote")

Loops in Python

Loops are used to repeat code multiple times.

Python has:

  • for loop
  • while loop

1. for Loop

Used to iterate over a sequence.

Syntax

for variable in sequence:
# code

Example 1: Loop through List

fruits = ["Apple", "Banana", "Mango"]

for fruit in fruits:
print(fruit)

Example 2: Loop through String

for ch in "Python":
print(ch)

2. while Loop

Runs as long as condition is True.

Syntax

while condition:
# code

Example

count = 1

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

Infinite Loop

If condition never becomes false.

while True:
print("Running forever")

Use carefully.


Loop Control Statements

Used to control loop execution.


1. break

Stops the loop immediately.


Example

for i in range(1, 10):
if i == 5:
break
print(i)

Output:

1
2
3
4

2. continue

Skips current iteration and moves to next iteration.


Example

for i in range(1, 6):
if i == 3:
continue
print(i)

Output:

1
2
4
5

3. pass

Does nothing.

Used as placeholder.


Example

for i in range(5):
pass

Range Function

The range() function generates a sequence of numbers.


Syntax

range(start, stop, step)

Parameters:

  • start → starting value
  • stop → ending value (excluded)
  • step → increment/decrement

Example 1: Basic Range

for i in range(5):
print(i)

Output:

0
1
2
3
4

Example 2: Start and Stop

for i in range(2, 6):
print(i)

Output:

2
3
4
5

Example 3: Step Value

for i in range(1, 10, 2):
print(i)

Output:

1
3
5
7
9

Reverse Loop

for i in range(10, 0, -1):
print(i)

Nested Loops

Loop inside another loop.


Example

for i in range(1, 4):
for j in range(1, 3):
print(i, j)

Practical Examples

Example 1: Sum of Numbers

total = 0

for i in range(1, 6):
total += i

print(total)

Output:

15

Example 2: Multiplication Table

num = 5

for i in range(1, 11):
print(num, "x", i, "=", num * i)

Summary

In this chapter you learned:

if, elif, else statements
✅ Nested conditions
for loop
while loop
break statement
continue statement
pass statement
range() function
✅ Nested loops
✅ Practical loop examples

2. Python Basics

Variables in Python

What is a Variable?

A variable is used to store data in memory.

Example:

name = "Aditya"
age = 25

Here:

  • name stores text
  • age stores a number

Rules for Naming Variables

Valid Examples

student_name = "Rahul"
age2 = 20
_total = 500

Invalid Examples

2name = "Rahul"     # Cannot start with number
student-name = "A" # Hyphen not allowed

Multiple Variable Assignment

x, y, z = 10, 20, 30
print(x, y, z)

Dynamic Typing

Python automatically detects data type.

x = 10
x = "Hello"

Data Types in Python

Python has several built-in data types.


1. Integer (int)

Integers are whole numbers.

age = 25
marks = -90

print(type(age))

Output:

<class 'int'>

2. Float (float)

Float represents decimal numbers.

price = 99.99
pi = 3.14

Output:

<class 'float'>

3. String (str)

String stores text.

name = "Aditya"
city = 'Delhi'

String Examples

print(name)
print(city)

4. Boolean (bool)

Boolean has only two values:

  • True
  • False
is_logged_in = True
is_admin = False

5. Complex (complex)

Complex numbers contain real and imaginary parts.

x = 3 + 5j

print(type(x))

Output:

<class 'complex'>

Checking Data Type

Use type() function.

x = 10
print(type(x))

Type Conversion

Type conversion means changing one data type into another.


1. Integer to Float

x = 10
y = float(x)

print(y)

Output:

10.0

2. Float to Integer

x = 5.9
y = int(x)

print(y)

Output:

5

3. Integer to String

x = 100
y = str(x)

print(y)
print(type(y))

4. String to Integer

x = "50"
y = int(x)

print(y + 10)

Output:

60

Input and Output

Output using print()

print("Welcome to Python")

Taking Input from User

name = input("Enter your name: ")

print("Hello", name)

Input Always Returns String

age = input("Enter age: ")

print(type(age))

Output:

<class 'str'>

Convert Input to Integer

age = int(input("Enter age: "))

print(age + 5)

Operators in Python

Operators are used to perform operations on values and variables.


1. Arithmetic Operators

OperatorMeaningExample
+Addition5 + 2
-Subtraction5 - 2
*Multiplication5 * 2
/Division5 / 2
%Modulus5 % 2
**Power5 ** 2
//Floor Division5 // 2

Example

a = 10
b = 3

print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a % b)
print(a ** b)
print(a // b)

2. Comparison Operators

Used to compare values.

OperatorMeaning
==Equal
!=Not equal
>Greater than
<Less than
>=Greater than equal
<=Less than equal

Example

x = 10
y = 20

print(x == y)
print(x != y)
print(x > y)
print(x < y)

3. Logical Operators

Used with conditions.

OperatorMeaning
andBoth conditions true
orAny one condition true
notReverse condition

Example

age = 20

print(age > 18 and age < 30)
print(age > 18 or age < 10)
print(not(age > 18))

4. Assignment Operators

Used to assign values.

OperatorExample
=x = 5
+=x += 2
-=x -= 2
*=x *= 2
/=x /= 2

Example

x = 10

x += 5
print(x)

x *= 2
print(x)

5. Bitwise Operators

Operate on binary values.

OperatorMeaning
&AND
``
^XOR
~NOT
<<Left Shift
>>Right Shift

Example

a = 5
b = 3

print(a & b)
print(a | b)
print(a ^ b)

6. Membership Operators

Used to check membership in sequence.

OperatorMeaning
inPresent
not inNot present

Example

text = "Python"

print("P" in text)
print("z" not in text)

7. Identity Operators

Used to compare memory location.

OperatorMeaning
isSame object
is notDifferent object

Example

x = [1, 2]
y = x
z = [1, 2]

print(x is y)
print(x is z)

Output:

True
False

Summary

In this chapter you learned:

✅ Variables
✅ Data types
✅ Integer, Float, String, Boolean, Complex
✅ Type conversion
✅ Input and output
✅ Arithmetic operators
✅ Comparison operators
✅ Logical operators
✅ Assignment operators
✅ Bitwise operators
✅ Membership operators
✅ Identity operators

1. Introduction to Python

What is Python?

Python is a high-level, interpreted, and general-purpose programming language created by Guido van Rossum and released in 1991.

Python is designed to be:

  • Easy to read
  • Simple to learn
  • Powerful for real-world applications

It is widely used in:

  • Web development
  • Data Science
  • Artificial Intelligence
  • Automation
  • Game development
  • Cybersecurity
  • Software development

Example of Python code:

print("Hello, World!")

Features of Python

1. Easy to Learn and Read

Python uses simple English-like syntax.

name = "Aditya"
print(name)

2. Interpreted Language

Python code runs line by line using an interpreter.

No compilation required before execution.


3. Platform Independent

Python works on:

  • Windows
  • Linux
  • macOS

Same code can run on different operating systems.


4. Open Source

Python is free to use and has a huge community.

Official website:
https://www.python.org


5. Object-Oriented

Python supports:

  • Classes
  • Objects
  • Inheritance
  • Polymorphism

6. Large Standard Library

Python provides built-in modules for:

  • File handling
  • Math
  • Web requests
  • Data processing
  • Database access

7. Supports Multiple Programming Styles

Python supports:

  • Procedural programming
  • Object-oriented programming
  • Functional programming

8. Huge Community Support

Millions of developers contribute tutorials, libraries, and solutions.


Installing Python

Step 1: Download Python

Visit:

https://www.python.org/downloads

Download the latest version.


Step 2: Install Python on Windows

During installation:

✅ Check:

Add Python to PATH

Then click:

Install Now

Step 3: Verify Installation

Open Command Prompt and type:

python --version

or

python3 --version

Example output:

Python 3.12.0

Python IDEs and Editors

What is an IDE?

IDE = Integrated Development Environment

It helps programmers write, run, and debug code.


1. IDLE

IDLE comes pre-installed with Python.

Features:

  • Simple interface
  • Good for beginners
  • Syntax highlighting

How to Open:

Search:

IDLE

in Windows Start Menu.


2. VS Code

Visual Studio Code is a popular lightweight editor.

Features:

  • Fast
  • Extensions support
  • Debugging tools
  • Git integration

Installation:

  1. Download VS Code
  2. Install Python extension

Website:
https://code.visualstudio.com


3. PyCharm

Professional Python IDE by JetBrains.

Features:

  • Smart code completion
  • Debugging
  • Project management
  • Django support

Versions:

  • Community Edition (Free)
  • Professional Edition (Paid)

Website:
https://www.jetbrains.com/pycharm/


4. Jupyter Notebook

Used mostly for:

  • Data Science
  • Machine Learning
  • Research

Features:

  • Run code cell by cell
  • Supports graphs and visualization
  • Interactive environment

Install using:

pip install notebook

Run using:

jupyter notebook

Running Python Programs

Method 1: Using Python Shell

Open terminal and type:

python

Then write:

print("Hello")

Method 2: Using Python File

Create a file:

hello.py

Add code:

print("Hello World")

Run:

python hello.py

Python Syntax Basics

Python syntax is simple and readable.


1. Print Statement

print("Welcome to Python")

2. Variables

name = "Aditya"
age = 25

3. Indentation

Python uses indentation instead of braces.

Correct:

if 5 > 2:
print("Five is greater")

Incorrect:

if 5 > 2:
print("Error")

4. Case Sensitive

name = "Aditya"
Name = "Kumar"

Both are different variables.


Comments and Documentation

What are Comments?

Comments are notes in code ignored by Python.

Used to explain code.


Single-Line Comment

# This is a comment
print("Hello")

Multi-Line Comment

"""
This is a
multi-line comment
"""

or

'''
Multi-line comment
'''

Documentation Strings (Docstrings)

Used to describe functions, classes, or modules.

Example:

def add(a, b):
"""
This function adds two numbers
"""
return a + b

Summary

In this chapter you learned:

✅ What Python is
✅ Features of Python
✅ Installing Python
✅ Python IDEs and editors
✅ Running Python programs
✅ Basic Python syntax
✅ Comments and documentation

Full Python Syllabus (Beginner to Advanced)

1. Introduction to Python

  • What is Python?
  • Features of Python
  • Installing Python
  • Python IDEs and Editors
    • IDLE
    • VS Code
    • PyCharm
    • Jupyter Notebook
  • Running Python programs
  • Python syntax basics
  • Comments and documentation

2. Python Basics

  • Variables
  • Data types
    • Integer
    • Float
    • String
    • Boolean
    • Complex
  • Type conversion
  • Input and output
  • Operators
    • Arithmetic
    • Comparison
    • Logical
    • Assignment
    • Bitwise
    • Membership
    • Identity

3. Control Flow Statements

  • if, elif, else
  • Nested conditions
  • Loops
    • for
    • while
  • Loop control statements
    • break
    • continue
    • pass
  • Range function

4. Strings in Python

  • String creation
  • String indexing and slicing
  • String methods
  • Escape characters
  • String formatting
    • f-strings
    • .format()
  • Regular expressions (re module)

5. Data Structures

Lists

  • Creating lists
  • List methods
  • List slicing
  • Nested lists

Tuples

  • Tuple operations
  • Packing and unpacking

Sets

  • Set operations
  • Union, intersection, difference

Dictionaries

  • Creating dictionaries
  • Dictionary methods
  • Nested dictionaries

6. Functions

  • Defining functions
  • Function arguments
    • Positional
    • Keyword
    • Default
    • Variable-length (*args, **kwargs)
  • Return statement
  • Lambda functions
  • Recursive functions
  • Scope and lifetime of variables

7. Modules and Packages

  • Importing modules
  • Creating modules
  • Python standard library
  • Packages
  • pip and package installation
  • Virtual environments

8. File Handling

  • Opening and closing files
  • Reading files
  • Writing files
  • File modes
  • Working with CSV files
  • Working with JSON files

9. Exception Handling

  • Types of errors
  • try, except
  • finally
  • else
  • Raising exceptions
  • Custom exceptions

10. Object-Oriented Programming (OOP)

  • Classes and objects
  • Constructors
  • Instance and class variables
  • Methods
  • Inheritance
  • Polymorphism
  • Encapsulation
  • Abstraction
  • Magic methods (__init__, __str__, etc.)

11. Advanced Python Concepts

  • Iterators
  • Generators
  • Decorators
  • Context managers
  • Closures
  • Comprehensions
    • List comprehension
    • Dictionary comprehension
  • Functional programming tools
    • map
    • filter
    • reduce

12. Python Libraries

Standard Libraries

  • math
  • random
  • datetime
  • os
  • sys
  • collections

Popular External Libraries

  • NumPy
  • Pandas
  • Matplotlib
  • Requests
  • BeautifulSoup
  • Flask
  • Django

13. Database Programming

  • SQLite with Python
  • MySQL connectivity
  • CRUD operations
  • ORM basics

14. Web Development with Python

Flask

  • Routing
  • Templates
  • Forms
  • APIs

Django

  • Models
  • Views
  • Templates
  • Admin panel
  • Authentication

15. Data Science with Python

  • NumPy basics
  • Pandas DataFrames
  • Data visualization
  • Data cleaning
  • Exploratory Data Analysis (EDA)

16. Machine Learning with Python

  • Scikit-learn basics
  • Regression
  • Classification
  • Clustering
  • Model evaluation

17. Automation and Scripting

  • Automating tasks
  • Web scraping
  • Email automation
  • File automation
  • Scheduling scripts

18. APIs and Networking

  • REST APIs
  • Using requests
  • JSON handling
  • API authentication
  • Socket programming basics

19. Testing in Python

  • Unit testing
  • unittest
  • pytest
  • Mocking
  • Debugging techniques

20. Multithreading and Multiprocessing

  • Threads
  • Processes
  • Synchronization
  • Async programming (asyncio)

21. Cybersecurity & Ethical Hacking with Python

  • Network scanning
  • Packet sniffing
  • Cryptography basics
  • Automation tools

22. GUI Development

  • Tkinter
  • PyQt basics
  • Event handling

23. Python for Cloud & DevOps

  • Working with AWS SDK (boto3)
  • Docker with Python
  • CI/CD basics

24. Performance Optimization

  • Profiling
  • Memory optimization
  • Efficient coding practices

25. Final Projects

  • Calculator app
  • To-do application
  • Chat application
  • Web scraper
  • Data dashboard
  • Machine learning project
  • REST API project

Recommended Learning Path

Beginner

  1. Basics
  2. Control Flow
  3. Strings
  4. Data Structures
  5. Functions
  6. File Handling

Intermediate

  1. OOP
  2. Modules & Packages
  3. Exception Handling
  4. Advanced Concepts

Advanced

  1. Web Development
  2. Data Science
  3. APIs
  4. Automation
  5. Machine Learning
  6. Cloud & DevOps

Ultimate Guide to Using GitHub for Python Projects (2026 Edition)

In today’s fast-paced development world, managing Python projects efficiently is crucial. Whether you’re a beginner or an experienced developer, tools like GitHub, PyTest, Docker, and modern dependency managers can significantly improve your workflow.

In this guide, we’ll explore the best tools and practices for managing Python projects using GitHub, along with the correct and updated ecosystem you should actually use in 2026.


🔑 Why Use GitHub for Python Projects?

GitHub is more than just a code hosting platform. It provides:

  • Version control with Git
  • Collaboration features
  • Issue tracking and project management
  • CI/CD automation with GitHub Actions

Using GitHub properly can help you build scalable, maintainable, and production-ready Python applications.


⚙️ 1. GitHub Actions – Automate Your Workflow

GitHub Actions is a powerful CI/CD tool that allows you to automate:

  • Code testing
  • Build processes
  • Deployment

Example Use Case:

Whenever you push code, GitHub Actions can:

  • Run PyTest automatically
  • Check code quality
  • Deploy your app

👉 This saves time and ensures bug-free releases.


🔄 2. GitHub Flow – Simple Workflow for Teams

GitHub Flow is a lightweight branching strategy:

Steps:

  1. Create a branch
  2. Make changes
  3. Open a pull request
  4. Review & merge

This workflow is ideal for:

  • Startups
  • Small teams
  • Continuous deployment projects

🧪 3. PyTest – Testing Made Easy

PyTest is one of the most popular Python testing frameworks.

Features:

  • Simple syntax
  • Powerful fixtures
  • Supports unit and integration tests

Example:

def test_add():
assert 2 + 2 == 4

Testing ensures your code is reliable and production-ready.


📦 4. Dependency Management – Pipenv vs Poetry

Pipenv (Traditional)

  • Combines pip + virtualenv
  • Easy to use

Poetry (Recommended in 2026 🚀)

  • Faster and modern
  • Better dependency resolution
  • Built-in packaging support

👉 Recommendation: Use Poetry for new projects.


🐳 5. Docker – Containerize Your Python App

Instead of “PyDocker” (which is not a standard tool), developers use Docker.

Benefits:

  • Consistent environment
  • Easy deployment
  • Works across all systems

Example:

FROM python:3.11
WORKDIR /app
COPY . .
RUN pip install -r requirements.txt
CMD ["python", "app.py"]

🧹 6. Code Quality Tools (Must Use)

To maintain clean and professional code:

  • flake8 → Linting
  • black → Code formatting
  • pylint → Deep analysis

👉 These tools improve readability and reduce bugs.


📚 7. Documentation Tools (Correct Options)

Instead of “Pytest Docs” (incorrect), use:

Best Tools:

  • MkDocs → Simple and modern
  • Sphinx → Advanced documentation

Good documentation improves:

  • SEO
  • User experience
  • Developer onboarding

💻 8. PyCharm – Professional Python IDE

PyCharm is a powerful IDE offering:

  • Smart code completion
  • Debugging tools
  • Built-in Git integration

It helps developers write clean and efficient code faster.


🏆 Best Tech Stack for Python Projects (2026)

Here’s the recommended modern stack:

PurposeTool
Version ControlGitHub
CI/CDGitHub Actions
TestingPyTest
Dependency MgmtPoetry
Code Qualityflake8, black
DocumentationMkDocs
ContainerizationDocker
IDEPyCharm

⚠️ Common Mistakes to Avoid

  • ❌ Using unknown tools like “PyDocker”
  • ❌ Ignoring testing
  • ❌ No CI/CD setup
  • ❌ Poor documentation
  • ❌ Not using version control properly

Avoiding these mistakes can save hours of debugging and maintenance.


📈 SEO Benefits of Proper Project Structure

A well-managed project can:

  • Improve website performance
  • Increase search rankings
  • Enhance user trust
  • Boost traffic

👉 Especially important if you’re building platforms like soatechnology.net


🔚 Conclusion

Managing Python projects with GitHub is essential in 2026. By using the right tools like GitHub Actions, PyTest, Docker, and Poetry, you can build scalable and efficient applications.

Focus on:

  • Automation
  • Clean code
  • Testing
  • Documentation

This approach will help you create professional, high-performing projects that stand out.

send email using python in ubuntu

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import datetime
import pytz
import time
import sys
tz_NY = pytz.timezone('Asia/Kolkata')
x = datetime.datetime.now(tz_NY)
# list of email_id to send the mail
li = ["adityaypi@yahoo.com", "rcmaditya@gmail.com","adityaypi@live.com","aditya@peakecorp.com"]
msg = MIMEMultipart()
msg['From'] = "aditya@peakecorp.com"
x = datetime.datetime.now(tz_NY)
for dest in li:
 try:
    subject = 'Admin Notofication'+ x.strftime('%m/%d/%Y %H:%M:%S')+" "+dest
    msg['To'] = dest
    msg['Subject'] = subject
    body = 'Latest FI Prices '+x.strftime('%m/%d/%Y %H:%M:%S')+' Attached'
    msg.attach(MIMEText(body,'html'))
    text = msg.as_string()
    s = smtplib.SMTP('smtp.gmail.com', 587)
    s.starttls()
    s.login("aditya@peakecorp.com", "app password")
    s.sendmail("", dest, text)  
    s.quit()
    time.sleep(1)
 except Exception as e:
    sys.stderr.write(str(e)+'\n')
    sys.stderr.flush()