✅ Type Casting in Python
Type casting means converting one data type into another data type.
Python provides built-in functions to perform type casting, and it's widely
used when you need to perform operations between different types or
ensure that data is in the correct format.
🔢 Why Type Casting?
To avoid errors when performing operations between different data
types.
To ensure compatibility between functions and inputs.
To process data properly (like converting user input from string to
integer).
📦 Common Type Casting Functions in Python
Function Converts to… Example
int() Integer int("5") → 5
float() Float float("3.14") → 3.14
str() String str(100) → "100"
list() List list("abc") → ['a','b','c']
tuple() Tuple tuple([1, 2]) → (1, 2)
set() Set set([1, 2, 2, 3]) → {1, 2, 3}
dict() Dictionary dict([(1, 'one')]) → {1: 'one'}
✅ Explanations
1. int → int
Always possible.
Example: int(5) → 5.
2. int → float
Always possible. Converts integer to floating-point.
Example: float(5) → 5.0.
3. int → str
Always possible. Converts integer to string.
Example: str(5) → "5".
4. float → int
Possible only if the float is a whole number or will be truncated.
Example: int(5.0) → 5, but int(5.7) → 5.
5. float → float
Always possible.
Example: float(5.7) → 5.7.
6. float → str
Always possible. Converts float to string.
Example: str(5.7) → "5.7".
7. str → int
Possible only if the string represents an integer value.
Example: int("123") → 123, but int("abc") ❌ error.
8. str → float
Possible only if the string represents a numeric value.
Example: float("3.14") → 3.14, but float("abc") ❌ error.
9. str → str
Always possible.
Example: str("hello") → "hello".
📌 Summary
int and float can always convert between each other, with
truncation when converting to int.
int and float can always be converted to str.
str can convert to int or float only if it’s a valid number.
❌ Invalid conversions from str (like "abc") to int or float will throw
errors.
Control Statements in Python
Control statements are used to control the flow of a program based on
conditions or loops. They help the program decide what to execute next,
how many times to repeat tasks, and when to stop.
Python has three main types of control statements:
▶ 1. Conditional Statements (Decision Making)
These are used when you want to perform different actions based on
conditions.
1. if, elif, else
x = 10
if x > 0:
print("Positive number")
elif x == 0:
print("Zero")
else:
print("Negative number")
✔ Executes one block depending on conditions.
▶ 2. Looping Statements (Repetition)
These are used when you want to repeat a block of code multiple times.
🔹 for loop: Used to iterate over a sequence (like a list or range).
for i in range(5):
print(i)
Output:
01234
🔹 while loop: Repeats while a condition is true.
count = 0
while count < 5:
print(count)
count += 1
Output:
01234
✅ The range() Function in Python
The range() function is used when you want to generate a sequence of
numbers, often for looping with a for loop. It’s very useful when you want
to repeat something multiple times or when you want to go through
numbers one by one.
🔢 Basic Syntax of range()
range(stop)
range(start, stop)
range(start, stop, step)
✅ start – where the sequence begins (default is 0).
✅ stop – where the sequence ends (this number is not included).
✅ step – how much to increase each time (default is 1).
📚 Examples
1️⃣ range(stop): Generates numbers from 0 up to, but not including,
stop.
for i in range(5):
print(i)
Output:
0
1
2
3
4
2️⃣ range(start, stop): Starts from start and ends before stop.
for i in range(2, 6):
print(i)
Output:
2
3
4
5
3️⃣ range(start, stop, step): You can also control how much the number
increases each time.
for i in range(1, 10, 2):
print(i)
Output:
1
3
5
7
9
▶ 3. Control Flow Statements (Modify Loop Execution)
These control how and when loops terminate or skip iterations.
🔹 break: Stops the loop immediately.
for i in range(5):
if i == 3:
break
print(i)
Output:
012
🔹 continue: Skips the current iteration and moves to the next one.
for i in range(5):
if i == 2:
continue
print(i)
Output:
0134
✅ Modules and Packages in Python
In Python, as your programs grow bigger, it becomes important to
organize your code. That’s where modules and packages come in!
📦 What is a Module?
A module is simply a Python file (with a .py extension) that contains
Python code — like functions, classes, variables — that you can reuse in
other Python programs.
Example:
Let's say you create a file called math_utils.py with this code:
# math_utils.py
def add(x, y):
return x + y
def subtract(x, y):
return x - y
Now, you can use this module in another Python file like this:
# main.py
import math_utils
print(math_utils.add(5, 3)) # Output: 8
print(math_utils.subtract(5, 3)) # Output: 2
✅ Built-in Modules
Python comes with many modules you can use right away, such as:
math – for mathematical functions
random – for random number generation
datetime – for working with dates and times
Example:
import math
print(math.sqrt(16)) # Output: 4.0
✅ Python Packages – Explained Clearly
A package in Python is a way to organize related modules (Python files)
in a directory structure. It helps you group together functions, classes, and
other resources in a logical way so that your code is easier to maintain
and reuse.
📦 What is a Package?
A package is a folder that contains one or more Python files
(modules).
It must contain a special file named __init__.py to be recognized as a
package.
You can import modules from it in your Python programs.
✅ Why Use Packages?
✔ Organize code better
✔ Share functionality across multiple programs
✔ Avoid clutter in large projects
✔ Makes your project scalable and easy to navigate
📂 How to Create a Package – Step-by-Step Example
✅ Step 1 – Create the Folder Structure
Let's say you want to create a package called mytools with two modules:
math_tools.py and string_tools.py.
mytools/
__init__.py
math_tools.py
string_tools.py
✅ Step 2 – Create the __init__.py File
This file can be empty or used to initialize the package.
mytools/init.py
# This file can be empty or used to import modules
✅ Step 3 – Write Some Code in the Modules
mytools/math_tools.py
def add(x, y):
return x + y
def multiply(x, y):
return x * y
mytools/string_tools.py
def greet(name):
return f"Hello, {name}!"
def shout(text):
return text.upper()
✅ Step 4 – Use the Package in Another File
Create a file called main.py outside the mytools folder.
main.py
from mytools import math_tools, string_tools
result = math_tools.add(5, 3)
print("Sum:", result)
message = string_tools.greet("Jeeva")
print(message)
Output:
Sum: 8
Hello, Jeeva!
✅ Additional Notes
1. ✅ The __init__.py file signals that the folder is a package.
2. ✅ You can import the whole module or just specific functions.
3. ✅ Packages are used widely in professional projects to structure
code.
📂 Folder Structure Overview
✅ How to Run It
1. Save the files with the structure above.
2. Open your terminal or command prompt.
3. Run the main.py file using:
4. python main.py
📌 Real-World Example
Packages like numpy, pandas, and matplotlib are used in data
science.
Web frameworks like Flask and Django are organized as packages.
Example Usage:
Used like this in a program
✅ Date and Time Operations in Python – Explained
Python provides two powerful modules to work with date and time:
1. datetime module – Used to manipulate dates and times.
2. time module – Provides time-related functions like timestamps and
formatting.
Let’s go through them step by step with examples similar to what you
shared.
📆 1. Using the datetime Module: The datetime module helps you work
with dates easily.
✅ Example: Get Today’s Date and Format It
from datetime import date
# Get today's date
now = date.today()
# Format the date as month-day-year
print("Date:", now.strftime("%m-%d-%y"))
# Print day of the week
print("Day of Week:", now.strftime("%A"))
# Print full month name
print("Month:", now.strftime("%B"))
Sample Output:
Date: 09-07-25
Day of Week: Sunday
Month: September
✅ Example: Calculate Difference Between Two Dates
from datetime import date
# Today's date
now = date.today()
# Some earlier date
then = date(2025, 8, 1)
# Difference between dates
timediff = now - then
# Number of days between them
print("Days between dates:", timediff.days)
⏱ 2. Using the time Module
The time module helps you access the system time and format it.
✅ Example: Get the Current Time
import time
# Get current time in seconds since epoch
nowtime = time.time()
# Convert it into local time structure
localtime = time.localtime(nowtime)
print("Local Time Structure:", localtime)
Output:
Local Time Structure: time.struct_time(tm_year=2025, tm_mon=9,
tm_mday=7, tm_hour=16, tm_min=30, tm_sec=45, tm_wday=6,
tm_yday=250, tm_isdst=0)
✅ Example: Get a Readable Time Format
import time
nowtime = time.time()
# Convert to human-readable string
print("Current Time:", time.asctime(time.localtime(nowtime)))
Output:
Current Time: Sun Sep 7 16:30:45 2025
✅ Example: Format Time Using strftime
import time
print(time.strftime("The date is %d-%m-%y. Today is a %A. It is %H hours,
%M minutes and %S seconds now."))
Output:
The date is 07-09-25. Today is Sunday. It is 16 hours, 30 minutes and 45
seconds now.
📜 Common Formatting Codes for strftime
Cod
Meaning
e
%d Day of the month (01–31)
Month as a number (01–
%m
12)
Year without century (00–
%y
99)
%Y Year with century (2025)
Full weekday name
%A
(Sunday)
%B Full month name
Cod
Meaning
e
(September)
Hour in 24-hour format
%H
(00–23)
%M Minutes (00–59)
%S Seconds (00–59)
✅ Summary
✔ Use datetime.date.today() to get today’s date.
✔ Use strftime() to format date and time in different ways.
✔ Subtract dates to find the difference in days.
✔ Use time.time() to get the current timestamp.
✔ Convert timestamps to structured local time with time.localtime().
✔ Format time using time.strftime() for readable outputs.