SRI HARSHA INSTITUTE OF P.G.
STUDIES
PYTHON PROGRAMMING
6. To create a Python program that simulates basic banking operations such as balance inquiry,
deposit, and withdrawal, while ensuring that these operations are accessible only to
authenticated users.
Procedure:
1. Define a validUser() function:
Prompt the user to enter username and password
If the username and password match predefined credentials, return True;
otherwise, return False.
2. Define Account class:
Initialize the account with the user’s name and an initial balance.
Define a method getBalance():
Check if the user is valid using validUser()
If valid, return the balance; otherwise, deny access.
Define a method deposit(amount):
Check if the user is valid using validUser().
If valid, add the amount to the balance and display the updated balance;
otherwise, deny access.
Define method withdraw(amount):
Check if the user is valid using validUser()
If valid and sufficient funds are available, deduct the amount form the
balance; otherwise, display error.
3. Create an account class instance with a name and initial balance.
4. Allow the user to perform operations such as checking balance, depositing money,
withdrawing money by calling the respective methods.
5. Display the results of each of the operations.
21
SRI HARSHA INSTITUTE OF P.G. STUDIES
Program:
Python File Name: [Link]
def validUser():
username = input("Enter username: ")
password = input("Enter password: ")
if username == 'ali' and password == 'ali123':
return True
else:
return False
class Account:
def init (self, name, initialBalance):
self. name = name
self. balance = initialBalance
def getBalance(self):
is_valid_user = validUser()
if is_valid_user:
return self. balance
else:
return "You are not authorized to access balance."
def deposit(self, amount):
is_valid_user = validUser()
if is_valid_user:
self. balance = self. balance + amount
22
SRI HARSHA INSTITUTE OF P.G. STUDIES
print("Your current balance is: {}".format(self. balance))
else:
return "You are not authorized to deposit."
def withdraw(self, amount):
is_valid_user = validUser()
if is_valid_user:
if self. balance >= amount:
self. balance = self. balance - amount
print("Your current balance is: {}".format(self. balance))
else:
return "Insufficient balance."
else:
return "You are not authorized to withdraw."
# Accounts class instance:
account = Account("ali", 1000)
# Check balance
balance = [Link]()
print(balance)
# Deposit money
[Link](2000)
# Withdraw money
[Link](500)
23
SRI HARSHA INSTITUTE OF P.G. STUDIES
Output:
Enter username: ali
Enter password: ali123
Output:
Your current balance is: 1000
Enter username: ali
Enter password: ali123
Enter deposit amount: 2000
Your current balance is: 3000
Enter username: ali
Enter password: ali123
Enter withdrawal amount: 500
Your current balance is: 2500
24
SRI HARSHA INSTITUTE OF P.G. STUDIES
7 . write a Python program to implement Object oriented Programming feature Polymorphism for the use case:
functions and objects.
Procedure:
1. Define a polyFun(obj) function:
It calls countryCapital () method on obj
It calls countryLanguage() method on obj.
It calls countryType() method on obj.
2. Define India class:
Initialize India class with country capital, country language and country type
Define countryCapital() method
o It prints the India capital name
Define countryLanguage() method
o It prints the India Language
Define countryType() method
o It prints the India country type
3. Define Usa class:
Initialize Usa class with country capital, country language and country type
Define countryCapital() method
o It prints the USA capital name
Define countryLanguage() method
o It prints the USA Language
Define countryType() method
o It prints the USA country type
4. Create India class instance with country capital, country language and country type as
indiaObj.
5. Create Usa class instance with country capital, country language and country type as
usaObj.
6. Call the function polyFun(obj) by passing indiaObj and display the results.
7. Call the function polyFun(obj) by passing usaObj and display the results.
25
SRI HARSHA INSTITUTE OF P.G. STUDIES
Program:
Python File Name: [Link]
def polyFun(obj):
[Link]()
[Link]()
[Link]()
class India:
def init (self, capitalName, languageName, cType):
[Link] = capitalName
[Link] = languageName
[Link] = cType
def countryCapital(self):
print("{} is the capital of India".format([Link]))
def countryLanguage(self):
print("{} is the mostly used language in India".format([Link]))
def countryType(self):
print("India is {}".format([Link]))
class Usa:
def init (self, capitalName, languageName, cType):
[Link] = capitalName
[Link] = languageName
[Link] = cType
def countryCapital(self):
print("{} is the capital of USA".format([Link]))
26
SRI HARSHA INSTITUTE OF P.G. STUDIES
def countryLanguage(self):
print("{} is the mostly used language in USA".format([Link]))
def countryType(self):
print("USA is {}".format([Link]))
#capturing user input
capital = input("Enter India capital:")
languageName = input("Enter India national language:")
countryType = input("Enter India country type:")
#creating India class instance
indiaObj = India(capital, languageName, countryType)
#capturing user input
capital = input("Enter USA capital:")
languageName = input("Enter USA national language:")
countryType = input("Enter USA country type:")
#creating Usa class instance
usaObj = Usa(capital, languageName, countryType)
#calling function by passing indiaObj
polyFun(indiaObj)
#calling function by passing usaObj
polyFun(usaObj)
27
SRI HARSHA INSTITUTE OF P.G. STUDIES
Output:
E:\pythonworks>python [Link]
Enter India capital:delhi
Enter India national language:hindi
Enter India country type:developing country
Enter USA capital:washington
Enter USA national language:english
Enter USA country type:developed country
delhi is the capital of India
hindi is the mostly used language in India
India is developing country
washington is the capital of USA
english is the mostly used language in USA
USA is developed country
28
SRI HARSHA INSTITUTE OF P.G. STUDIES
8. Write a Python program to create list by taking input from user and min, max, sum and
sorted list.
Procedure:
1. Create a function createList() to create list:
Prompts the user to enter the values into list
2. Create a function dispList() to display lsit:
It displays the list
3. Create a function findCount() to find number of elements:
It displays number of elements in the list.
4. Create a function findMax() to find max element in the list
It finds the maximum element in the list
5. Create a function findMin() to find min element in the list
It find minimum element in the list
6. Create a function findSum() to find sum of the elements in the list:
It find sum of the elements in the list.
7. Create a function listSort() to find sorted list.
8. Call these functions and display the results.
29
SRI HARSHA INSTITUTE OF P.G. STUDIES
Program:
Python file name : [Link]
def findCount():
print("List contains {} elements".format(len(lst)))
def findMax():
print("The maximum element in the list is {}".format(max(lst)))
def findMin():
print("The minimum element in the list is {}".format(min(lst)))
def findSum():
sum = 0
for i in lst:
sum = sum + i
print("The sum of elements in the list is {}".format(sum))
def dispList():
print(lst)
def listSort():
print("sortered List : ",sorted(lst))
def createList():
for i in range(n):
lstValue = int(input("Enter value:"))
[Link](lstValue)
#reading input
n = int(input("Enter length of list:"))
#Creating empty list
30
SRI HARSHA INSTITUTE OF P.G. STUDIES
lst = []
#calling functions
createList()
dispList()
findCount()
findMax()
findMin()
findSum()
listSort()
Output:
E:\pythonworks>python [Link]
Enter length of list:5
Enter value:10
Enter value:30
Enter value:20
Enter value:40
Enter value:50
[10, 30, 20, 40, 50]
List contains 5 elements
The maximum element in the list is 50
The minimum element in the list is 10
The sum of elements in the list is 150
sortered List : [10, 20, 30, 40, 50]
31
SRI HARSHA INSTITUTE OF P.G. STUDIES
9. Write a program to draw bar chart horizontal and vertical bars using Matplotlib.
Procedure:
1. Import Numpy library using command pip install numpy
2. Import Matplotlib library using command pip install matplotlib
3. Create a function read_X_Values() to read values for x-axis
Prompts user the message “Please Enter X-axis values:”
Prompts the user to enter value:
Creates list for X-axis.
4. Create a function read_Y_Values() to read values for x-axis
Prompts user the message “Please Enter Y-axis values:”
Prompts the user to enter value:
Creates list for Y-axis.
5. Create a function drawHorizontalBar():
It draws the Horizontal Bar.
6. Create a function drawVerticalBar():
It draws the Vertical Bar
7. Allow the user to enter number of values on X-axis and Y-axis.
8. Call the above functions and displays the output.
9. End.
32
SRI HARSHA INSTITUTE OF P.G. STUDIES
Program:
Python file name: [Link]
# importing the necessary libraries and modules
import [Link] as plt
import numpy as np
def read_X_Values():
print("Please Enter X-axis values:")
for i in range(xNum):
dataValues = input("Enter value:")
[Link](dataValues)
def read_Y_Values():
print("Please Enter Y-axis values:")
for i in range(yNum):
dataValues = int(input("Enter value:"))
[Link](dataValues)
def drawHorizontalBar():
[Link](xValues,yValues)
# to show our graph
[Link]()
def drawVerticalBar():
[Link](xValues,yValues)
# to show our graph
[Link]()
33
SRI HARSHA INSTITUTE OF P.G. STUDIES
# creating the data values for the vertical y and horisontal x axis
xNum = int(input("Enter number of values on X-axis:"))
yNum = int(input("Enter number of values on Y-axis:"))
#creating empty list for X-axis and Y-axis
xValues = []
yValues = []
if xNum != yNum:
print("Invalid Input values; pls enter same number of elements for both X-axis and Y-
axis")
else:
read_X_Values()
read_Y_Values()
drawHorizontalBar()
drawVerticalBar()
34
SRI HARSHA INSTITUTE OF P.G. STUDIES
Output:
Enter number of values on X-axis:4
Enter number of values on Y-axis:4
Please Enter X-axis values:
Enter value:Oranges
Enter value:Apples
Enter value:Mangos
Enter value:Berries
Please Enter Y-axis values:
Enter value:10
Enter value:20
Enter value:30
Enter value:40
35
SRI HARSHA INSTITUTE OF P.G. STUDIES
36
SRI HARSHA INSTITUTE OF P.G. STUDIES
10. Develop Python program to implement instance variable concept for ATM class
Procedure:
1. Define ATM class:
Initialize ATM class with customer name and initial balance
Define deposit() method
o It checks amount is positive or not; If the amount is positive, adds it to
the balance; otherwise, displays error message
Define withdraw() method
o It checks withdraw amount is less than the available balance
o If withdraw amount is less than the available balance, amount will be
deducted from the balance
o If the withdraw amount is more than the available balance, error
message will be displayed.
Define checkBalance () method
o It display customer name along with available balance.
2. Read customer name and initial balance from the keyboard
3. Create ATM class object
4. Call checkBalance() method to check the balance
5. Call deposit() method to deposit certain amount
6. Call withdraw() method to withdraw certain amount
7. Call withdraw() method with overflow amount.
8. Display the output
9. stop
37
SRI HARSHA INSTITUTE OF P.G. STUDIES
Program:
Python file name: [Link]
class ATM:
def init (self, customerName, balance=0.0):
[Link] = customerName
[Link] = balance
def deposit(self,amount):
if amount > 0:
[Link] += amount
print(f"{amount} successfully deposited. New Balance : {[Link]}")
else:
print("Deposit amount must be positive")
def withdraw(self, amount):
if 0 < amount <= [Link]:
[Link] -= amount
print(f"{amount} withdrawn successfully. New balance: {[Link]}")
elif amount > [Link]:
print("Insufficient funds!")
else:
print("Withdrawal amount must be positive!")
38
SRI HARSHA INSTITUTE OF P.G. STUDIES
def checkBalance(self):
print(f"Customer Name: {[Link]}, Balance: {[Link]}")
name = input("Enter Customer Name:")
initialBalance = int(input("Enter Intial amount:"))
account1 = ATM(name, initialBalance)
[Link]()
[Link](2000)
[Link](1500)
[Link](6000) # Insufficient funds scenario
Output:
Enter Customer Name:anil
Enter Intial amount:5000
Customer Name: anil, Balance: 5000
2000 successfully deposited. New Balance : 7000
1500 withdrawn successfully. New balance: 5500
Insufficient funds!
39