Python Programming Basics Guide
Python Programming Basics Guide
DEPARTMENT OF COMPUTER
SCIENCE AND BUSINESS SYSTEMS
STUDY MATERIAL
INTRODUCTION TO
PYTHON PROGRAMMING
Prepared by :
Applications:
Banking:
Account numbers
Number of failed login attempts
Number of transactions
Automotive:
Engine RPM
Number of wheels
Gear position
# 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
# 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 +, -, *, //, %, ** +, -, *, /, **
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.
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.
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
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"
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
Examples
Banking:
customer_name = "Arjun"
account_balance = 12000
Automotive:
speed = 65.4
gear = 3
status = "Running"
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")
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
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).
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
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.
Examples
Banking:
balance = 15000
account_status = "Active"
Automotive:
speed = 105
engine_temp = 98
Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 11
Module1: Python Basics & Flow Control Control
Examples
Banking:
balance = 6000
account_type = "Savings"
kyc_verified = True
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.
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).
Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 13
Module1: Python Basics & Flow Control Control
Examples
Banking:
balance = 8000
min_balance = 5000
Automotive:
engine_temp = 102
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.
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)
if Statement
What it is?
The if statement checks a single condition, and executes the block if it evaluates to True.
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.
Syntax:
if condition:
# code if true
else:
# code if false
Examples:
Banking:
balance = 3000
withdraw = 4000
Automotive:
engine_temp = 85
if-elif-else Ladder
What it is?
Used when there are multiple conditions, checked one-by-one.
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
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.
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.
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.
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.
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
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")
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
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")
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.
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)
Examples
Banking – Using datetime:
import datetime
today = [Link]()
print("Date of Transaction:", today)
for i in range(3):
print("Sensor Reading", i)
[Link](2) # waits for 2 seconds
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
Examples
Banking – Use from datetime import date:
from datetime import date
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.
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
if condition_to_exit:
[Link]("Reason for exiting")
pin_attempts = 0
if pin_attempts == 3:
[Link]("Too many failed attempts. Program terminated.")
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:
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.
Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 27
Module1: Python Basics & Flow Control Control
if guess != secret_number:
print("Sorry, you've run out of attempts. The number was", secret_number)
if entered_pin != correct_pin:
[Link]("Card Blocked. Too many failed attempts.")
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
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.
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
Automotive Example:
def engine_status(temp):
if temp > 100:
return "Overheating"
else:
return "Normal"
Summary Table
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)
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
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
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")
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
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.
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.")
Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 36
Module2: Functions & Lists
Full Program:
import random
import sys
def guess_game():
global attempts
secret_number = [Link](1, 10)
max_attempts = 5
attempts += 1
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
How to Apply?
Banking:
transactions = [1000, -500, 2000, -300]
Automotive:
speed_log = [45, 52, 60, 72]
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.
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]
How to Apply?
Banking:
recent_txns = transactions[-3:]
Automotive:
first_two_speeds = speed_log[0:2]
How to Apply?
Banking:
print(len(transactions)) # Total number of transactions
Automotive:
print(len(speed_log)) # Total speed readings
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
How to Apply?
Banking:
all_txns = old_txns + new_txns
Automotive:
simulated_data = [70] * 5
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
How to Apply?
Banking:
for t in transactions:
print("Transaction:", t)
Automotive:
for speed in speed_log:
print("Speed:", speed)
How to Apply?
Banking:
if -500 in transactions:
print("Withdrawal detected")
Automotive:
if 80 in speed_log:
print("High speed recorded")
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]
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")
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
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.
How to Apply?
import pprint
vehicle_log = {
"speed": 120,
"alerts": {"ABS": False, "Airbag": True},
"location": {"lat": 12.9716, "lon": 77.5946}
}
[Link](vehicle_log)
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]
print_summary(customers["1001"])
How to Apply?
String Creation and Concatenation
vehicle = "Tesla"
model = "Model X"
full_name = vehicle + " " + model
print(full_name) # Tesla Model X
Output:
SPEED => 80
TEMP => 95
RPM => 3000
Output:
Dear Customer, your a/c 5678 has balance ₹50200.75
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)
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
Banking
cust_name = "Anjali Mehta"
txn_id = 938274
status = "SUCCESS"
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
How to Apply?
ord() – Character → Unicode number
print(ord('A')) # 65
print(ord('z')) # 122
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().
How to Apply?
Step 1: Install the module
pip install pyperclip
diagnostic = "OBD Error: P0138 - Oxygen Sensor High Voltage (Bank 1 Sensor 2)"
[Link](diagnostic)
print("Copied to clipboard for emailing or logging.")
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.")
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!"
}
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
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."
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")
log_dir = Path("/vehicle_logs/2025/06/")
if not log_dir.exists():
log_dir.mkdir(parents=True)
today = [Link]().strftime('%Y-%m-%d')
report_dir = Path(f"./reports/{today}")
report_dir.mkdir(parents=True, exist_ok=True)
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).
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')
Other options:
[Link]() – Reads one line
[Link]() – Returns all lines as a list
Automotive Example
Writing to a File
with open("[Link]", "w") as f:
[Link]("This will overwrite the file.")
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.
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.
How to Apply?
Saving Data to a Shelf
import shelve
test_data = {
"RPM_Limit": 6500,
"Temp_Threshold": 105.0,
"Fuel_Map": [12.5, 13.0, 13.8]
}
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'
}
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).
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.
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
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
Output:
Customer ID: 123456 | Txn: TXN7890 | Amount: ₹2050.50
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.
But format() remains useful in contexts where more flexibility or older Python versions are in
use.
Verify installation:
import openpyxl
Real-World Examples
Banking: Read Customer Balance Sheet
wb = openpyxl.load_workbook('bank_data.xlsx')
sheet = wb['Accounts']
Useful when integrating CSV data into systems that don’t support headers.
with open('[Link]') as f:
data = [Link](f)
print(data['customer_id'])
Real-World Examples
Automotive: Save Sensor Readings to JSON
import json
sensor_data = {
"vehicle": "Altroz",
"rpm": 3000,
"temperature": 92.5
}
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]}")
How to Apply?
class Customer:
pass
cust1 = Customer()
Attributes
What it is?
Attributes are variables that belong to an object or class.
How to Apply?
class Car:
def __init__(self, make, speed):
[Link] = make
[Link] = speed
Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 64
Module5: Classes and Objects
How to Apply?
class Rectangle:
def __init__(self, width, height):
[Link] = width
[Link] = height
r = Rectangle(5, 10)
print([Link] * [Link])
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])
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)
How to Apply?
import copy
class Car:
def __init__(self, brand, speed):
[Link] = brand
[Link] = speed
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
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}")
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.
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)
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.
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
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
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]}"
Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M Page 69
Module5: Classes and Objects
def __str__(self):
return f"{[Link]} of ₹{[Link]}"
t = Transaction(1000, "Deposit")
print(t)
Can be extended for ATM, Online Transfer, etc.
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
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
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 __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%"
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
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.
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.
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.
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.
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.
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().
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.