0% found this document useful (0 votes)
13 views81 pages

Python Programming Basics Guide

The document is a study material for an Introduction to Python Programming course, detailing various data types including integers, floating-point numbers, and strings, along with their applications in banking and automotive contexts. It covers fundamental programming concepts such as variable assignment, boolean values, comparison operators, and control flow using conditions. The material includes syntax examples and practical applications to help students understand how to implement these concepts in Python.

Uploaded by

supreetdemo
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views81 pages

Python Programming Basics Guide

The document is a study material for an Introduction to Python Programming course, detailing various data types including integers, floating-point numbers, and strings, along with their applications in banking and automotive contexts. It covers fundamental programming concepts such as variable assignment, boolean values, comparison operators, and control flow using conditions. The material includes syntax examples and practical applications to help students understand how to implement these concepts in Python.

Uploaded by

supreetdemo
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

BMS Institute of Technology and Management

(An Autonomous Institution Affiliated to VTU, Belagavi)


Avalahalli, Doddaballapur Main Road, Bengaluru – 560119

DEPARTMENT OF COMPUTER
SCIENCE AND BUSINESS SYSTEMS

STUDY MATERIAL
INTRODUCTION TO
PYTHON PROGRAMMING

Prepared by :

Dr. Vishwa Kiran S


Associate Professor
Module1: Python Basics & Flow Control Control

 The Integer Data Type


What it is?
An integer is a whole number (no fractional part) and can be positive, negative, or zero.
 Examples: -10, 0, 25, 100000

When and Where it can be applied?


Use integers when dealing with:
 Countable quantities (e.g., number of customers, vehicle count, attempts)
 Values that do not need decimal precision

Applications:
 Banking:
 Account numbers
 Number of failed login attempts
 Number of transactions
 Automotive:
 Engine RPM
 Number of wheels
 Gear position

How to apply (syntax)?


# Declaration
x = 10
y = -200
z=0

# Operations
sum = x + 5

Examples
Banking:
failed_attempts = 3
print("Access blocked after", failed_attempts, "failed attempts.")

Automotive:
gear_position = 5
print("Current gear:", gear_position)

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 1
Module1: Python Basics & Flow Control Control

 The Floating-Point Data Type


What it is?
A floating-point (float) number is a number with a decimal point or written in exponential
form.
 Examples: 3.14, -0.99, 100.0, 1.2e3

When and Where it can be applied?


Use floats when:
 Decimal precision is required
 Measuring or computing with accuracy
Applications:
 Banking:
 Interest rate (e.g., 6.5%)
 Account balance (e.g., ₹1325.75)
 Automotive:
 Fuel efficiency (km/l)
 Temperature readings (87.3 °C)
 Speed (65.5 km/h)

How to apply (syntax)?


# Declaration
balance = 12345.67
temperature = -5.3

# Operations
new_balance = balance + 100.25

Examples
Banking:
balance = 4321.50
interest_rate = 5.5 # percentage
interest = (balance * interest_rate) / 100
print("Interest:", interest)

Automotive:
engine_temp = 92.7
speed = 64.3
print("Speed:", speed, "km/h")

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 2
Module1: Python Basics & Flow Control Control

 Summary Table
Feature Integer (int) Floating-point (float)
Values Whole numbers Decimal numbers
Examples 10, -3, 0 3.14, -0.01, 1.2e3
Account No, Attempt
Use Case (Banking) Balance, Interest rate
Count
Use Case (Automotive) Gear position, RPM Speed, Fuel %, Engine Temp
Operations +, -, *, //, %, ** +, -, *, /, **

 String Data Type


What it is?
A string is a sequence of characters enclosed in single quotes (' ') or double quotes (" "). It can
include letters, digits, spaces, and symbols.

When and where it can be applied?


Use strings to represent textual data like:
 Names, addresses, messages, identifiers, codes, logs, timestamps
Applications:
 Banking:
 Customer names, account types, transaction remarks
 Automotive:
 Vehicle status logs, error messages, model names

How to apply (syntax)?


# Declaration
name = "Ravi"
vehicle_model = 'Maruti Swift'

Examples
Banking:
account_type = "Savings"
customer_name = "Anjali"
print("Account Type:", account_type)

Automotive:
model = "Hyundai Verna"
status = "Engine Check OK"
print("Vehicle Model:", model)

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 3
Module1: Python Basics & Flow Control Control

 String Concatenation
What it is?
Concatenation means joining two or more strings using the + operator.

When and where it can be applied?


Used to:
 Build messages
 Combine identifiers (e.g., user IDs or logs)
 Format output dynamically
Applications:
 Banking:
 Combine customer name with messages
 Automotive:
 Combine sensor name with alert message

How to apply (syntax)?


full_name = first_name + " " + last_name
message = "Speed is " + str(speed) + " km/h"

Examples
Banking:
first_name = "Rahul"
last_name = "Kumar"
welcome_msg = "Hello, " + first_name + " " + last_name
print(welcome_msg)

Automotive:
sensor = "Temperature"
value = "85°C"
alert = sensor + " reading is " + value
print(alert)

 String Replication
What it is?
Replication means repeating a string multiple times using the * operator.

When and where it can be applied?


Used for:
 Formatting output (lines, headers, separators)

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 4
Module1: Python Basics & Flow Control Control
 Simulation messages or placeholders
Applications:
 Banking:
 Print lines in receipts or reports
 Automotive:
 Repeat status or test messages in logs

How to apply (syntax)?


separator = "-" * 30
print(separator)

Examples
Banking:
print("Transaction Receipt")
print("=" * 40)

Automotive:
print("Diagnostic Log")
print("*" * 50)

 Summary Table
Concept Operator Syntax Example Domain Example
String Declaration – name = "Anil" "account_type = 'Savings'"
String Concatenation + "Hello " + name "Engine Temp: " + temp
String Replication * "=" * 20 "*" * 50 # log separator"

 Storing Values in Variables


What it is?
Variables are named containers used to store values (data) like numbers, text, etc., in Python.
You can assign any type of value to a variable.

When and Where it can be Applied?


Use variables when:
 You need to store intermediate results
 You want to reuse data or track state of a system
Applications:
 Banking:
 Store customer balance, interest rate, account status

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 5
Module1: Python Basics & Flow Control Control
 Automotive:
 Store engine temperature, speed, gear position

How to Apply (Syntax)?


balance = 5000 # Integer
account_type = "Savings" # String
engine_temp = 95.6 # Float

Examples
Banking:
customer_name = "Arjun"
account_balance = 12000

Automotive:
speed = 65.4
gear = 3
status = "Running"

 Your First Program


What it is?
A simple Python script that demonstrates variable assignment and output using print()
function.

When and Where it can be Applied?


 Ideal for beginners
 Foundation for debugging, testing
 Forms basis of larger programs
Applications:
 Banking: Print account summary
 Automotive: Display vehicle diagnostic summary

How to Apply (Syntax)?


# First Program
name = "Ravi"
print("Welcome", name)

Examples
Banking:
account_holder = "Meera"
balance = 8750
print("Account Holder:", account_holder)
print("Available Balance:", balance)

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 6
Module1: Python Basics & Flow Control Control
Automotive:
vehicle = "Tata Nexon"
speed = 75.3
print("Vehicle:", vehicle)
print("Speed:", speed, "km/h")

 Dissecting Your Program


What it is?
This means breaking down each part of your Python program to understand what it does line-
by-line.

When and Where it can be Applied?


 Use this technique to learn and debug code.
 Essential in training, education, and testing scenarios.
Applications:
 Banking: Understanding transaction logic
 Automotive: Diagnosing logic for error detection or status update

How to Apply?
Take this example:
# Program to calculate total balance
name = "Amit" # Stores customer's name
balance = 10000 # Initial balance
deposit = 2500 # Amount to deposit
balance = balance + deposit # New balance after deposit
print("Hello", name) # Greeting message
print("Updated Balance:", balance) # Show updated balance

Examples with Dissection


Banking:
# Program to show balance update
name = "Amit" # Variable storing name
balance = 10000 # Original balance
deposit = 2500 # New deposit
balance += deposit # Update balance
print("Hello", name)
print("Updated Balance:", balance)

Automotive:
# Program to calculate safe speed range
car_model = "Hyundai i20"
speed = 70 # Current speed
max_safe_speed = 80
print("Car:", car_model)
print("Speed:", speed, "km/h")

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 7
Module1: Python Basics & Flow Control Control
if speed < max_safe_speed:
print("Status: Safe Driving")
else:
print("Warning: Over Speed!")

 Summary Table
Concept What it does Domain Use Example
Customer name,
Storing Values Assign data to variables name = "Asha"
Engine speed
Run simple code using Greet user, Show
First Program print("Hello", name)
print and vars status
Dissecting Debug
Explain each line of code balance += deposit
Program banking/vehicle logic

 Boolean Values
What it is?
Boolean values represent truth values:
 True
 False
They are used to control the flow of a program through decisions (conditions).

When and Where it Can Be Applied?


 When performing logical checks, comparisons, or deciding actions.
Applications:
 Banking:
 Check if balance is sufficient
 Validate login attempt
 Automotive:
 Detect if engine temperature is too high
 Check if headlights should be ON

How to Apply (Syntax)?


status = True
if status:
print("Proceed")

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 8
Module1: Python Basics & Flow Control Control

Examples
Banking:
is_verified = True
if is_verified:
print("Transaction Approved")

Automotive:
engine_on = False
if not engine_on:
print("Engine is off")

 Comparison Operators
What it is?
Used to compare two values and return a Boolean result (True or False).

Operator Meaning
== Equal to
!= Not equal to
> Greater than
< Less than
Greater than or equal
>=
to
<= Less than or equal to

When and Where it Can Be Applied?


Used in:
 if-else, while, for loops
 Any decision-making part of a program
Applications:
 Banking:
 Check if withdrawal amount is within balance
 Automotive:
 Check if speed is above safety limit

How to Apply (Syntax)?


balance = 5000
if balance > 1000:
print("Eligible for loan")

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 9
Module1: Python Basics & Flow Control Control

Examples
Banking:
balance = 3000
withdraw = 2500
if balance >= withdraw:
print("Withdrawal permitted")
else:
print("Insufficient funds")

Automotive:
speed = 90
if speed > 80:
print("Warning: Over-speeding")

Combined Use
Syntax:
if condition: # condition returns Boolean
do_something()

Example – Banking:
pin_entered = 1234
correct_pin = 1234
if pin_entered == correct_pin:
print("Access Granted")
else:
print("Invalid PIN")

Example – Automotive:
engine_temp = 105
if engine_temp > 100:
print("Engine Overheating Warning!")

 Summary Table
Concept Example Output Domain
Boolean Value True, False Flow control Both
== Equal To speed == 60 True/False Automotive
!= Not Equal status != "Active" True/False Banking
> Greater
balance > 5000 True/False Banking
Than
< Less Than temp < 100 True/False Automotive
>=, <= score >= 70 True/False Both

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 10
Module1: Python Basics & Flow Control Control

 Boolean Operators
What it is?
Boolean operators are used to combine or manipulate boolean values. They return either
True or False.

Operator Description Example


True if both conditions are
and A and B
true
or True if at least one is true A or B
not Inverts the boolean value not A

When and Where it Can Be Applied?


 To create complex conditions in decision-making.
 When you need multiple checks in one statement.
Applications:
 Banking:
 Check if balance is sufficient and account is active.
 Check if user is admin or manager.
 Automotive:
 Check if speed > 100 and temperature > 90.
 Alert if door is open or seatbelt is not worn.

How to Apply (Syntax)?


if condition1 and condition2:
# do something

Examples
Banking:
balance = 15000
account_status = "Active"

if balance > 10000 and account_status == "Active":


print("Eligible for premium account")

Automotive:
speed = 105
engine_temp = 98

if speed > 100 and engine_temp > 95:


print("Alert: High Speed and Engine Heat!")

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 11
Module1: Python Basics & Flow Control Control

 Mixing Boolean and Comparison Operators


What it is?
You can combine comparisons using boolean operators to form compound conditions.
Example:
if (balance >= 5000 and account_type == "Savings"):

When and Where it Can Be Applied?


 Useful in nested validations
 Helps shorten logic with readable conditions
Applications:
 Banking:
 Apply interest only if balance ≥ ₹5000 and account is “Savings”
Automotive:
 Alert driver if (seatbelt not fastened) or (door not closed)

How to Apply (Syntax)?


if (comparison1) and (comparison2):
action()

Examples
Banking:
balance = 6000
account_type = "Savings"
kyc_verified = True

if balance > 5000 and account_type == "Savings" and kyc_verified:


print("Eligible for Interest Credit")
Automotive:
door_closed = False
seatbelt_fastened = True

if not door_closed or not seatbelt_fastened:


print("Warning: Safety Protocol Violation")

 Summary Table
Expression Result Notes
True and True True Both must be true
True and False False One false makes entire False
False or True True At least one true makes it True
not False True Negation of False
balance > 5000 and kyc_verified Varies Used in banking
speed > 90 and engine_temp > 95 Varies Used in automotive

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 12
Module1: Python Basics & Flow Control Control
Tip: Use Parentheses for Clarity
if (speed > 90 and engine_temp > 100) or driver_drowsy:
print("Activate Auto-Brake System")

 Condition
What it is?
A condition is an expression that evaluates to either True or False.
It determines whether a block of code should be executed or skipped.

When and Where it Can Be Applied?


 Anytime decision-making is needed in a program.
Applications:
 Banking:
 If balance > withdrawal amount → allow withdrawal
 Automotive:
 If speed > speed_limit → issue warning

How to Apply (Syntax)?


if condition:
# block of code

Examples
Banking:
balance = 12000
withdraw = 5000
if balance >= withdraw:
print("Withdrawal Approved")

Automotive:
speed = 90
if speed > 80:
print("Warning: Over Speeding!")

 Block of Code
What it is?
A block of code is a group of statements that run together under a condition, defined by
indentation (usually 4 spaces in Python).

When and Where it Can Be Applied?


 Blocks are used under if, elif, else, for, while etc.
 Only executes if the associated condition is True.

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 13
Module1: Python Basics & Flow Control Control

How to Apply (Syntax)?


if condition:
# This is a block (4-space indent)
do_something()
do_something_else()

Note: In Python, indentation is not optional – it defines the block.

Examples
Banking:
balance = 8000
min_balance = 5000

if balance >= min_balance:


print("Eligible for Loan")
print("Proceed to next step")

Automotive:
engine_temp = 102

if engine_temp > 100:


print("Overheating Detected")
print("Activating Cooling System")

 Summary Table
Element Role in Flow Control Example (Banking) Example (Automotive)
Decides whether code
Condition if balance > 5000: if speed > 80:
block runs
Executes only if
Block print("Loan Approved") print("Turn on Fan")
condition is True
Defines code block 4 spaces or a tab under if, Required under all
Indentation
scope else, etc. control structures

 Program Execution
What it is?
Program execution in Python refers to the sequential line-by-line interpretation and
execution of code by the Python interpreter.

When and Where It Can Be Applied?


 Applied always when running a Python script or module.
 The interpreter starts at the first line and proceeds downward, unless altered by flow
control, function calls, loops, or exceptions.

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 14
Module1: Python Basics & Flow Control Control
Applications:
 Banking: Transaction processing based on steps
 Automotive: Sequential checking of sensors and actuators

How to Use:
Python programs can be executed:
bash
[Link]

Example:
print("Program Started")
balance = 5000
print("Balance:", balance)

 Flow Control Statements


Flow control changes the natural top-to-bottom execution of a program using conditions.

 if Statement
What it is?
The if statement checks a single condition, and executes the block if it evaluates to True.

When and Where to Use?


Use when there is one condition to verify.
Applications:
 Banking: Check if user is verified
 Automotive: Check if engine temperature is above threshold

Syntax:
if condition:
# block of code

Examples:
Banking:
balance = 10000
if balance > 0:
print("Proceed with transaction")

Automotive:
speed = 90
if speed > 80:
print("Over-speeding detected!")

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 15
Module1: Python Basics & Flow Control Control

 if-else Statement
What it is?
Handles two branches — one block runs if condition is True, the else block runs if it's False.

When and Where to Use?


When you need to take action in both outcomes.
Applications:
 Banking: Withdraw success or show insufficient funds
 Automotive: Alert or confirm normal engine condition

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

Examples:
Banking:
balance = 3000
withdraw = 4000

if balance >= withdraw:


print("Transaction Approved")
else:
print("Insufficient Funds")

Automotive:
engine_temp = 85

if engine_temp > 100:


print("Overheating Warning!")
else:
print("Engine Temperature Normal")

 if-elif-else Ladder
What it is?
Used when there are multiple conditions, checked one-by-one.

When and Where to Use?


When you need multi-level decision making.

Applications:
 Banking: Interest rate based on balance ranges
 Automotive: Gear suggestion based on speed

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 16
Module1: Python Basics & Flow Control Control

Syntax:
if condition1:
# block 1
elif condition2:
# block 2
else:
# block N

Examples:
Banking:
balance = 120000

if balance < 5000:


print("No Interest")
elif balance < 100000:
print("Interest Rate: 4%")
else:
print("Interest Rate: 6%")
Automotive:
speed = 45

if speed < 20:


print("Gear 1")
elif speed < 40:
print("Gear 2")
elif speed < 60:
print("Gear 3")
else:
print("Gear 4 or 5")

Summary Table
Statement Description Banking Example Automotive Example
Executes when condition
if if balance > 0: if speed > 80:
is True
Two outcomes Approve or reject Show warning or OK
if-else
(True/False) withdrawal status
Multiple decision Interest based on Gear suggestion based on
if-elif-else
branches balance speed

 while Loop
What it is?
The while loop repeatedly executes a block of code as long as a condition is True.

When and Where to Use?


 When you don’t know the exact number of iterations in advance.
 Best suited for sensor monitoring, login attempts, or repeated actions until a
condition changes.

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 17
Module1: Python Basics & Flow Control Control
Applications:
 Banking: Allow up to 3 login attempts
 Automotive: Monitor sensor value until a threshold is reached

Syntax:
while condition:
# block of code

Examples
Banking:
attempts = 0
while attempts < 3:
pin = input("Enter PIN: ")
if pin == "1234":
print("Access Granted")
break
else:
print("Wrong PIN")
attempts += 1

Automotive:
engine_temp = 90
while engine_temp < 100:
print("Engine Temperature:", engine_temp)
engine_temp += 2

 break Statement
What it is?
Used to immediately exit a loop (either for or while) when a condition is met.

When and Where to Use?


 To stop execution prematurely when some condition is met.
Applications:
 Banking: Stop login attempts after correct PIN
 Automotive: Stop checking sensor when critical value is hit

Syntax:
while condition:
if some_condition:
break

Examples
Banking:
while True:
pin = input("Enter PIN: ")

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 18
Module1: Python Basics & Flow Control Control
if pin == "4321":
print("Access granted")
break
print("Try again")

Automotive:
speed = 0
while True:
speed += 10
if speed > 100:
print("Critical Speed Reached:", speed)
break

 continue Statement
What it is?
Skips the current iteration and jumps to the next cycle of the loop.

When and Where to Use?


 When you want to skip specific conditions and keep looping.
Applications:
 Banking: Skip transactions below ₹1000 while summarizing
 Automotive: Ignore invalid sensor values like -1

Syntax:
while condition:
if skip_condition:
continue
# code that runs if not skipped

Examples
Banking:
transactions = [500, 1200, 8000, 300]
i=0
while i < len(transactions):
if transactions[i] < 1000:
i += 1
continue
print("Processed:", transactions[i])
i += 1
Automotive:
sensor_data = [70, -1, 90, 85]
i=0
while i < len(sensor_data):
if sensor_data[i] == -1:
i += 1
continue
print("Valid Sensor Value:", sensor_data[i])
i += 1

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 19
Module1: Python Basics & Flow Control Control

Summary Table
Concept Description Use in Banking Use in Automotive
Loops while condition is Monitor sensor until safe
while Allow login attempts
True value
Exit on correct PIN
break Exits the loop early Stop loop at critical speed
entry
Ignore small
continue Skips current loop iteration Skip invalid sensor values
transactions

 for Loops
What it is?
A for loop is used to iterate over a sequence (like a list, tuple, string, or range) and execute a
block of code once for each item in that sequence.

When and Where to Use?


 When the number of iterations is known or countable
 Efficient for iterating through items in a list or performing an action a fixed number
of times
Applications:
 Banking: Loop over transactions or customer records
 Automotive: Loop through sensor values, log entries

Syntax:
for variable in sequence:
# block of code

Examples
Banking:
transactions = [2000, -1500, 3000, -500]
for txn in transactions:
print("Transaction Amount:", txn)

Automotive:
speeds = [40, 50, 65, 80, 90]
for speed in speeds:
print("Speed logged:", speed, "km/h")

 range() Function
What it is?
The range() function returns a sequence of numbers, starting from a start (default 0) to a stop
(exclusive), with a defined step (default 1).

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 20
Module1: Python Basics & Flow Control Control

When and Where to Use?


 When you want to loop a fixed number of times
 Best used with for loops for indexed iteration
Applications:
 Banking: Generate monthly reports for N months
 Automotive: Log data every N seconds or simulate sensor readings

Syntax:
range(stop)
range(start, stop)
range(start, stop, step)

Examples
Banking:
# Print statement for 6 months
for month in range(1, 7):
print("Month", month, ": Interest credited")

Automotive:
# Simulate RPM from 1000 to 5000 in steps of 1000
for rpm in range(1000, 6000, 1000):
print("Engine RPM:", rpm)

 Summary Table
Concept Description Banking Use Case Automotive Use Case
Iterates over items in Iterate through account Iterate through speed or
for loop
a sequence transactions RPM values
Generates a sequence Loop over months, Simulate time steps,
range()
of numbers customer IDs sensor values
range(5) 0 to 4 5 transactions 5 sensor readings
RPM levels: 1000, 2000,
range(1, 4) 1 to 3 Generate 3-month report
3000
Even numbers
range(0, 10, 2) Report every 2 days Speed simulation in steps
between 0 and 9

Combined Example:
Banking:
# Simulate a mini statement
amounts = [5000, -2000, -500, 7000]
for i in range(len(amounts)):
print(f"Transaction {i+1}: ₹{amounts[i]}")

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 21
Module1: Python Basics & Flow Control Control
Automotive:
# Simulate log of temperature readings
for i in range(1, 6):
print("Sensor Reading", i, ": Temperature OK")

What is range() with start, stop, step?


The range() function in Python is used to generate a sequence of numbers.
It can accept up to 3 arguments:

range(start, stop, step)


 start – starting value (inclusive)
 stop – ending value (exclusive)
 step – difference between each number (default is +1)
If only 1 value is passed, it’s treated as stop, and start defaults to 0.

When and Where It Can Be Applied


Used in controlled loops, such as:
 Fixed repetition
 Skipping values in a pattern
 Creating number sequences for reports, logs, or time intervals
Applications:
 Banking:
 Generate transaction IDs
 Create monthly interest schedules
 Automotive:
 Simulate RPM, speed increases
 Periodic data logging (e.g., every 5 seconds)

How to Apply: Syntax & Explanation


range(stop)
for i in range(5): # Equivalent to range(0, 5)
print(i)

Output: 0 1 2 3 4

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

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 22
Module1: Python Basics & Flow Control Control
Output: 2 3 4 5

range(start, stop, step)


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

Output: 10 8 6 4 2

Domain Examples
Banking Example 1: Generate 6-month report
for month in range(1, 7):
print("Month", month, ": Interest credited")

Banking Example 2: Transaction ID skipping


for txn_id in range(1001, 1011, 2): # ID steps of 2
print("Transaction ID:", txn_id)

Automotive Example 1: Simulate increasing speed


for speed in range(0, 101, 20): # From 0 to 100 in steps of 20
print("Speed:", speed, "km/h")

Automotive Example 2: RPM deceleration


for rpm in range(6000, 1000, -1000):
print("RPM:", rpm)

 Summary Table
Syntax Description Example Output
range(5) 0 to 4 01234
range(2, 6) 2 to 5 2345
range(1, 10, 2) Odd numbers from 1 to 9 1 3 5 7 9
range(10, 0, -2) Countdown from 10 to 2 10 8 6 4 2
range(start, stop, 1) Default stepping Increments by 1

 Importing Modules
What it is?
A module is a file containing Python code (functions, classes, or variables).
Importing a module allows you to reuse code from built-in libraries or custom scripts.

When and Where to Use?


 When you want to organize code, reuse functionality, or access standard libraries
(e.g., math, datetime, os, random)
 Helps with modularity, reusability, and clarity

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 23
Module1: Python Basics & Flow Control Control
Applications:
 Banking:
 Use datetime to calculate interest periods
 Use json to store user profiles securely
 Automotive:
 Use time to simulate sensor readings at intervals
 Use math for calculations (e.g., fuel efficiency)

How to Apply (Syntax)


import module_name

You can then access its functions using:


module_name.function_name()

Examples
Banking – Using datetime:
import datetime

today = [Link]()
print("Date of Transaction:", today)

Automotive – Using time:


import time

for i in range(3):
print("Sensor Reading", i)
[Link](2) # waits for 2 seconds

 from ... import ... Statement


What it is?
A shortcut to import only specific parts (functions, classes, variables) from a module.
It avoids the need to use the module prefix.

When and Where to Use?


 When only a specific function or class is needed
 Makes code cleaner and more readable
Applications:
 Banking:
 Import only date from datetime for transactions

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 24
Module1: Python Basics & Flow Control Control
 Automotive:
 Import only sleep from time module to simulate delays

How to Apply (Syntax)


from module_name import function_name
You can now use:
function_name() # No module prefix needed

Examples
Banking – Use from datetime import date:
from datetime import date

print("Today's Date:", [Link]())

Automotive – Use from time import sleep:


from time import sleep

for i in range(3):
print("Monitoring engine...")
sleep(1)

 Summary Table
Syntax Description Example
import module Imports the whole module import datetime
Access function using
[Link]() [Link]()
module name
from module import Imports only the required
from time import sleep
function function
function() Use directly without prefix sleep(2)

 [Link]()
What it is?
[Link]() is a function provided by Python’s sys module.
It is used to immediately terminate the execution of a Python program before it naturally
ends.

When and Where to Use?


 When a critical error or invalid condition occurs
 When you want to forcefully stop execution under specific scenarios

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 25
Module1: Python Basics & Flow Control Control
Applications:
 Banking:
 Exit program if login fails after 3 attempts
 Stop transaction processing if KYC is not verified
 Automotive:
 Stop diagnostics if essential sensor data is missing
 Exit loop if hardware not responding

How to Apply (Syntax)


Step-by-step:
import sys

if condition_to_exit:
[Link]("Reason for exiting")

The message in [Link]("...") is optional and is printed to stderr.

Banking Domain Example


import sys

pin_attempts = 0

while pin_attempts < 3:


pin = input("Enter your PIN: ")
if pin == "1234":
print("Access granted")
break
else:
print("Incorrect PIN")
pin_attempts += 1

if pin_attempts == 3:
[Link]("Too many failed attempts. Program terminated.")

Automotive Domain Example


import sys

sensor_connected = False

if not sensor_connected:
[Link]("Error: Critical sensor not connected. Aborting diagnostics.")
else:
print("Running diagnostics...")

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 26
Module1: Python Basics & Flow Control Control

 Summary Table
Concept Description Example Output
Terminates the program Too many failed attempts. Program
[Link]()
immediately terminated.
On error, failed login, missing
Use case Security breach or hardware fault
hardware
Requires import sys Must be called before use

Tip:

Use [Link]() inside:


 Loops
 if statements
 Error-handling blocks (try...except)

Objective:
Let the user guess a number between 1 and 10.
The program:
 Randomly selects a number
 Prompts user repeatedly until correct
 Shows a success message or exits after limited attempts

What It Is?
A beginner-friendly, interactive program that demonstrates core Python logic using
conditions, loops, and modules.

When and Where to Use


This kind of game:
 Is great for learning flow control
 Can be adapted for secure input, attempt limits, or random simulations
 Real-world use:
 Banking: Security PIN guessing simulation
 Automotive: Password entry for diagnostics

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 27
Module1: Python Basics & Flow Control Control

How to Apply – Code Example


import random

secret_number = [Link](1, 10)


attempts = 0
max_attempts = 5

print("Welcome to Guess the Number Game!")


print("I'm thinking of a number between 1 and 10.")

while attempts < max_attempts:


guess = int(input("Take a guess: "))
attempts += 1

if guess < secret_number:


print("Too low!")
elif guess > secret_number:
print("Too high!")
else:
print("Good job! You guessed it in", attempts, "attempt(s).")
break

if guess != secret_number:
print("Sorry, you've run out of attempts. The number was", secret_number)

Banking Variant – PIN Guess Simulation


import random
import sys

correct_pin = str([Link](1000, 9999))


print("Debug (for testing):", correct_pin)

for attempt in range(3):


entered_pin = input("Enter 4-digit PIN: ")
if entered_pin == correct_pin:
print("Access granted.")
break
else:
print("Incorrect PIN.")

if entered_pin != correct_pin:
[Link]("Card Blocked. Too many failed attempts.")

Automotive Variant – Diagnostic Access Code


import random

access_code = [Link](100, 999)


print("Enter the correct code to run diagnostics.")

for attempt in range(3):


code = int(input("Enter code (between 100–999): "))
if code == access_code:
print("Diagnostic Mode Enabled")
break
else:
print("Incorrect Code")

if code != access_code:
print("Access denied. Try again later.")

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 28
Module1: Python Basics & Flow Control Control

 Summary of Concepts Used


Concept Description
[Link]() Generates a random integer
while/for Used for limited attempts
input() To accept user input
if/elif/else Decision-making based on guess
Stop loop or program on
break/[Link]()
conditions

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 29
Module2: Functions & Lists

 Functions in Python
What it is?
A function is a reusable block of code that performs a specific task.
Python functions are defined using the def keyword.

When and Where to Use Functions?


Functions are useful when:
 A task is repeated often
 You want to modularize your code
 You want to keep code readable, reusable, and testable
Applications:
Banking:
 Calculate interest
 Verify PIN
 Generate transaction summary
Automotive:
 Calculate fuel efficiency
 Check sensor status
 Control device behavior

How to Apply: Syntax and Examples


 Defining a Function with Parameters
def function_name(parameter1, parameter2):
# block of code

Banking:
def calculate_interest(balance, rate):
interest = (balance * rate) / 100
print("Interest:", interest)
Automotive:
def fuel_efficiency(distance, fuel_used):
efficiency = distance / fuel_used
print("Fuel Efficiency:", efficiency, "km/l")

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 30
Module2: Functions & Lists
 Return Values using return
What it is?
The return statement ends the function and sends back a result to the caller.
Syntax:
def function_name(params):
# processing
return result

Banking Example:
def calculate_balance(initial, deposit, withdrawal):
return initial + deposit - withdrawal

new_balance = calculate_balance(1000, 500, 200)


print("Updated Balance:", new_balance)

Automotive Example:
def engine_status(temp):
if temp > 100:
return "Overheating"
else:
return "Normal"

print(engine_status(95)) # Output: Normal

 Summary Table

Feature Description Example


def keyword Defines a function def greet():
Parameters Inputs passed to function def interest(p, r):
return
Sends result back to the caller return p * r / 100
statement
Function call Executes the function greet() or calculate_balance()

 Combined Example
Banking – EMI Calculator Function
def calculate_emi(principal, rate, months):
emi = (principal * rate * (1 + rate) ** months) / ((1 + rate) ** months - 1)
return round(emi, 2)

emi = calculate_emi(500000, 0.01, 12)


print("Monthly EMI:", emi)

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 31
Module2: Functions & Lists
Automotive – Speed Classification
def classify_speed(speed):
if speed < 40:
return "Slow"
elif speed < 80:
return "Moderate"
else:
return "Fast"
print(classify_speed(90)) # Output: Fast

 The None Value


What it is?
 None is a special constant in Python that represents the absence of a value or null
value.
 Returned implicitly by functions that do not use return.

When and Where to Use?


 To initialize a variable before assigning a meaningful value
 To represent empty database fields, sensor disconnection, or incomplete
transactions
Applications:
 Banking: If a customer hasn't submitted KYC, status can be None
 Automotive: If a sensor is not yet initialized

Syntax:
value = None

Examples
Banking:
kyc_status = None
if kyc_status is None:
print("KYC not submitted")

Automotive:
engine_temp = None
if engine_temp is None:
print("Sensor data not received")

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 32
Module2: Functions & Lists

 Keyword Arguments and the print() Function


What it is?
 Keyword arguments allow you to specify parameters by name, not just by position.
 The print() function in Python supports keyword arguments like:
 sep – separator between items
 end – what to print at the end (default is newline)

When and Where to Use?


 Use keyword arguments to improve clarity, flexibility, and custom formatting.

Applications:
 Banking: Display account info with formatting
 Automotive: Print logs in a readable format

Syntax:
print("A", "B", sep="-", end=" DONE\n")

Examples
Banking:
print("Name", "Balance", sep=": ", end=" ✅\n")

Automotive:
print("Speed", 80, "km/h", sep=" - ", end=" | Logged\n")

 Local and Global Scope


What it is?
 Local variable: Defined inside a function and accessible only within that function.
 Global variable: Defined outside all functions and accessible throughout the script.

When and Where to Use?


 Use local scope to avoid name conflicts.
 Use global scope for shared configuration or system-wide variables.
 Avoid overusing global, as it reduces modularity.

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 33
Module2: Functions & Lists
Applications:
 Banking: Shared interest rate (global); user-specific transaction amount (local)
 Automotive: Global threshold values; local sensor readings

Syntax:
# Global variable
x = 10

def example():
y=5 # Local variable
print(x, y)

Global Keyword:
def update_rate():
global rate
rate = 0.06

Examples
Banking:
interest_rate = 0.05 # Global

def calculate_interest(balance):
return balance * interest_rate # Access global inside function

Automotive:
default_speed = 60 # Global

def adjust_speed(sensor_speed):
adjusted = sensor_speed + 10 # Local variable
print("Adjusted Speed:", adjusted)

 Summary Table
Concept Description Banking Use Case Automotive Use Case
Null/undefined
None kyc_status = None sensor_data = None
value
Keyword args Custom output
sep=": ", end="✓\n" print("RPM", rpm, sep="-")
in print formatting
Variable inside
Local Scope balance in calculate() speed inside adjust_speed()
function
Variable outside default_speed,
Global Scope interest_rate
functions temp_threshold

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 34
Module2: Functions & Lists

 The global Statement


What it is?
The global statement allows you to modify a variable defined in the global scope from
within a function.

When and Where to Use?


 When you need a function to change a global variable
 When managing shared states (not generally recommended unless necessary)
Applications:
 Banking: Update interest rate across multiple functions
 Automotive: Adjust global system settings like max_speed

Syntax:
count = 0

def increment():
global count
count += 1

Examples:
Banking:
interest_rate = 0.05

def update_rate():
global interest_rate
interest_rate = 0.06

Automotive:
threshold = 100

def override_threshold():
global threshold
threshold = 90

 Exception Handling
What it is?
Python uses try-except blocks to catch and handle errors gracefully during program
execution.

When and Where to Use?


 To prevent crashes due to runtime errors like invalid input or missing files

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 35
Module2: Functions & Lists
 Handle specific exceptions (ValueError, ZeroDivisionError, etc.)

Applications:
 Banking: Handle invalid input while entering PIN or transaction amount
 Automotive: Handle missing sensor values or communication errors

Syntax:
try:
# risky code
except SomeError:
# handle error
else:
# optional, runs if no error
finally:
# optional, always runs

Examples:
Banking:
try:
amount = float(input("Enter withdrawal amount: "))
print("Processing ₹", amount)
except ValueError:
print("✅ Invalid amount entered.")

Automotive:
try:
speed = int(input("Enter speed: "))
print("Logged speed:", speed)
except ValueError:
print("⚠️ Speed must be a number.")

 A Short Program: Guess the Number (with global and


try-except)
Program Objective:
Let the user guess a number between 1 and 10
 Use random module
 Use global for attempt tracking
 Use try-except to handle input errors

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 36
Module2: Functions & Lists
Full Program:
import random
import sys

attempts = 0 # Global variable

def guess_game():
global attempts
secret_number = [Link](1, 10)
max_attempts = 5

print(" Guess the Number (1 to 10)")

while attempts < max_attempts:


try:
guess = int(input("Your guess: "))
except ValueError:
print("✅ Please enter a valid number.")
continue

attempts += 1

if guess < secret_number:


print("Too low!")
elif guess > secret_number:
print("Too high!")
else:
print(f" Correct! You guessed it in {attempts} attempt(s).")
return

print(f" Game over. The number was {secret_number}.")


[Link]()

guess_game()

 Summary Table
Concept Description Banking Use Case Automotive Use Case
Modify global vars from Update interest rates
global Adjust global thresholds
functions globally
Handle invalid input Handle sensor failure or
try-except Catch runtime errors
(amount, PIN) bad data
Card block after multiple
[Link]() Exit program early Abort diagnostics
failures
Guess game Loop, condition, Simulate command
Simulate PIN guessing
usage exception, global verification

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 37
Module2: Functions & Lists

 The List Data Type


What it is?
A list is an ordered, mutable collection that holds multiple items (values) in a single variable.
Lists can contain integers, strings, floats, or even other lists.

When and Where It Can Be Applied?


 When you need to store and manipulate a collection of related values (e.g.,
transactions, speed logs).
 Useful in data analysis, logs, dashboards, and reports.

How to Apply?
Banking:
transactions = [1000, -500, 2000, -300]

Automotive:
speed_log = [45, 52, 60, 72]

 Getting Individual Values in a List with Indexes


What it is?
Accessing items in a list using index numbers (starting from 0).

When and Where It Can Be Applied?


 When you want to fetch or modify a specific item from the list.

How to Apply?
Banking:
print(transactions[2]) # Output: 2000

Automotive:

print(speed_log[0]) # Output: 45

 Negative Indexes
What it is?
Negative indexes count from the end of the list. -1 refers to the last item, -2 to second last, etc.

When and Where It Can Be Applied?


 When you need to quickly access recent or last entries.

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 38
Module2: Functions & Lists
How to Apply?
Banking:
last_transaction = transactions[-1]

Automotive:
last_speed = speed_log[-1]

 Getting a List from Another List with Slices


What it is?
You can use slicing to extract a subset of a list: list[start:end].

When and Where It Can Be Applied?


 When you want to analyze or display only part of the data.

How to Apply?
Banking:
recent_txns = transactions[-3:]

Automotive:
first_two_speeds = speed_log[0:2]

 Getting a List’s Length with len()


What it is?
Returns the number of items in a list.

When and Where It Can Be Applied?


 When checking the total number of events or entries recorded.

How to Apply?
Banking:
print(len(transactions)) # Total number of transactions

Automotive:
print(len(speed_log)) # Total speed readings

 Changing Values in a List with Indexes


What it is?
Allows you to modify a specific element in the list using its index.

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 39
Module2: Functions & Lists
When and Where It Can Be Applied?
 When a data value needs to be corrected or updated.

How to Apply?
Banking:
transactions[1] = -450

Automotive:
speed_log[2] = 65

 List Concatenation and Replication


What it is?
 Concatenation (+): Combines two lists
 Replication (*): Repeats elements of a list

When and Where It Can Be Applied?


 Concatenation for merging reports or logs
 Replication for simulating repeated inputs

How to Apply?
Banking:
all_txns = old_txns + new_txns

Automotive:
simulated_data = [70] * 5

 Removing Values from Lists with del


What it is?
The del statement removes an element at a specific index.

When and Where It Can Be Applied?


 When clearing obsolete or incorrect entries.

How to Apply?
Banking:
del transactions[2]

Automotive:
del speed_log[0]

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 40
Module2: Functions & Lists

 Using for Loops with Lists


What it is?
A for loop is used to iterate through each item in a list.

When and Where It Can Be Applied?


 When performing batch processing like generating summaries.

How to Apply?
Banking:
for t in transactions:
print("Transaction:", t)

Automotive:
for speed in speed_log:
print("Speed:", speed)

 The in and not in Operators


What it is?
Check if an item exists or does not exist in a list.

When and Where It Can Be Applied?


 For searching and validation operations.

How to Apply?
Banking:
if -500 in transactions:
print("Withdrawal detected")

Automotive:
if 80 in speed_log:
print("High speed recorded")

 The Multiple Assignment Trick


What it is?
Unpacks list values into individual variables in a single line.

When and Where It Can Be Applied?


 When splitting structured data into readable parts.

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 41
Module2: Functions & Lists
How to Apply?
Banking:
name, balance, status = ["Alice", 5000, "Active"]

Automotive:
rpm, temp, fuel = [3000, 95, 60]

 Using enumerate() Function with Lists


What it is?
Returns both the index and the item during iteration.

When and Where It Can Be Applied?


 When displaying positioned logs or entries.

How to Apply?
Banking:
for i, t in enumerate(transactions):
print(f"Txn {i+1}: ₹{t}")

Automotive:
for i, speed in enumerate(speed_log):
print(f"Reading {i+1}: {speed} km/h")

 Using [Link]() and [Link]()


What it is?
 [Link]() selects a random item from a list
 [Link]() rearranges the list randomly

When and Where It Can Be Applied?


 Useful in simulation, testing, and random sampling

How to Apply?
Banking:
import random
customers = ["A", "B", "C"]
print([Link](customers)) # Random audit

Automotive:
[Link](speed_log) # Randomize test data

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 42
Module3: Dictionaries & String Manipulation

 The Dictionary Data Type


What it is?
A dictionary in Python is an unordered collection of key-value pairs, where each key must be
unique and immutable (like strings or numbers), and the values can be of any type.
car_info = {"brand": "Volvo", "model": "XC90", "year": 2024}

When and Where it is Applied?


 Automotive: Storing vehicle attributes (e.g., speed, engine temperature, fuel level).
 Banking: Representing a customer's profile (e.g., account number, balance, transaction
history).

How to Apply?
# Automotive domain
engine_data = {"RPM": 3000, "temperature": 90, "oil_level": "full"}

# Banking domain
account = {"name": "John Doe", "balance": 15000.75, "account_number": "AB1234XYZ"}

 Pretty Printing
What it is?
Pretty printing refers to formatting dictionaries or complex nested data structures in a
readable, indented form using pprint module.

When and Where it is Applied?


 Automotive: Debugging sensor data logs from an ECU.
 Banking: Printing nested transaction history or audit logs for clarity.

How to Apply?
import pprint

vehicle_log = {
"speed": 120,
"alerts": {"ABS": False, "Airbag": True},
"location": {"lat": 12.9716, "lon": 77.5946}
}
[Link](vehicle_log)

 Using Data Structures to Model Real-World Things


What it is?
Using dictionaries, lists, and combinations of both to simulate real-world systems like a fleet of
cars or a set of customer accounts.
When and Where it is Applied?
 Automotive: Modeling a fleet management system.
 Banking: Simulating account management, transactions, and audit trails.
Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS Page 43
Module3: Dictionaries & String Manipulation

How to Apply?
Automotive Domain
fleet = {
"KA01AB1234": {"model": "Sedan", "fuel": "Diesel", "mileage": 15},
"KA05XY9876": {"model": "SUV", "fuel": "Petrol", "mileage": 10}
}
print(fleet["KA01AB1234"]["fuel"]) # Output: Diesel

Banking Domain
customers = {
"1001": {"name": "Alice", "balance": 25000, "transactions": [1000, -500, 2000]},
"1002": {"name": "Bob", "balance": 30000, "transactions": [-200, 300, -100]}
}
print(customers["1002"]["transactions"]) # Output: [-200, 300, -100]

Common Dictionary Operations

Operation Example Description


Accessing values d[key] Returns value for key
Adding/modifying
d["new_key"] = value Adds or updates key-value
entry
Deleting entry del d["key"] Removes key-value pair
Checking
'key' in d Returns True if key exists
existence
Looping for k, v in [Link]() Iterate over key-value pairs
Getting
[Link](), [Link](), [Link]() Access dictionary components
keys/values/items
Copying new_d = [Link]() Creates shallow copy
Returns value or default if key
Safe access [Link]("key", "default")
doesn’t exist

Mini Use Cases


Automotive - Tire Pressure Monitor
tire_pressure = {"front_left": 32, "front_right": 31, "rear_left": 30, "rear_right": 32}
for tire, psi in tire_pressure.items():
if psi < 30:
print(f"Warning: Low pressure on {tire}")

Banking - Customer Summary Report


def print_summary(customer):
print(f"Name: {customer['name']}")
print(f"Balance: ₹{customer['balance']}")
print("Last 3 transactions:", customer['transactions'][-3:])

print_summary(customers["1001"])

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS Page 44


Module3: Dictionaries & String Manipulation

 Manipulating Strings – Working with Strings


What it is?
Strings in Python are sequences of characters enclosed in single (') or double (") quotes.
Python provides powerful built-in functions and methods to manipulate these strings for tasks
like formatting, parsing, searching, replacing, and transforming text data.

When and Where to Apply?


Automotive Domain
 Parsing diagnostic logs from onboard computers (OBD).
 Formatting vehicle telemetry data for display.
 Analyzing sensor outputs and command strings.
Banking Domain
 Formatting customer messages or alerts.
 Parsing and validating user inputs (e.g., account number, IFSC).
 Processing and displaying transaction statements.

How to Apply?
String Creation and Concatenation
vehicle = "Tesla"
model = "Model X"
full_name = vehicle + " " + model
print(full_name) # Tesla Model X

String Indexing and Slicing


vin = "1HGCM82633A004352"
print(vin[0:3]) # Output: 1HG (Manufacturer code)

Common String Methods


Method Purpose Example
Converts to
lower() / upper() "TESLA".lower() → 'tesla'
lowercase/uppercase
Checks start/end of
startswith() / endswith() "ACC12345".startswith("ACC")
string
join() / split() Joins or splits strings ".".join(["192", "168", "1", "1"])
Trims whitespace or
strip() / lstrip() / rstrip() " bank123 ".strip() → 'bank123'
characters
"error: high temp".replace("error",
replace() Replaces substring
"warning")
Checks substring
in 'error' in "engine error code"
existence

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS Page 45


Module3: Dictionaries & String Manipulation

Use Cases in Domains


Automotive - Log Parsing
log = "SPEED=80;TEMP=95;RPM=3000"
data = [Link](";")
for entry in data:
key, value = [Link]("=")
print(f"{key} => {value}")

Output:
SPEED => 80
TEMP => 95
RPM => 3000

Banking - SMS Formatting


account = "ACC12345678"
balance = 50200.75
message = f"Dear Customer, your a/c {account[-4:]} has balance ₹{balance:.2f}"
print(message)

Output:
Dear Customer, your a/c 5678 has balance ₹50200.75

 Validation and Checks


Checking Digits and Alphabets
code = "PIN1234"
print([Link]()) # True
print([Link]()) # False

Password Check in Banking App


password = "Secure#Bank1"
if len(password) >= 8 and any([Link]() for c in password):
print("Valid Password")

Date Parsing (String Handling)


date_str = "2025-06-23"
parts = date_str.split("-")
year, month, day = parts
print(f"Year: {year}, Month: {month}, Day: {day}")

Mini Practice Problems


Automotive: Validate License Plate Format
plate = "KA01AB1234"
if plate[:2].isalpha() and plate[2:4].isdigit() and plate[-4:].isdigit():
print("Valid Plate")

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS Page 46


Module3: Dictionaries & String Manipulation

Banking: Extract Transaction Info


trans_log = "TXNID:456789;AMT:1250;STATUS:SUCCESS"
for field in trans_log.split(";"):
k, v = [Link](":")
print(f"{k} = {v}")

 Putting Strings Inside Other Strings


What it is?
This concept involves embedding variable values inside a string using string formatting
techniques. Python provides multiple ways to construct such dynamic strings:
1. f-strings (formatted string literals)
2. [Link]() method
3. Old % formatting (less recommended now)

When and Where to Apply?


Automotive Domain:
 Displaying real-time vehicle parameters like speed, RPM, and fuel level on
dashboards or logs.
 Composing messages for diagnostics or alerts (e.g., "Warning: Engine temp is 105°C").
Banking Domain:
 Generating customer messages: account balance, transaction alerts, and mini-
statements.
 Creating formatted reports or email templates for customers.

How to Apply?
Using f-strings (Python 3.6+)
vehicle = "Volvo"
speed = 80
print(f"{vehicle} is moving at {speed} km/h")

Using [Link]()
alert = "Engine temperature is {0}°C at {1} RPM".format(105, 3000)
print(alert)

Using % operator (Old Style)


rpm = 3000
message = "Engine RPM is %d" % rpm
print(message)

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS Page 47


Module3: Dictionaries & String Manipulation

Example Use Cases


Automotive – Alert Message
vehicle = "Hyundai Creta"
temp = 102
rpm = 3200

msg = f"{vehicle}: High temperature alert! Temp = {temp}°C, RPM = {rpm}"


print(msg)

Output:
Hyundai Creta: High temperature alert! Temp = 102°C, RPM = 3200
Banking – Transaction Notification
name = "Ravi Kumar"
acc_no = "AC987654321"
amount = 1500.75
balance = 20500.50

print(f"Dear {name}, ₹{amount:.2f} has been debited from a/c {acc_no[-4:]}. Available balance: ₹{balance:.2f}")

Output:
Dear Ravi Kumar, ₹1500.75 has been debited from a/c 4321. Available balance: ₹20500.50

Sample Practice Scenarios


Automotive
model = "Tata Nexon"
fuel = "Petrol"
range_left = 340

print(f"{model} ({fuel}) can run for {range_left} km before refueling.")

Banking
cust_name = "Anjali Mehta"
txn_id = 938274
status = "SUCCESS"

print("Hello {}, your transaction ID {} is marked as {}.".format(cust_name, txn_id, status))

 Useful String Methods


What It Is?
Python strings support built-in methods to manipulate and query strings easily. These
methods help in searching, replacing, validating, transforming, and splitting strings.

When and Where It Can Be Applied?

Domain Use Case


Parsing OBD-II logs, formatting dashboard messages, validating
Automotive
commands
Banking Validating input (e.g., PAN, IFSC), formatting transaction messages

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS Page 48


Module3: Dictionaries & String Manipulation

How to Apply?
Common String Methods
Method Description Example
lower() Converts string to lowercase "BANK".lower() → "bank"
upper() Converts string to uppercase "alert".upper() → "ALERT"
"OBD1234".startswith("OBD") →
startswith() Checks if string starts with a substring
True
endswith() Checks if string ends with a substring "[Link]".endswith(".csv") → True
isalpha() Checks if string has only letters "volvo".isalpha() → True
isdigit() Checks if string has only digits "12345".isdigit() → True
Checks if string has only letters and
isalnum() "ACC1234".isalnum() → True
numbers
Removes whitespace from start and
strip() " done ".strip() → "done"
end
split(delim) Splits string into list by delimiter "12:30:45".split(":") → ['12','30','45']
join() Joins list of strings into one ":".join(['12','30','45']) → "12:30:45"
"ABS error".replace("error", "OK") →
replace() Replaces substrings
"ABS OK"
find() Finds first index of substring "engine temp high".find("temp") → 7

Example – Automotive Domain


log = "RPM:3200;TEMP:98;FUEL:Low"
items = [Link](";")
for item in items:
key, value = [Link](":")
print(f"{[Link]()} = {[Link]().upper()}")

Example – Banking Domain


account_no = " ACC9876 "
if account_no.strip().startswith("ACC") and account_no.strip().isalnum():
print("Valid account number format")

 Numeric Values of Characters – ord() and chr()


What It Is?
 ord(char) → returns the Unicode code (integer) of a character.
 chr(int) → returns the character corresponding to a Unicode code.

When and Where It Can Be Applied?

Domain Use Case


Automotive Encoding commands to sensors, generating encrypted tokens
Banking Basic encryption/decryption (e.g., Caesar cipher), audit logging

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS Page 49


Module3: Dictionaries & String Manipulation

How to Apply?
ord() – Character → Unicode number
print(ord('A')) # 65
print(ord('z')) # 122

chr() – Unicode number → Character


print(chr(65)) # 'A'
print(chr(122)) # 'z'

Example – Simple Encryption (Caesar Cipher)


Banking Domain – Encrypting PAN initials
def simple_encrypt(text):
return ''.join(chr(ord(c)+1) for c in text)

print(simple_encrypt("ABC123")) # Output: "BCD234"

Example – Command Encoding


Automotive Domain:
command = "ENGON"
encoded = [ord(c) for c in command]
print(encoded) # Output: [69, 78, 71, 79, 78]Mini Practice Tasks

Automotive
 Write a function that converts all error codes in a vehicle log to uppercase.
 Extract numbers from logs like "Speed=120;RPM=3400;Fuel=Half" and convert them to
integers.
Banking
 Validate if a given customer ID is alphanumeric and starts with “CUST”.
 Encrypt a short message using a Caesar Cipher-like shift using ord() and chr().

 Copying and Pasting Strings with the pyperclip Module


What It Is?
The pyperclip module allows Python programs to copy text to and paste text from the
system clipboard. It helps automate text input/output by eliminating manual copy-paste steps.

When and Where It Can Be Applied?

Domain Application Example


Automotive Auto-copy error codes, diagnostics info, VINs for reports
Banking Auto-copy transaction messages, account summaries, support templates

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS Page 50


Module3: Dictionaries & String Manipulation

How to Apply?
Step 1: Install the module
pip install pyperclip

Step 2: Use it in your Python script


import pyperclip

[Link]("Automated Alert: RPM limit exceeded.")


text = [Link]()
print("Clipboard contains:", text)Example Applications

Automotive – Copy Diagnostic Report


import pyperclip

diagnostic = "OBD Error: P0138 - Oxygen Sensor High Voltage (Bank 1 Sensor 2)"
[Link](diagnostic)
print("Copied to clipboard for emailing or logging.")

Banking – Auto-Copy Customer Response Message

import pyperclip

msg = "Dear Customer, ₹5000 has been credited to your A/C ending with 4567."
[Link](msg)
print("Copied to clipboard for support chat or mail.")

Project: Multi-Clipboard Automatic Messages


What It Is?
A script that stores multiple pre-written messages and pastes them automatically
depending on a given keyword (e.g., greeting, support, farewell). It simulates a multi-clipboard
system using a dictionary of text templates.

When and Where It Can Be Applied?


Domain Application
Automotive Support teams responding to common vehicle issues
Banking Customer service agents responding with template messages for transactions

How to Apply?
Step-by-Step: Multi-Clipboard Project
# multi_clipboard.py
import sys
import pyperclip

messages = {
"greeting": "Hello! How can I assist you today?",
"error_code": "Please refer to the service center for OBD error code P0420.",
"txn_alert": "Your transaction of ₹5000 is successful. A/C ending with 6789.",
"signoff": "Thank you for contacting support. Have a great day!"
}

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS Page 51


Module3: Dictionaries & String Manipulation

if len([Link]) < 2:
print("Usage: python multi_clipboard.py [keyword]")
[Link]()
key = [Link][1] # keyword passed from command line
if key in messages:
[Link](messages[key])
print(f"Message for '{key}' copied to clipboard.")
else:
print(f"No message found for '{key}'")
Run the script:
python multi_clipboard.py txn_alert

This will copy the transaction alert message to the clipboard.

Domain Use Cases


Automotive
Keyword Message
start "Engine start sequence initiated. Please check systems."
error_code "Refer to service manual for code P0301 (Cylinder 1 misfire)."

Banking
Keyword Message
txn_alert "₹10,000 debited from A/C XXXX1234 on 23-June-2025."
support "Please contact support at 1800-XXX-XXXX for more assistance."

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS Page 52


Module4: File Handling, Excel, CSV, and JSON

 Files and File Paths


What it is?
A file path is a string that represents the location of a file or directory on your computer. It
can be absolute (starting from the root directory) or relative (starting from the current
working directory).
 Absolute path: Full path from the root (C:\Users\name\... on Windows or
/home/name/... on Linux).
 Relative path: Location from the current working directory (e.g., ./data/[Link]).
Python provides the os and pathlib modules to work with file paths and directories in a cross-
platform manner.

When and Where it Can Be Applied?


Automotive Domain
 Access vehicle diagnostic logs stored in specific directories.
 Manage firmware files for Electronic Control Units (ECUs).
 Read/write CAN message logs from test runs stored in different folders.
Banking Domain
 Access customer KYC documents stored in structured directories.
 Manage and analyze transaction logs.
 Organize daily batch processing input/output files using date-based paths.

How to Apply?
Basic Operations with File Paths
import os

# Absolute Path
abs_path = [Link]("engine_logs.txt")

# Joining Paths
path = [Link]("data", "vehicles", "engine_logs.txt")

# Directory Name and Base Name


print([Link](path)) # 'data/vehicles'
print([Link](path)) # 'engine_logs.txt'

Using pathlib (modern and preferred):


from pathlib import Path

# Creating a path object


p = Path("data/vehicles/engine_logs.txt")
print([Link]) # engine_logs.txt
print([Link]) # data/vehicles
print([Link]) # .txt
print([Link]()) # True or False

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS Page 53


Module4: File Handling, Excel, CSV, and JSON
 Real-World Examples
Automotive Use Case

from pathlib import Path

log_dir = Path("/vehicle_logs/2025/06/")
if not log_dir.exists():
log_dir.mkdir(parents=True)

file_path = log_dir / "can_data.txt"


with open(file_path, "w") as f:
[Link]("CAN_MSG_01: 0x101\nCAN_MSG_02: 0x102")

 Stores CAN messages in a structured directory per year/month for diagnostics.


Banking Use Case
from pathlib import Path
from datetime import datetime

today = [Link]().strftime('%Y-%m-%d')
report_dir = Path(f"./reports/{today}")
report_dir.mkdir(parents=True, exist_ok=True)

file_path = report_dir / "transactions_summary.txt"


with open(file_path, "w") as file:
[Link]("CustomerID: 123456 | Amount: $5000 | Status: Completed")

 Creates a new directory daily and saves transaction summaries per date.
Security Considerations
 Always sanitize input if file paths come from users to avoid path traversal attacks.
 Use with open(...) context to automatically close files and prevent leaks.
 Ensure proper file permissions for sensitive data (especially in banking).

 The File Reading/Writing Process


What it is?
The file reading/writing process in Python allows programs to open, read, write, and
modify files on the disk. This is done using Python’s built-in open() function along with file
methods like read(), write(), and close(). Modern practice uses with open(...) as f: to handle
files safely.

When and Where it Can Be Applied?


Automotive Domain
 Logging real-time data from sensors or ECUs to files.
 Reading configuration files to set vehicle testing parameters.
 Writing test outcomes to log files for post-analysis.

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS Page 54


Module4: File Handling, Excel, CSV, and JSON
Banking Domain
 Reading customer transaction history from a file.
 Writing monthly account statements to text or CSV files.
 Logging user login attempts or failed transactions for audit purposes.

How to Apply?
Step-by-Step File I/O in Python
 Opening a File
file_object = open("[Link]", "mode")

Mode Purpose
'r' Read only
'w' Write (overwrite)
'a' Append
'b' Binary mode (e.g., 'rb', 'wb')

 Reading from a File


with open("vehicle_data.txt", "r") as f:
content = [Link]()

Other options:
 [Link]() – Reads one line
 [Link]() – Returns all lines as a list
Automotive Example

with open("engine_temp_log.txt", "r") as f:


for line in f:
print("Temperature reading:", [Link]())

 Writing to a File
with open("[Link]", "w") as f:
[Link]("This will overwrite the file.")

 Overwrites existing content.


Banking Example
with open("[Link]", "w") as f:
[Link]("Customer ID: 987654\nBalance: ₹25,000\nStatus: Active")

 Appending to a File
with open("[Link]", "a") as f:
[Link]("New transaction recorded at 12:45 PM\n")

Used for logs or when you don’t want to erase old data.

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS Page 55


Module4: File Handling, Excel, CSV, and JSON
 Reading and Writing with Binary Files
Useful for firmware, images, or ECU dumps in automotive.
with open("[Link]", "rb") as binary_file:
data = binary_file.read()

Best Practices
 Always use with open(): Ensures file is closed properly even if exceptions occur.
 Check file existence using [Link]() before reading.
 Avoid overwriting important data unintentionally (be cautious with 'w' mode).
 Use exception handling (try/except) for robustness in critical systems like banking
apps.

Real-World Use Cases


Automotive: Log CAN Messages
can_msgs = ["0x101: Speed", "0x102: RPM"]
with open("can_log.txt", "a") as f:
for msg in can_msgs:
[Link](msg + "\n")

Banking: Save Transaction Records


transactions = [
"TXN001, ₹1000, SUCCESS",
"TXN002, ₹500, FAILED"
]
with open("[Link]", "w") as f:
[Link]("\n".join(transactions))

 Saving Variables with the shelve Module


What it is?
The shelve module in Python provides a simple, dictionary-like interface to store Python
variables persistently on disk. It serializes data using pickle internally, allowing you to store
complex objects like lists, dictionaries, or custom classes into a file-based key-value store.
Think of it as a persistent dictionary:
import shelve
db = [Link]('mydata')
db['key'] = value
[Link]()

When and Where it Can Be Applied?


Automotive Domain
 Caching vehicle calibration data, sensor thresholds, or configuration profiles.
 Storing test results or metadata between test bench sessions.
 Saving temporary vehicle status data during debugging of ECUs.

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS Page 56


Module4: File Handling, Excel, CSV, and JSON
Banking Domain
 Saving user session data or temporary transaction states in a backend system.
 Persistently storing account preferences or customer profiling variables.
 Caching login attempts, failed transactions, or interim reports.

How to Apply?
 Saving Data to a Shelf
import shelve

with [Link]('bank_user_data') as db:


db['customer1'] = {'id': 101, 'balance': 5000, 'status': 'Active'}
db['customer2'] = {'id': 102, 'balance': 2000, 'status': 'Inactive'}

This stores the values just like a dictionary — but on disk.


 Retrieving Data
with [Link]('bank_user_data') as db:
print(db['customer1']['balance']) # Output: 5000

 Checking Keys and Values


with [Link]('bank_user_data') as db:
print(list([Link]())) # ['customer1', 'customer2']
print(list([Link]())) # List of dicts

 Real-World Use Cases


Automotive Use Case: Save ECU Test Data
import shelve

test_data = {
"RPM_Limit": 6500,
"Temp_Threshold": 105.0,
"Fuel_Map": [12.5, 13.0, 13.8]
}

with [Link]('ecu_test_config') as config:


config['vehicle_ABC'] = test_data

 Useful in automated test rigs for storing and reusing test settings.
Banking Use Case: Cache User Preferences
import shelve

prefs = {
'theme': 'dark',
'alerts': True,
'last_login': '2025-06-23 10:00:00'
}

with [Link]('session_data') as session:


session['user_456'] = prefs

 Enables web applications to maintain UI or security settings across sessions.

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS Page 57


Module4: File Handling, Excel, CSV, and JSON
Good Practices
 Use with [Link](...) to ensure proper file closing.
 shelve creates several files (e.g., .db, .dat, .dir) — keep them together.
 Avoid storing large or frequently updated data. Use a database for such cases.
 Only use string keys, as required by shelve.

Limitations
 Not thread-safe: Don’t use it in concurrent or multi-user systems.
 Not suitable for high-performance or high-scale applications.
 All changes must be manually written (no auto-sync unless using writeback=True).

 Saving Variables with print().format() Function


What it is?
The print().format() function in Python allows you to insert variable values into strings using
placeholders. It is a part of string formatting, which is especially useful when generating
structured, readable text for reports, logs, or user output.
This method is part of Python’s string templating system, offering a clear way to dynamically
embed variables into text.

When and Where it Can Be Applied?


Automotive Domain
 Format and log CAN data messages.
 Generate readable diagnostic reports for vehicle sensors.
 Create formatted strings to display ECU results.
Banking Domain
 Print formatted account statements or transaction receipts.
 Generate dynamic summaries in customer-facing messages.
 Create tabular output for employee reports or audits.

How to Apply?
Basic Usage
name = "Alice"
balance = 1500
print("Customer {} has ₹{} in the account.".format(name, balance))

Output:
Customer Alice has ₹1500 in the account.

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS Page 58


Module4: File Handling, Excel, CSV, and JSON
Positional and Keyword Arguments
print("Vehicle {0} has an RPM of {1}".format("BMW X5", 3500))
print("User {name} has a balance of ₹{bal}".format(name="Rahul", bal=7000))

Formatting Numbers

amount = 1234.56789
print("Amount: ₹{:.2f}".format(amount)) # ₹1234.57

speed = 89
print("Speed: {:03d} km/h".format(speed)) # Speed: 089 km/h

 :.2f → 2 decimal places


 :03d → pad to 3 digits with zeros

Real-World Examples
Automotive Example: Logging Sensor Data
sensor = "CoolantTemp"
value = 97.356
print("Sensor: {} | Value: {:.1f} °C".format(sensor, value))

Output:
Sensor: CoolantTemp | Value: 97.4 °C

Banking Example: Transaction Summary


cust_id = 123456
txn_id = "TXN7890"
amount = 2050.5
print("Customer ID: {} | Txn: {} | Amount: ₹{:.2f}".format(cust_id, txn_id, amount))

Output:
Customer ID: 123456 | Txn: TXN7890 | Amount: ₹2050.50

Writing to a File with format()


You can use format() with write() to save formatted strings to a file:
with open("transaction_report.txt", "w") as f:
[Link]("Customer: {} | Balance: ₹{:.2f}\n".format("Neha", 4356.25))

Best Practices
 Use :.2f for monetary values to standardize currency format.
 Use {:<10} or {:>10} for aligning columns in logs/reports.
 Avoid f-strings if compatibility with Python < 3.6 is needed.

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS Page 59


Module4: File Handling, Excel, CSV, and JSON
Alternative: f-Strings (Python 3.6+)
print(f"Customer {name} has ₹{balance:.2f} in the account.")

But format() remains useful in contexts where more flexibility or older Python versions are in
use.

 Working with Excel Spreadsheets


What it is?
Excel spreadsheets are widely used for structured data storage, analysis, and reporting.
Python’s openpyxl module allows automation of tasks such as reading and writing .xlsx files,
modifying cell content, and processing spreadsheets programmatically.

When and Where It Can Be Applied?


Banking Domain
 Automating generation of daily account statements.
 Reading customer data sheets for bulk processing.
 Analyzing transaction histories or credit reports.
Automotive Domain
 Reading ECU performance logs in Excel format.
 Managing and analyzing vehicle maintenance schedules.
 Collecting sensor calibration data from test environments.

 Installing the openpyxl Module


How to Apply?
Install the module using pip:
pip install openpyxl

Verify installation:
import openpyxl

Reading Excel Documents


Opening an Excel File
import openpyxl

# Load the workbook


wb = openpyxl.load_workbook('[Link]')

# Get the names of all sheets


print([Link])

# Select a sheet by name


sheet = wb['Sheet1']

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS Page 60


Module4: File Handling, Excel, CSV, and JSON
Accessing Cell Values
# Access value of cell B2
value = sheet['B2'].value
print("Cell B2:", value)

# Using row and column indexes


value = [Link](row=3, column=2).value

Looping Through Rows


for row in sheet.iter_rows(min_row=2, max_row=5, min_col=1, max_col=3):
for cell in row:
print([Link], end=' ')
print()

 Real-World Examples
Banking: Read Customer Balance Sheet
wb = openpyxl.load_workbook('bank_data.xlsx')
sheet = wb['Accounts']

for row in sheet.iter_rows(min_row=2, values_only=True):


cust_id, name, balance = row
print(f"Customer ID: {cust_id}, Name: {name}, Balance: ₹{balance}")

Automotive: Read Engine Test Report


wb = openpyxl.load_workbook('engine_test.xlsx')
sheet = [Link]

for row in sheet.iter_rows(min_row=2, values_only=True):


test_id, rpm, temp = row
print(f"Test ID: {test_id} | RPM: {rpm} | Temp: {temp} °C")

Tips and Best Practices


 .load_workbook() opens the file in read-write mode by default.
 Always validate sheet names using .sheetnames before accessing.
 Use .values_only=True in iter_rows() to get plain values (not cell objects).
 Be cautious about large Excel files; for massive data sets, consider pandas.

 Working with CSV Files and JSON Data


 The csv Module
What it is?
The csv module allows Python to read from and write to CSV (Comma-Separated Values)
files—used extensively for structured data interchange.

When and Where It Can Be Applied?


Banking Domain
 Import/export customer data.
 Analyze transaction logs.
 Share data with other financial systems in CSV format.
Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS Page 61
Module4: File Handling, Excel, CSV, and JSON
Automotive Domain
 Logging sensor or CAN data in tabular format.
 Storing vehicle test run results.
 Exchanging configuration parameters with test automation tools.

Reading CSV Files


import csv

with open('[Link]') as file:


reader = [Link](file)
for row in reader:
print(row)

To skip the header:


next(reader) # Skip first line (header)

Writing CSV Files


with open('[Link]', 'w', newline='') as file:
writer = [Link](file)
[Link](['ID', 'Amount', 'Status'])
[Link]([101, 2500, 'SUCCESS'])

Project: Removing the Header from CSV Files


import csv

with open('[Link]') as input_file, open('no_header.csv', 'w', newline='') as output_file:


reader = [Link](input_file)
writer = [Link](output_file)

next(reader) # Skip header row


for row in reader:
[Link](row)

Useful when integrating CSV data into systems that don’t support headers.

 The json Module


What it is?
The json module handles JavaScript Object Notation (JSON) — a lightweight data
interchange format used extensively in APIs and web applications.

When and Where It Can Be Applied?


Banking Domain
 Receiving customer or transaction data via APIs.
 Storing application configuration in JSON.
 Logging data exchanges with partner services.
Automotive Domain
 Sending/receiving data to/from cloud dashboards via APIs.
 Logging diagnostic info from embedded systems in JSON format.
 Configuring automotive test rigs using JSON files.
Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS Page 62
Module4: File Handling, Excel, CSV, and JSON
Loading JSON (Read from File or API)
import json

with open('[Link]') as f:
data = [Link](f)
print(data['customer_id'])

Dumping JSON (Write to File)


new_data = {'vehicle': 'XUV700', 'rpm': 3500, 'temp': 88}

with open('vehicle_log.json', 'w') as f:


[Link](new_data, f, indent=4)

JSON String Operations


# Convert JSON string to Python dict
json_str = '{"name": "Raj", "balance": 5000}'
data = [Link](json_str)

# Convert Python dict to JSON string


output = [Link](data)

APIs (Application Programming Interfaces)


 Often return data in JSON format.
 Use requests module to fetch:
import requests
response = [Link]('[Link]
data = [Link]()

Real-World Examples
Automotive: Save Sensor Readings to JSON
import json

sensor_data = {
"vehicle": "Altroz",
"rpm": 3000,
"temperature": 92.5
}

with open("engine_data.json", "w") as f:


[Link](sensor_data, f)

Banking: Read Transaction CSV


import csv

with open("[Link]") as f:
reader = [Link](f)
next(reader) # Skip header
for row in reader:
print(f"Txn ID: {row[0]} | Amount: ₹{row[1]} | Status: {row[2]}")

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS Page 63


Module5: Classes and Objects

 Classes and Objects: Programmer-Defined Types


What it is?
 A class is a blueprint for creating objects (instances).
 An object is a collection of data (attributes) and behaviors (methods).
 Programmer-defined types allow you to model real-world entities.

When and Where to Apply?


 When built-in types (like int, list) are insufficient to represent domain-specific data
models.
 In domains requiring encapsulation of related data and behavior like:
 Automotive: Engine, Sensor, Vehicle
 Banking: Account, Customer, Transaction

How to Apply?
class Customer:
pass

cust1 = Customer()

 Attributes
What it is?
 Attributes are variables that belong to an object or class.

When and Where to Apply?


 Used to represent state or properties of an object.
 Automotive: speed, fuel_level, rpm for Car object.
 Banking: balance, account_number for BankAccount.

How to Apply?
class Car:
def __init__(self, make, speed):
[Link] = make
[Link] = speed

my_car = Car("Volvo", 80)


print(my_car.make, my_car.speed)

 Rectangles (Example Class)


What it is?
 An example from the book for modeling geometric data using objects.

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 64
Module5: Classes and Objects

When and Where to Apply?


 This can model screen areas, sensor ranges, or bank branches' layout zones.

How to Apply?
class Rectangle:
def __init__(self, width, height):
[Link] = width
[Link] = height

r = Rectangle(5, 10)
print([Link] * [Link])

 Instances as Return Values


What it is?
 Functions can create and return instances (objects) of classes.

When and Where to Apply?


 To encapsulate logic inside functions that produce customized objects.
 Automotive: A create_vehicle() function returning a Vehicle object.
 Banking: create_account(customer_name) returning a BankAccount.

How to Apply?
def create_customer(name, age):
class Customer:
def __init__(self, name, age):
[Link] = name
[Link] = age
return Customer(name, age)

c1 = create_customer("Ravi", 35)
print([Link], [Link])

 Objects are Mutable


What it is?
 Objects' attributes can be changed after creation.
 The object reference remains the same, but its state can be modified.

When and Where to Apply?


 To update object data dynamically:
 Automotive: Update a car’s fuel level as it drives.
 Banking: Update a customer’s balance after transactions.

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 65
Module5: Classes and Objects

How to Apply?
class BankAccount:
def __init__(self, balance):
[Link] = balance

acc = BankAccount(1000)
[Link] += 500 # Deposit
print([Link]) # Output: 1500

 Copying Objects
What it is?
 Copying can be shallow (new reference) or deep (new object with copied values)

When and Where to Apply?


 Needed when duplicating an object without affecting the original.
 Automotive: Clone vehicle configuration templates.
 Banking: Duplicate account for analysis without affecting the real one.

How to Apply?
import copy

class Car:
def __init__(self, brand, speed):
[Link] = brand
[Link] = speed

car1 = Car("Volvo", 100)


car2 = [Link](car1) # Shallow copy
car3 = [Link](car1) # Deep copy

 Summary Table
Concept Use Case - Automotive Use Case - Banking
Class/Object Vehicle, Engine, Sensor Customer, Account, Transaction
Attributes speed, fuel_type, engine_on balance, IFSC, account_type
Rectangle Parking area, sensor zone ATM screen, branch layout
Instances as Return create_engine(), build_car() open_account(), new_customer()
Mutable Objects update speed, temperature deposit, withdraw, update KYC
Object Copying clone vehicle config replicate account for audit

 Time Class
What it is?
 A class used to represent time as an object with attributes like hour, minute, and second.
 Helps in organizing and manipulating time-related data using object-oriented design.

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 66
Module5: Classes and Objects

When and Where to Apply?


Domain Use Cases
Automotive Trip duration, engine run time, fuel usage logs
Transaction timestamps, session durations, interest calculation
Banking
timeframes

How to Apply?
class Time:
def __init__(self, hour=0, minute=0, second=0):
[Link] = hour
[Link] = minute
[Link] = second

def print_time(self):
print(f"{[Link]:02d}:{[Link]:02d}:{[Link]:02d}")

t1 = Time(10, 45, 30)


t1.print_time() # Output: 10:45:30

 Pure Functions
What it is?
 Functions that do not modify objects passed to them.
 They take objects as input, perform computations, and return new objects without
altering the original.

When and Where to Apply?


Domain Use Cases
Automotive Calculating estimated arrival time without changing current time object
Calculating interest or maturity date without modifying the original
Banking
account object

How to Apply?
def add_time(t1, t2):
total_seconds = ([Link] + [Link]) * 3600 + ([Link] + [Link]) * 60 + ([Link] + [Link])
hours = total_seconds // 3600
minutes = (total_seconds % 3600) // 60
seconds = total_seconds % 60
return Time(hours, minutes, seconds)

start = Time(1, 20, 30)


duration = Time(2, 45, 15)
end = add_time(start, duration)
end.print_time() # Output: 04:05:45

Note: add_time() does not change start or duration.

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 67
Module5: Classes and Objects

 Modifiers (Mutators)
What it is?
 Functions that modify the object passed to them, typically through self.
 Called mutator methods or modifiers because they change internal state.

When and Where to Apply?


Domain Use Cases
Automotive Updating trip time as the car moves
Adjusting account balance, updating interest
Banking
period

How to Apply?
def increment(time_obj, seconds):
time_obj.second += seconds
while time_obj.second >= 60:
time_obj.second -= 60
time_obj.minute += 1
while time_obj.minute >= 60:
time_obj.minute -= 60
time_obj.hour += 1

trip_time = Time(2, 50, 30)


increment(trip_time, 500) # Mutates original object
trip_time.print_time() # Output will reflect updated time

 Summary Table
Concept Description Automotive Example Banking Example
Time Represents hours, Drive duration, sensor Session time, transaction
Class minutes, seconds logs logs
Pure Returns new object, Estimated arrival time Interest computation, EMI
Function no side-effects calculation scheduler
Alters the existing Increment trip time, Update account after
Modifier
object directly update engine timer deposit/withdrawal

Simple Practice Examples


Banking: Add transaction time to current time (Pure Function)
def add_transaction_time(current_time, txn_duration):
return add_time(current_time, txn_duration)

Automotive: Update engine run-time (Modifier)


def update_engine_time(engine_time, seconds):
increment(engine_time, seconds)

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 68
Module5: Classes and Objects

 Object-Oriented Features
What it is?
OOP is a programming paradigm based on objects. Python supports:
 Encapsulation: Bundling data and methods.
 Abstraction: Hiding implementation details.
 Inheritance: Reusing code via parent-child relationships.
 Polymorphism: Different classes respond to same method.

When/Where to Apply?
 Automotive: Design Vehicle, Car, Truck classes.
 Banking: Use Account, SavingsAccount, LoanAccount.

How to Apply?
class Vehicle:
def start(self):
print("Vehicle starting...")

class Car(Vehicle):
def start(self):
print("Car starting with key...")

v = Vehicle()
c = Car()
[Link]() # Vehicle starting...
[Link]() # Car starting with key...

 Printing Objects
What it is?
 When printing an object, Python uses the special method __str__() or __repr__().

Where to Apply?
 For debugging/logging object state.

How to Apply?
class Customer:
def __init__(self, name, balance):
[Link] = name
[Link] = balance

def __str__(self):
return f"Customer: {[Link]}, Balance: ₹{[Link]}"

cust = Customer("Anita", 5000)


print(cust)

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 69
Module5: Classes and Objects

 Another Example: Transaction Class


class Transaction:
def __init__(self, amount, type):
[Link] = amount
[Link] = type

def __str__(self):
return f"{[Link]} of ₹{[Link]}"

t = Transaction(1000, "Deposit")
print(t)
 Can be extended for ATM, Online Transfer, etc.

One more Example


Description:
Combining multiple classes and methods to represent a real-world object.
Automotive Example:
class Engine:
def __init__(self, power):
[Link] = power

def __str__(self):
return f"{[Link]} HP Engine"

class Car:
def __init__(self, brand, engine):
[Link] = brand
[Link] = engine

def __str__(self):
return f"{[Link]} with {[Link]}"

e = Engine(150)
c = Car("Volvo", e)
print(c) # Volvo with 150 HP Engine

 The __init__() Method


What it is?
 The constructor of the class.
 Automatically invoked during object creation.

When to Use?
 When initializing object attributes.
class Account:
def __init__(self, acc_no, balance):
self.acc_no = acc_no
[Link] = balance

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 70
Module5: Classes and Objects

 The __str__() Method


What it is?
 A string representation of the object.
 Used by print() and str().
python
CopyEdit
class Sensor:
def __init__(self, id, value):
[Link] = id
[Link] = value

def __str__(self):
return f"Sensor ID: {[Link]}, Value: {[Link]}"

s = Sensor("TMP101", 36.6)
print(s)

 Operator Overloading
What it is?
 You can redefine standard operators like +, ==, etc., for custom behavior.
Banking Example:
class Money:
def __init__(self, amount):
[Link] = amount

def __add__(self, other):


return Money([Link] + [Link])

def __str__(self):
return f"₹{[Link]}"

m1 = Money(1000)
m2 = Money(500)
m3 = m1 + m2
print(m3) # ₹1500

 Type-Based Dispatch
What it is?
 Different logic based on argument type.

Example:
def display(info):
if isinstance(info, str):
print("Name:", info)
elif isinstance(info, int):
print("Account Number:", info)

display("Ravi")
display(123456)

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 71
Module5: Classes and Objects

Polymorphism
What it is?
 Different classes implement the same method in different ways.

Where to Use?
 Banking: Different accounts have calculate_interest().
 Automotive: Different vehicles implement start() differently.
class LoanAccount:
def calculate_interest(self):
return "Interest at 10%"

class SavingsAccount:
def calculate_interest(self):
return "Interest at 4%"

for acc in [LoanAccount(), SavingsAccount()]:


print(acc.calculate_interest())

 Interface and Implementation


What it is?
 Interface: What a class exposes (e.g., methods).
 Implementation: How those methods work internally.

Why Use It?


 To separate what an object does from how it does it.
 Enables flexibility and modular design.

Example:
class Vehicle:
def start(self): # Interface
raise NotImplementedError

class Car(Vehicle):
def start(self): # Implementation
print("Car starts with a push button.")

class Truck(Vehicle):
def start(self):
print("Truck starts with ignition key.")

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 72
Module5: Classes and Objects

 Summary Table
Concept Description Automotive Use Banking Use
__init__() Initializes object Engine(power) Account(acc_no, balance)
__str__() String representation Sensor, Car Customer, Transaction
Operator
Redefining +, ==, etc. Distance + Distance Money + Money
Overloading
Behavior based on
Type Dispatch log_data(sensor) display(info)
argument type
Shared interface,
Polymorphism start() in Car, Truck calculate_interest()
different behavior
Interface &
Abstraction [Link]() Account.compute_tax()
Impl.

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 73
Practice Questions

Module1: Automotive Domain - Python Basics & Flow Control


1. Write a Python expression to calculate the fuel efficiency of a car given the distance
traveled (in km) and fuel consumed (in liters).
2. What data type would you use to store the mileage of a car (e.g., 18.5 km/l)? Justify your
answer.
3. Write a Python program to concatenate two strings representing a vehicle’s make and
model (e.g., "Toyota" and "Corolla").
4. Write a Python program that asks for the user’s car speed and checks whether it exceeds
a given speed limit using conditional statements.
5. How can you use [Link]() in a program that monitors engine temperature and exits if it
crosses a critical threshold?
6. Given a vehicle’s fuel level (in percentage), write a program using comparison operators
to check if it’s below 15% and print a low fuel warning.
7. Write a Python script to determine if a car's engine type is "Electric", "Diesel", or "Petrol"
using Boolean and comparison operators.
8. What will be the output of the following expression in Python? print("Car" + "Speed" * 3)
9. Write a Python program that asks for a car's current speed and displays different
messages based on speed (e.g., "Slow", "Normal", "Over-speeding").
10 What will be the output of the following expression? print(bool(0)) and print(bool(50)) in
the context of fuel level.
11 Write a Python program that imports the random module and generates a random speed
between 40 km/h and 120 km/h.
12 Explain the role of Boolean operators (and, or, not) in writing a Python program to check
if a car’s speed is in a safe range (e.g., 40-80 km/h).
13 Write a Python program to check if a vehicle is eligible for an emissions test based on its
registration year.
14 How can you use string replication to print a pattern that simulates a car moving
forward (---> ---> --->)?
15 Write a Python script to determine if a vehicle qualifies for a toll exemption based on its
type (e.g., Electric vehicles are exempt).

Module1: Banking Domain - Python Basics & Flow Control


1. Write a Python expression to calculate the interest earned on a savings account given the
principal amount, rate of interest, and time period.
2. What data type would you use to store an account balance and why?
3. Write a Python program to concatenate a bank name and a branch location (e.g., "HDFC"
+ " Indiranagar").
4. Write a Python script that asks for a customer's age and checks if they qualify for a
senior citizen savings scheme using conditional statements.
5. How can [Link]() be used in an ATM transaction program when a wrong PIN is entered
multiple times?
6. Given a bank account balance, write a program that checks if there are sufficient funds
for a withdrawal of ₹5000.
7. Write a Python program that determines if a bank transaction is "Debit" or "Credit" using
Boolean and comparison operators.

Questions Prepared by: Dr. Vishwa Kiran S, Dept of CSBS Page 74


Practice Questions

8. What will be the output of the following expression in Python? print("Bank" +


"Statement" * 2)
9. Write a Python script that asks for a loan amount and interest rate and displays different
messages based on the interest rate (e.g., "Low", "Moderate", "High").
10 What will be the output of the following expression? print(bool(0.00)) and
print(bool(500.75)) in the context of account balance.
10 Write a Python program that imports the random module and generates a random account
number.
11 Explain the role of Boolean operators (and, or, not) in checking multiple loan eligibility
criteria (e.g., minimum salary, credit score).
12 Write a Python program to check if a customer is eligible for a credit card based on their
monthly income.
13 How can you use string replication to print a pattern that simulates a transaction receipt
(==== Bank Transaction ==== repeated)?
14 Write a Python script to determine if a user is eligible for an overdraft facility based on
their account type (e.g., "Savings", "Current").

Module2: Automotive Domain - Functions & Lists


1 Write a function calculate_mileage(distance, fuel) that returns the mileage of a vehicle.
2 What will be the output of the following function?
def car_type():
return "SUV"
print(car_type())

3 Write a function that accepts a car model as a parameter and prints whether it is electric,
petrol, or diesel (based on predefined data).
4 Create a function calculate_speed(distance, time) that calculates and returns speed.
Handle division by zero using exception handling.
5 What is the significance of the None value in Python functions? Provide an example
related to car diagnostics.
6 Write a Python function that takes the number of passengers and the available seat
capacity and returns whether the vehicle is full.
7 What will be the output of the following code?
car = "Tesla"
def print_car():
print(car)
print_car()

8 Demonstrate the use of the global statement in a function that keeps track of the total
distance traveled by a vehicle.
9 Write a function get_car_info(make, model, year) that returns a formatted string of the
car’s details using keyword arguments.
10 . Write a program using a list to store different fuel types available at a petrol station and
print them using a loop.
11 . How can lists be used to store vehicle registration numbers? Write a Python snippet
that adds, removes, and displays the registration numbers.

Questions Prepared by: Dr. Vishwa Kiran S, Dept of CSBS Page 75


Practice Questions

12 . Given a list of car speeds, write a function that returns the maximum speed recorded.
13 . Modify the Magic 8 Ball program to predict random fuel efficiency values for different
driving conditions.
14 . Write a Python program to sort a list of vehicle names in alphabetical order.
15 . Explain the difference between lists and tuples using an example related to automotive
spare parts inventory.

Module2: Banking Domain - Functions & Lists


1. Write a function calculate_interest(principal, rate, time) that returns the interest earned.
2. What will be the output of the following function?
def account_type():
return "Savings Account"
print(account_type())

3. Write a function that accepts an account balance and withdrawal amount as parameters
and returns whether the withdrawal is possible.
4. Create a function validate_transaction(amount, balance) that raises an exception if the
withdrawal amount exceeds the balance.
5. What is the role of the None value in Python functions? Provide an example related to a
failed banking transaction.
6. Write a Python function that takes a list of transactions (deposits and withdrawals) and
calculates the final balance.
7. What will be the output of the following code?

bank_name = "HDFC"
def print_bank():
print(bank_name)
print_bank()

8. Demonstrate the use of the global statement in a function that tracks the total number of
bank transactions.
9. Write a function get_customer_info(name, age, account_type) that returns a formatted
string of the customer’s details using keyword arguments.
10 . Write a program using a list to store different loan types available in a bank and
print them using a loop.
11 . How can lists be used to store multiple account numbers? Write a Python snippet that
adds, removes, and displays account numbers.
12 . Given a list of account balances, write a function that returns the highest balance.
13 . Modify the Magic 8 Ball program to predict random stock market outcomes.
14 . Write a Python program to sort a list of customer names alphabetically.
15 . Explain the difference between lists and tuples using an example related to banking
transaction records.

Module3: Automotive Domain - Dictionaries & String Manipulation


1. Create a dictionary to store car details (make, model, year, fuel type). Write a Python
function to print the details in a formatted manner.

Questions Prepared by: Dr. Vishwa Kiran S, Dept of CSBS Page 76


Practice Questions

2. How can dictionaries be used to store vehicle registration information? Write a program
that adds, updates, and retrieves registration details.
3. Write a Python function to pretty-print a dictionary storing different car brands and
their country of origin.
4. Given a dictionary of car models and their prices, write a function to return the price of a
given model.
5. How can a nested dictionary be used to store vehicle specifications (engine, transmission,
fuel efficiency)? Provide a Python example.
6. Explain the difference between lists and dictionaries in the context of storing vehicle
service history.
7. Write a Python script to iterate over a dictionary storing car models and their top speeds,
printing each model along with its speed.
8. Write a function that converts a dictionary containing car details into a formatted string
using f-strings.
9. Use string manipulation methods to validate a car registration number (e.g., check if it
starts with "KA" for Karnataka).
10 . Given a string containing a vehicle identification number (VIN), write a program to
extract only the numeric portion.
11 . Write a program that checks if a car's chassis number contains only alphanumeric
characters.
12 . Write a Python function that counts the occurrence of each letter in a car
manufacturer’s name (e.g., "Mercedes").
13 . Demonstrate the use of ord() and chr() functions to encode and decode vehicle
registration plate characters.
14 . How can the pyperclip module be used in an automotive service management system?
Provide an example.
15 . Implement a simple clipboard-based application that copies and pastes car details
using the pyperclip module.

Module3: Banking Domain - Dictionaries & String Manipulation


1. Create a dictionary to store customer account details (name, account number, balance,
account type). Write a Python function to print them in a structured format.
2. How can dictionaries be used to manage multiple customer transactions? Write a
program to store transactions and retrieve them based on an account number.
3. Write a Python function to pretty-print a dictionary storing different bank branches and
their IFSC codes.
4. Given a dictionary of account types and their minimum balance requirements, write a
function to return the minimum balance required for a given account type.
5. How can a nested dictionary be used to store bank customer details (personal info,
account info, transaction history)? Provide a Python example.
6. Explain the difference between lists and dictionaries in the context of managing bank
customer data.
7. Write a Python script to iterate over a dictionary storing bank names and their interest
rates, printing each bank with its rate.

Questions Prepared by: Dr. Vishwa Kiran S, Dept of CSBS Page 77


Practice Questions

8. Write a function that converts a dictionary containing banking details into a formatted
string using f-strings.
9. Use string manipulation methods to validate an account number (e.g., check if it consists
of exactly 10 digits).
10 . Given a string containing a bank transaction reference number, write a program to
extract only the numeric portion.
11 . Write a program that checks if a customer’s PAN number contains only uppercase
letters and digits.
12 . Write a Python function that counts the occurrence of each letter in a bank's name (e.g.,
"State Bank of India").
13 . Demonstrate the use of ord() and chr() functions to encode and decode bank
transaction reference characters.
14 . How can the pyperclip module be used in an online banking system for copying OTPs or
transaction details? Provide an example.
15 . Implement a simple clipboard-based application that copies and pastes bank details
using the pyperclip module.

Module4: Automotive Domain - File Handling, Excel, CSV, and JSON


1. Write a Python program to save a car’s fuel efficiency data into a text file and then read it
back.
2. How can you use the shelve module to store and retrieve a vehicle’s service history?
3. Write a Python script that reads a car's maintenance log stored in a text file and prints it
line by line.
4. Explain the difference between reading (r), writing (w), and appending (a) modes in the
context of storing vehicle sensor logs.
5. Create a Python program that writes a formatted string containing a vehicle's details
(make, model, year) into a file using [Link]().
6. How can [Link] be used to check whether a vehicle log file exists before reading it?
7. Write a Python script to read an Excel sheet containing vehicle registration details using
openpyxl.
8. Write a program that extracts the list of electric vehicles from an Excel file and prints
them.
9. Explain how the openpyxl module can be used to update an Excel spreadsheet
containing vehicle sales data.
10 . Write a Python program to read a CSV file containing vehicle mileage data and print the
average mileage.
11 . Create a script that removes the header from a CSV file containing car sales data.
12 . Write a Python function to convert a dictionary containing car specifications into a JSON
string.
13 .How can an API be used to fetch real-time fuel prices and store them in a JSON file?
14 . Write a script that reads a JSON file containing vehicle insurance details and prints
them in a formatted way.
15 . Explain the difference between CSV and JSON formats with an example of storing
vehicle manufacturing details.

Questions Prepared by: Dr. Vishwa Kiran S, Dept of CSBS Page 78


Practice Questions

Module4: Banking Domain - File Handling, Excel, CSV, and JSON


1. Write a Python program to save customer bank transaction details into a text file and
read them back.
2. How can you use the shelve module to store and retrieve a customer’s account
balance securely?
3. Write a Python script that reads a bank statement stored in a text file and prints each
transaction separately.
4. Explain the difference between reading (r), writing (w), and appending (a) modes in
the context of storing banking transactions.
5. Create a Python program that writes a formatted string containing account details
(name, balance, account type) into a file using [Link]().
6. How can [Link] be used to check whether a customer's transaction file exists before
reading it?
7. Write a Python script to read an Excel sheet containing customer account details
using openpyxl.
8. Write a program that extracts a list of loan defaulters from an Excel file and prints
their details.
9. Explain how the openpyxl module can be used to update an Excel spreadsheet
containing bank loan records.
10 . Write a Python program to read a CSV file containing daily bank transactions and
compute the total debit and credit amounts.
11 . Create a script that removes the header from a CSV file containing bank customer
records.
12 . Write a Python function to convert a dictionary containing bank account information
into a JSON string.
13 . How can an API be used to fetch real-time exchange rates and store them in a JSON file?
14 . Write a script that reads a JSON file containing customer credit scores and prints them
in a structured format.
15 . Explain the difference between CSV and JSON formats with an example of storing
customer loan details.

Module5: Automotive Domain - Classes and Objects


1. Define a Python class Car with attributes make, model, and year. Create an instance and
print its details.
2. Write a method inside the Car class that calculates the car's age based on the current
year.
3. What is the purpose of the __init__ method in a class? Implement it in a Vehicle class.
4. Write a Python class Engine that has attributes fuel_type and horsepower. Create an
instance and modify an attribute.
5. How can you use objects as return values? Provide an example of a CarFactory class that
creates and returns a Car object.
6. Write a Python program to demonstrate that objects are mutable by modifying a car’s
mileage attribute.

Questions Prepared by: Dr. Vishwa Kiran S, Dept of CSBS Page 79


Practice Questions

7. Implement a method inside the Car class that returns a formatted string representation
of the car details using __str__().
8. Explain and implement operator overloading for the + operator to combine the mileage
of two Car objects.
9. Write a Python program to copy an object of the Car class using the copy module.
10 . Create a Speedometer class with a method that returns the current speed of the vehicle.
11 . Define a Time class to represent the driving duration of a vehicle. Implement a method
to add two Time objects.
12 . Implement a modifier method inside the Car class that increases the car's speed.
13 . What is type-based dispatch in Python? Provide an example where different car types
(Electric, Diesel, Petrol) override a method.
14 . Write a program to demonstrate polymorphism by creating a base class Vehicle and
derived classes Car and Truck.
15 . Explain how interface and implementation differ using an example of a Vehicle interface
with an abstract method fuel_efficiency().

Module5: Banking Domain - Classes and Objects


1. Define a Python class BankAccount with attributes account_number, account_holder, and
balance. Create an instance and print its details.
2. Write a method inside the BankAccount class to deposit and withdraw money.
3. What is the role of the __init__ method in a class? Implement it in a Customer class.
4. Write a Python class Loan that has attributes amount, interest_rate, and duration. Create
an instance and modify an attribute.
5. How can you use objects as return values? Provide an example of a Bank class that
creates and returns a BankAccount object.
6. Write a Python program to demonstrate that objects are mutable by modifying a bank
account’s balance.
7. Implement a method inside the BankAccount class that returns a formatted string
representation of the account details using __str__().
8. Explain and implement operator overloading for the + operator to merge two
BankAccount balances.
9. Write a Python program to copy an object of the BankAccount class using the copy
module.
10 . Create a Transaction class with a method that records a debit or credit transaction.
11 . Define a Time class to represent the maturity period of a fixed deposit. Implement a
method to add two Time objects.
12 . Implement a modifier method inside the Loan class that increases the loan tenure.
13 . What is type-based dispatch in Python? Provide an example where different account
types (Savings, Current, Fixed Deposit) override a method.
14 .Write a program to demonstrate polymorphism by creating a base class Account and
derived classes SavingsAccount and CheckingAccount.
15 . Explain how interface and implementation differ using an example of a BankService
interface with an abstract method process_transaction().

Questions Prepared by: Dr. Vishwa Kiran S, Dept of CSBS Page 80

Common questions

Powered by AI

In programming, lists and dictionaries serve distinct roles for data management. Lists maintain ordered collections of items, ideal for storing homogeneous data like transaction amounts or account numbers sequentially. Their indexing allows quick access when order matters. In contrast, dictionaries use key-value pairs, supporting structured, heterogeneous data storage, which is useful for storing detailed records such as customer details or vehicle specifications. For banking, dictionaries can manage complex customer data encompassing names, accounts, and balances together efficiently . In automotive applications, dictionaries help store car details or registration information using descriptive keys for easy updates and retrieval . While lists are efficient for indexed operations, dictionaries offer more flexibility for lookup operations based on unique keys.

Control flow statements like 'if', 'if-else', and 'if-elif-else' allow branching paths in decision-making processes based on specified conditions. The 'if' statement executes code only if a condition evaluates to true, such as allowing a transaction if 'balance > withdrawal amount' in banking . The 'if-else' statement handles two outcomes by executing an alternative block if the condition is false, enabling decisions like approving or rejecting withdrawals based on balance sufficiency . The 'if-elif-else' ladder facilitates multiple condition checks, such as determining interest rates based on balance ranges or gear suggestions based on speed in automotive applications . These control flows guide logical paths based on the environment or data input.

The 'break' statement is used to immediately exit a loop when a specific condition is met, which is crucial in processes requiring immediate stops upon condition satisfaction, like halting login attempts after entering the correct PIN in banking . In automotive applications, 'break' may stop sensor checks when a critical velocity is detected . Conversely, 'continue' skips the current iteration, resuming future cycles of the loop, useful in scenarios like continuing after processing non-critical errors or alerts. For banking processes, this allows passing insignificant transaction errors . It efficiently manages loop iterations, improving code execution by focusing only on significant data points or events, conserving resources and improving flow.

Indentation is critical in Python because it defines the scope of code blocks, ensuring that lines of code belong to the correct logical group. Without proper indentation, Python scripts will not execute as intended since it won't recognize grouped statements within control structures. In banking applications, indentation ensures that all operations related to a transaction approval are executed together when conditions like 'balance > 5000' are true . Similarly, in automotive contexts, properly indented code ensures that actions such as 'Activating Cooling System' execute only when 'engine_temp > 100', maintaining proper flow and function of the program . Incorrect indentation leads to error or unintended execution sequences.

Boolean operators like 'and', 'or', and 'not' are used to create compound conditions that enhance the readability and efficiency of conditional statements by allowing multiple comparisons to be expressed succinctly. In banking, for instance, a condition like 'balance >= 5000 and account_type == "Savings"' enables checking multiple criteria to determine interest eligibility in one line . In automotive applications, it allows for simultaneous checks, such as safety conditions with 'if not door_closed or not seatbelt_fastened', thereby triggering alerts efficiently when either condition fails .

Dictionaries in banking applications manage customer transactions by associating unique keys to each transaction or account detail, enabling efficient data access and manipulation. For instance, using a nested dictionary to store customer data as 'customer_data = {"John": {"account_number": "12345", "transactions": [{"date": "2023-10-01", "amount": 200}]}}' allows easy retrieval and updates through keys like "John" or "transactions" . Such structures support quick lookups of transaction history, real-time updates, and accurate record management, essential for maintaining financial integrity and customer service efficiency. Advantages include organizing complex datasets, facilitating quick access, and supporting scalable data models critical in banking operations.

Program execution in Python is typically sequential, proceeding line-by-line from the start to the end of a script. This ordered flow is vital for ensuring predictable and reliable application behaviors, especially in sensitive domains like banking and automotive, where procedural accuracy is paramount. Flow control, through conditions, loops, and function calls, can alter this sequence to respond dynamically to input or system states. For instance, in banking, flow control might involve checking if 'balance > withdrawal amount' before proceeding with a transaction . In automotive applications, similar checks can halt or continue systems based on sensor data . Such controls ensure robust, logical flows that adapt to operational demands and constraints.

'If-elif-else' structures are significant for multi-level decision-making processes as they allow multiple conditions to be evaluated sequentially, ensuring that the correct block of code executes based on the first true condition. In banking, they facilitate interest rate determination, for example, by checking balance ranges: 'if balance < 5000: no interest; elif balance < 100000: interest 4%; else: interest 6%' . In automotive, these structures can suggest gears based on speed levels, allowing refined control over operational decisions like shifting from 'Gear 1' to 'Gear 4 or 5' depending on the speed . This structured decision-making process enhances program flexibility and accuracy in complex, real-world applications.

Efficient use of data structures like lists, tuples, and dictionaries is crucial when managing complex datasets in banking and automotive sectors, as it directly impacts system performance and maintenance. Lists are useful for ordered collections and indexing, ideal for transaction records. Tuples, being immutable, provide data integrity and are suited for fixed datasets like fixed vehicle attributes. Dictionaries offer rapid access and dynamic modifications using keys, excellent for storing client details and specifications. Efficient data structuring facilitates faster data retrieval, reduces processing time, and enhances scalability—a key aspect for handling large databases and ensuring operation efficiency . Proper structure usage supports robust, responsive, and maintainable systems.

Neglecting or improperly using the 'else' clause in 'if-else' statements can lead to incomplete decision-making processes, potentially causing logical errors and adverse results in applications like banking and automotive systems. Without an 'else' clause, systems may fail to handle conditions comprehensively, leading to unaddressed scenarios. For example, in banking, mishandling withdrawal conditions without 'else' might result in denying service without informing users about balance issues . Similarly, in automotive systems, neglecting 'else' could miss alerts for engine conditions not meeting specific criteria but still requiring attention. Ensuring all logical branches are covered prevents overlooked conditions, enhancing reliability and user satisfaction.

You might also like