I am trying to make a basic Grocery Store without prices - python

class Toptanci:
def __init__(self):
self.fruits = dict(apple=30, pear=40, cherry=20, banana=10, strawberry=15)
self.vegetables = dict(garlic=40, Tomatoes=30, Eggplant=40, Onion=25, Potato=15)
self.all_list = self.fruits and self.vegetables ## YANLIS OLABILIR !
def report(self): ### RAPOR
print(self.fruits and self.vegetables)
def is_resource_sufficient(self, purchase): ### YETERLI VAR MI DIYE BAK
can_purchase = True
for item in purchase.all_list:
if purchase.all_list[item] > self.all_list[item]:
print(f"Sorry there is not enough {item}")
can_purchase = False
return can_purchase
def order_purchase(self, order): ### GEREKLI AMOUNUT"U CIKAR
for item in order.all_list:
self.all_list[item] -= order.all_list[item]
print(f"Here is your {order}")
def main(self):
question1 = input("Fruits or Vegetables?").lower()
question2 = int(input("Please enter the KG amount you want ="))
question3 = input("Would you like something else? 'y' or 'n'").lower()
if question1 == 'fruits':
print(question2)
Basically, I am trying to get input from the user and deduct the amount from the base values. In addition, I want to add the amount I get from the Toptanci class into the Manav class. So when in Manav section the amount gathered will be added. In the Manav Class we should have the amount of vegetable or fruits bought and it should display the bought amount. So when another user tries to buy from Manav. It will see Manav's stock and the stock will be reduced accordingly.

Related

Currently doing a python udemy course, involving making a coffee machine using objects and class, I'm confused about this error

#Coffee Machine in OOP code
#Define the Moneymachine class first to process the money and currency received
class MoneyMachine:
CURRENCY = "$"
#write the coin values in a dictionary
COIN_VALUES = {
"quarters" : 0.25,
"dimes" : 0.1,
"nickles" : 0.05,
"pennies" : 0.01
}
#we write functions using init function to initialize
def __init__(self):
self.profit = 0
self.money_received = 0
def report(self):
#Prints the report of the current profit
print(f"Money: {self.CURRENCY}{self.profit}")
def process_coins(self):
#Returns the value of the total calculated coins inserted
print("Please insert coins.")
for coin in self.COIN_VALUES:
self.money_received += int(input(f"How many {coins}? ")) * self.COIN_VALUES[coin]
return self.money_received
#define the payment function
def make_payment(self,cost):
self.process_coins()
if self.money_received >= cost:
change = round(self.money_received - cost, 2)
print(f"Here is your {self.CURRENCY}{change} in change.")
self.profit += cost
self.money_received = 0
return True
#if payment is not enough, return False
else:
print("Sorry that's not enough money. Money refunded.")
self.money_received = 0
return False
#Next we define the Menu class and Menu items. We can model it using classes
class menuItem:
#put in all the ingredient variables and the cost ofcourse
def __init__(self, name, water, milk, coffee, cost):
self.name = name
self.cost = cost
self.ingredients = {
"water" : water,
"milk" : milk,
"coffee": coffee
}
#full menu with costs for different coffees
class menu:
"""Models the Menu with drinks."""
def __init__(self):
self.menu = [
MenuItem(name="latte", water=200, milk=150, coffee=24, cost=2.5),
MenuItem(name="espresso", water=50, milk=0, coffee=18, cost=1.5),
MenuItem(name="cappuccino", water=250, milk=50, coffee=24, cost=3),
]
def get_items(self):
#Returns all the names of the available menu items
options = ""
for item in self.menu:
options += f"{item.name}/"
return options
def find_drink(self, order_name):
#Searches the menu for a particular drink by name. Returns that item if it exists, otherwise returns None
for item in self.menu:
if item.name == order_name:
return items
print("Sorry that item is not available")
#After this we make the CoffeeMaker class to process the coffee
class CoffeeMaker:
#models the coffee Machine
def __init__(self):
self.resources = {
"water" : 300,
"milk" : 200,
"coffee": 100,
}
def report(self):
#prints out the report of the resources:
print(f"Water: {self.resources['water']}ml")
print(f"Milk: {self.resources['milk']}ml")
print(f"Coffee: {self.resources['coffee']}g")
def is_resource_sufficient(self,drink):
#Returns True when order can be made, False if ingredients are insufficient
can_make = True
for item in drink.ingredients:
if drink.ingredients[item] > self.resources[item]:
print(f"Sorry there is not enough {item}.")
can_make = False
return can_make
def make_coffee(self,order):
#Deducts the required ingredients from the resources
for item in order.ingredients:
self.resouces[item] -= order.ingredients[item]
print(f"Here's your {order.name}. Enjoy!")
#----------------------------------------------------------------------Python Part-----------------------------------------------------------------------#
money_machine = MoneyMachine()
coffee_maker = CoffeeMaker()
is_on = True
coffee_maker.report()
money_machine.report()
while is_on:
options = menu.get_items()
choice = input(f"What would you like? ({options}): ")
if choice == "off":
is_on = False
elif choice == "report":
coffee_maker.report()
money_machine.report()
else:
drink = menu.find_drink(choice)
if coffee_maker.is_resource_sufficient(drink) and money_machine.make_payment(drink.cost):
coffee_maker.make_coffee(drink)
Now it runs all fine during the course but whenever I run it, I get this error:
Traceback (most recent call last):
File "c:\Users\Armand S\Desktop\Python Files\D16 Coffee Machine in OOP.py", line 123, in <module>
options = menu.get_items()
TypeError: get_items() missing 1 required positional argument: 'self'
I have no idea what this error is and in need of help. Any suggestions?
I've looked for alot of solutions but I'm just confused as to why the functions in my while loop need more positional arguments (since I'm not using the def function? idk) so yeah I'm asking that. And if there are any more suggestions to make my code better then that would be appreciated.
You have to create an object of the main class first to access the get_items() method
Try the following -
menuObj = menu()
options = menuObj.get_items()
...
...
...
# Update the object name in the else as well
else:
drink = menuObj.find_drink(choice)
N.B: There are other issues in your code as well like spelling mistakes on variable names. One of them is you wrote 'coin' in the for loop but while printing you wrote 'coins'. Then there are 'menuItem' and 'MenuItem'. Do fix them as well.
You cannot directly call the get_items() method without creating an instance ( menu=menu() ) of the menu class, as it's not a classmethod.
The mistake behind this error is that you haven't defined an instance menu = Menu() (class names should begin with capital letter as per best practices) so I have changed it!
There are other variable mistakes in your code as well. However I have modified your code!
Here is your code after modifications:
class MoneyMachine:
CURRENCY = "$"
#write the coin values in a dictionary
COIN_VALUES = {
"quarters" : 0.25,
"dimes" : 0.1,
"nickles" : 0.05,
"pennies" : 0.01
}
#we write functions using init function to initialize
def __init__(self):
self.profit = 0
self.money_received = 0
def report(self):
#Prints the report of the current profit
print(f"Money: {self.CURRENCY}{self.profit}")
def process_coins(self):
#Returns the value of the total calculated coins inserted
print("Please insert coins.")
for coin in self.COIN_VALUES:
self.money_received += int(input(f"How many {coin}? ")) * self.COIN_VALUES[coin]
return self.money_received
#define the payment function
def make_payment(self,cost):
self.process_coins()
if self.money_received >= cost:
change = round(self.money_received - cost, 2)
print(f"Here is your {self.CURRENCY}{change} in change.")
self.profit += cost
self.money_received = 0
return True
#if payment is not enough, return False
else:
print("Sorry that's not enough money. Money refunded.")
self.money_received = 0
return False
class MenuItem:
#put in all the ingredient variables and the cost ofcourse
def __init__(self, name, water, milk, coffee, cost):
self.name = name
self.cost = cost
self.ingredients = {
"water" : water,
"milk" : milk,
"coffee": coffee
}
class Menu:
"""Models the Menu with drinks."""
def __init__(self):
self.menu = [
MenuItem(name="latte", water=200, milk=150, coffee=24, cost=2.5),
MenuItem(name="espresso", water=50, milk=0, coffee=18, cost=1.5),
MenuItem(name="cappuccino", water=250, milk=50, coffee=24, cost=3),
]
def get_items(self):
#Returns all the names of the available menu items
options = ""
for item in self.menu:
options += f"{item.name}/"
return options
def find_drink(self, order_name):
#Searches the menu for a particular drink by name. Returns that item if it exists, otherwise returns None
for item in self.menu:
if item.name == order_name:
return item
print("Sorry that item is not available")
class CoffeeMaker:
#models the coffee Machine
def __init__(self):
self.resources = {
"water" : 300,
"milk" : 200,
"coffee": 100,
}
def report(self):
#prints out the report of the resources:
print(f"Water: {self.resources['water']}ml")
print(f"Milk: {self.resources['milk']}ml")
print(f"Coffee: {self.resources['coffee']}g")
def is_resource_sufficient(self,drink):
#Returns True when order can be made, False if ingredients are insufficient
can_make = True
for item in drink.ingredients:
if drink.ingredients[item] > self.resources[item]:
print(f"Sorry there is not enough {item}.")
can_make = False
return can_make
def make_coffee(self,order):
#Deducts the required ingredients from the resources
for item in order.ingredients:
self.resources[item] -= order.ingredients[item]
print(f"Here's your {order.name}. Enjoy!")
money_machine = MoneyMachine()
coffee_maker = CoffeeMaker()
is_on = True
coffee_maker.report()
money_machine.report()
menu = Menu()
while is_on:
options = menu.get_items()
choice = input(f"What would you like? ({options}): ")
if choice == "off":
is_on = False
elif choice == "report":
coffee_maker.report()
money_machine.report()
else:
drink = menu.find_drink(choice)
if coffee_maker.is_resource_sufficient(drink) and money_machine.make_payment(drink.cost):
coffee_maker.make_coffee(drink)

How to reduce repeated code with different variable names (python)

class Budget:
def __init__(self):
self.wants_perc = 0
self.wants_amt = 0
self.wants_left = 0
self.needs_perc = 0
self.needs_amt = 0
self.needs_left = 0
self.food_perc = 0
self.food_amt = 0
self.food_left = 0
while True:
try:
self.monthly_income = float(input("Enter your monthly income after taxes: "))
break
except ValueError:
print("Invalid Input : Please enter a number")
continue
while True:
print("Enter desired percentage of income spent for each category (do not include %): ")
try:
self.wants_perc = float(input("Wants: "))
self.needs_perc = float(input("Needs: "))
self.food_perc = float(input("Food: "))
if self.wants_perc + self.needs_perc + self.food_perc not in range(95, 105):
print("Invalid Input : Must add to 100%")
continue
else:
break
except ValueError:
print("Invalid Input : Please enter a number")
continue
def deposit(self):
dep_loc = input("Where would you like to deposit? ")
while True:
try:
if dep_loc.lower() == "wants":
self.wdep_amt = float(input("Deposit amount: "))
self.wants()
break
elif dep_loc.lower() == "needs":
self.ndep_amt = float(input("Deposit amount: "))
self.needs()
break
elif dep_loc.lower() == "food":
self.fdep_amt = float(input("Deposit amount: "))
self.food()
break
else:
print("Invalid Input")
break
except ValueError:
print("Invalid Input : Please enter a number")
continue
def wants(self):
self.wants_max = (self.wants_perc / 100) * self.monthly_income
self.wants_amt += self.wdep_amt
self.wants_left = self.wants_max - self.wants_amt
print(f"Amount spent on wants: ${self.wants_amt} \nAmount left to spend: ${round(self.wants_left,2)}")
def needs(self):
self.needs_max = (self.needs_perc / 100) * self.monthly_income
self.needs_amt += self.ndep_amt
self.needs_left = self.needs_max - self.needs_amt
print(f"Amount spent on needs: ${self.needs_amt} \nAmount left to spend: ${round(self.needs_left,2)}")
def food(self):
self.food_max = (self.food_perc / 100) * self.monthly_income
self.food_amt += self.fdep_amt
self.food_left = self.food_max - self.food_amt
print(f"Amount spent on food: ${self.food_amt} \nAmount left to spend: ${round(self.food_left,2)}")
wyatt = Budget()
while True:
wyatt.deposit()
I know this is a very general question, but is it possible to reduce the amount of repeated code I use? I feel like there has to be a way to use one general variable in a loop for each of the categories. My three functions that use the food, wants, and needs variables are all the exact same besides the names. I thought of getting user input and adding it to a list and indexing that list to get each category, but I couldn't fully figure it out. This may be too broad for stack overflow and if it is I apologize. Thanks!
In general there is no mechanism for reducing the amount of code - if there was, it would already be part of the language. Making a dictionary instead of member variables doesn't really help, because all it will do is replace your 9 member variables with 9 dictionary items.
However, there is an opportunity for factoring out repeated operations. Your instinct is correct that repeated blocks of code are a sign of poor design. I would suggest you start with a class structure something like this:
class BudgetItem:
def __init__(self, name):
self.name = name
self.perc = 0
self.amt = 0
self.left = 0
def get_perc(self):
self.perc = float(input(f"{self.name}: "))
class Budget:
def __init__(self, monthly_income):
self.monthly_income = monthly_income
self.wants = BudgetItem("Wants")
self.needs = BudgetItem("Needs")
self.food = BudgetItem("Food")
self.all_items = (self.wants, self.needs, self.food)
def gather_percentages(self):
print("Enter desired percentage of income"
" spent for each category (do not include %): ")
for b in self.all_items:
b.get_perc()
if 95.0 <= sum(b.perc for b in self.all_items) <= 105.0:
print("Precentages must sum to 100")
# etc.
Create a separate class to represent a budget category, since the logic for each is identical. Add methods to the little class to capture that logic. Now re-write your main class in terms of those three individual items. I won't take the time to refactor your whole program, but I hope you get the idea. You should end up with a much shorter program and no significant repeated logic.
One other thing: I think that putting an "input" statement in a class constructor is a terrible idea. Constructors should not contain complicated loops or extended logic. I would put it outside the class and pass the data into the class as arguments, or as method calls.

Extracting a tuple value from a dictionary in python

am working on a restaurant project, and I need a hand :)
so the program will display the main dishes, and the user has to enter which dish he/she wants..
and then the choice will be taken and then added to the bill (dish name, price, num of items)...
so far I chose a dictionary so when the user enters 1 (key), the program will display Mashroum Risto...
this what've created:
dishes = {1 : ('Mashroum Risito', 3.950), 2 : ['Tomato Pasta', 2.250],3:['Spagehtie',4.850]}
now my question is how to get the dish name without the price (the price is 3.950) and extract it! and also how to get the price without the name so then I can send it into the bill function to calculate it? and if you have any suggestions please go ahead, because i don't know if using dictionary was the right choice
def MainDish():
dishes = {1 : ('Mashroum Risito', 3.950), 2 : ['Tomato Pasta', 2.250],3:
['Spagehtie',4.850]}
dishes.values
print("1. Mashroum Risito 3.950KD")
print("2. Tomato Pasta 2.250KD")
print("3. Spagehtie 4.850KD")
choice = eval(input('Enter your choice: '))
NumOfItem = eval(input('How many dish(es): '))
while(choice != 0):
print(dishes.get(choice)) #to display the item only without the
price
a = dishes.values()
recipient(a)
break
The way you have implemented it:
print (dishes[1][0]) #will give you name
print (dishes[1][1]) #will give you price
where [x][y]
x = key in the dict (input in your case)
y = element of the value in the dict (0 = name, 1=price in your case)
You should probably create the dictionary better as below:
Follow up question is not so clear but I think this is what you are after roughly. You will need to tweak the returns to your usage:
def MainDish():
NumOfItem = float(input('How many dish(es): '))
dish = list(dishes)[choice-1]
cost_of_dish = dishes[dish]
totalcost = cost_of_dish * NumOfItem
print (f"\n\tOrdered {NumOfItem}x {dish} at {cost_of_dish}KD each. Total = {totalcost}KD\n")
return dish, cost_of_dish, totalcost
dishes = {'Mashroum Risito': 3.950, 'Tomato Pasta': 2.250}
for key,val in dishes.items():
print (f"{list(dishes).index(key)+1}. {key}: {val}KD")
keepgoing = True
while keepgoing:
choice = int(input('Enter your choice: '))
if choice == 0:
keepgoing = False
break
else:
dish, cost_of_dish, totalcost = MainDish()

Having trouble exporting user input to txt file in Python

So long story short, I have been working on a Python program and I have been trying to get what the user inputs into the program to a txt file - I received some help online overall, but a bit stumped here.. Need it to include index, make, model, color, year and mileage of the vehicles that have been input (basically what is visible in the output when user hits "4" at main menu). The idea is when user hits "6" , that list/ data will be exported to txt file named "Vehicle Inventory" and then Exit the application. The issue is definitely around end of code at elif ch == 6: ... Any assistance or resolution on this would be appreciated !! Here is what I have so far:
# automobile class
class automobile:
# constructor
def __init__(self, make="", model="", color="", year=2018, mileage=0):
self.make = make
self.model = model
self.color = color
self.year = year
self.mileage = mileage
# setter methods
def set_make(self, make):
self.make = make
def set_model(self, model):
self.model = model
def set_color(self, color):
self.color = color
def set_year(self, year):
self.year = year
def set_mileage(self, mileage):
self.mileage = mileage
# getter methods
def get_make(self):
return self.make
def get_model(self):
return self.model
def get_color(self):
return self.color
def get_year(self):
return self.year
def get_mileage(self):
return self.mileage
# end of automobile class
# method to add a new vehicle to the inventory
def add_vehicle(v_list):
make = input("Enter make: ")
model = input("Enter model: ")
color = input("Enter color: ")
year = int(input("Enter year: "))
mileage = int(input("Enter mileage: "))
v = automobile(make, model, color, year, mileage)
v_list.append(v)
print("*** VEHICLE ADDED SUCCESSFULLY...")
# method to remove a vehicle from the inventory
def remove_vehicle(v_list):
index = int(input("Enter the index # of vehicle you would like to remove: "))
if index >= 0 and index < len(v_list):
make = v_list[index].get_make()
model = v_list[index].get_model()
v_list.pop(index)
print(make, model, "HAS BEEN REMOVED FROM INVENTORY !")
else:
print("*** INVALID INDEX #... PLEASE TRY AGAIN")
# method to update a vehicle info in the inventory
def update_vehicle(v_list):
index = int(input("Enter the index # of vehicle you would like to update: "))
if index >= 0 and index < len(v_list):
make = input("Enter new make: ")
model = input("Enter new model: ")
color = input("Enter new color: ")
year = int(input("Enter new year: "))
mileage = int(input("Enter new mileage: "))
v_list[index].set_make(make)
v_list[index].set_model(model)
v_list[index].set_color(color)
v_list[index].set_year(year)
v_list[index].set_mileage(mileage)
print("*** UPDATED SUCCESSFULLY !")
else:
print("*** INVALID INDEX #... PLEASE TRY AGAIN")
# method to print all vehicle details in proper formatted order
def display_vehicles(v_list):
print('{:10} {:10} {:10} {:10} {:10} {:10}'.format('INDEX #', 'MAKE', 'MODEL', 'COLOR', 'YEAR', 'MILEAGE'))
for i in range(len(v_list)):
v = v_list[i]
print('{:10} {:10} {:10} {:10} {:10} {:10}'.format(str(i), v.get_make(), v.get_model(), v.get_color(), str(v.get_year()), str(v.get_mileage())))
v_list = [] # initial list
# looping infinitely
while True:
# showing menu
print("1. Add a vehicle")
print("2. Remove a vehicle")
print("3. Update a vehicle")
print("4. Display all vehicle inventory")
print("5. Exit")
print("6. Export to 'Vehicle Inventory' txt file and Exit")
# getting choice
ch = int(input("*** PLEASE CHOOSE AN OPTION: "))
# performing actions based on choice
if ch == 1:
add_vehicle(v_list)
elif ch == 2:
remove_vehicle(v_list)
elif ch == 3:
update_vehicle(v_list)
elif ch == 4:
display_vehicles(v_list)
elif ch == 5:
break;
elif ch == 6:
with open('Vehicle Inventory.txt', 'w') as filehandle:
for display_vehicles in v_list:
filehandle.write("%s\n" % display_vehicles)
break;
else:
print("*** INVALID OPTION... PLEASE TRY AGAIN")
Executing your code, the txt file contains lines such as
<__main__.automobile object at 0x0000017F5E7017C0>.
The problem is that at line filehandle.write("%s\n" % display_vehicles) pass an object reference as data to be written to the file. As far as I know, there is no ready-made function that allows you to pass a file an object reference and have the data auto-extracted from it. If you really want to use a txt file, you can do something like this:
with open('Vehicle Inventory.txt', 'w') as filehandle:
for display_vehicles in v_list:
filehandle.write("make: {}, model: {}, color: {}, year: {}, mileage:{} \n".format(display_vehicles.get_make(),display_vehicles.get_model(),display_vehicles.get_color(),display_vehicles.get_year(),display_vehicles.get_mileage()))
Output
make: car, model: a, color: red, year: 2020, mileage:20
make: car2, model: b, color: black, year: 10, mileage: 10
A brief explanation of Format.
Format allows you to insert values into a string using a style based on placeholders. {} correspond to anonymous placeholders: this means that the value that goes in that position depends on the order used inside .format(value1, value2, ...).
Alternatively, you can use named placeholders such as:
"my car is {color} and i bought it in {year}".format(color= "red", year= 2010)
About the txt file
Personally I would not use a txt file, especially since loading data from this type of file can be quite annoying in cases where you are only interested in a few rows or a certain value of each row (e.g.: all red cars). I don't know if the txt file is mandatory for you, so I won't provide any detailed info on the following alternative methods. In any case, you should know that there are other types of files that are widely used for storing information.
Json. The data are stored into a dictionary, i.e. a set of key-value pairs. Reading and writing files is trivial thanks to the json module
Csv. This is very similar to a txt but has a more structured form, as if it were a table. Each row corresponds to a record, each record consists of columns. Thanks to pandas, it is easy to use csv to extract subsets of data based on the value contained in the records or the row index. The file structure also allows you to quickly create graphs and export data to Excel.
Pickle. If you don't even care about human-friendly representation but just want to save the data permanently to a file, you could try pickle

Is the example below considered efficient? And if not, how so can it be better?

I am new to programming and object-oriented programming.
Below is a portion of the code in python that is running just fine as intended. I have hard-coded some variable for testing purposes at the open_bank_account().
Question: Would be considered fairly optimal and efficient? If not, where can I look to improve the code?
class Bank_Account:
def __init__(self, account_id, account_pin, account_balance):
self._account_id = account_id
self._account_pin = account_pin
self._account_balance = account_balance
self._individual_bank_account_dicitionary = {}
self._individual_bank_account_dicitionary[account_id] = {"Pin": account_pin, "Balance": account_balance}
def get_bank_account_balance(self, account_id):
return "Balance: ${:.2f}".format(self._individual_bank_account_dicitionary[account_id]["Balance"])
def __str__(self):
return "{}".format(self._individual_bank_account_dicitionary)
class Bank:
def __init__(self, bank_name):
self._bank_name = bank_name
self._bank_dicitionary = {}
def update_bank_dictionary(self, bank_account):
self._bank_dicitionary[bank_account._account_id] = {"Pin": bank_account._account_pin, "Balance": bank_account._account_balance}
# 1. A method to return the dictionary of bank accounts of the object from class Bank.
# 2. In this case, only bank_1 from main() is the object argument.
def get_bank_dictionary(self):
return self._bank_dicitionary
# 1. Method to create object bank_account only when needed.
def get_bank_account(self, account_id):
account_pin = self._bank_dicitionary[account_id]["Pin"]
account_balance = self._bank_dicitionary[account_id]["Balance"]
bank_account = Bank_Account(account_id, account_pin, account_balance)
return bank_account
# 1. This is used to convert the dictionary into a string for printing purposes.
def string_bank_dictionary(self):
string_list = ["account ID: {} \naccount Pin: {} \nBank Balance: {} \n".format(key, self._bank_dicitionary[key]["Pin"], self._bank_dicitionary[key]["Balance"])\
for key, value in self._bank_dicitionary.items()]
return "\n".join(string_list)
def __str__(self):
return "{}".format(self.string_bank_dictionary())
def open_bank_account(bank):
# # Uncomment out when running actual program.
# account_id = input("Enter account id here: ")
# account_pin = input("Enter account pin here: ")
# account_balance = input("Enter account initial balance here: ")
# Comment out when running actual program.
# Currently in used for testing purposes.
account_id = 455
account_pin = 123
account_balance = 888
bank_account = Bank_Account(account_id, account_pin, account_balance)
bank.update_bank_dictionary(bank_account)
# Comment out when running actual program.
# Currently in used for testing purposes.
account_id = 777
account_pin = 777
account_balance = 1
bank_account = Bank_Account(account_id, account_pin, account_balance)
bank.update_bank_dictionary(bank_account)
# Comment out when running actual program.
# Currently in used for testing purposes.
account_id = 631
account_pin = 222
account_balance = 50
bank_account = Bank_Account(account_id, account_pin, account_balance)
bank.update_bank_dictionary(bank_account)
return bank
def check_bank_blanance(bank):
valid_id_password = False
temporary_dictionary = bank.get_bank_dictionary()
while True:
account_id = int(input("Enter account id here: "))
account_pin = int(input("Enter account pin here: "))
for key in temporary_dictionary.keys():
if account_id == key and temporary_dictionary[account_id]["Pin"] == account_pin:
valid_id_password = True
bank_account = bank.get_bank_account(account_id)
print(bank_account.get_bank_account_balance(account_id))
break
if valid_id_password == True:
break
else:
print("Invalid account id/password. Please try again.")
def main():
bank_1 = Bank("ABC Bank")
while True:
print("Menu \n1. Open bank account \n2. Check balance")
while True:
account_choice = int(input("Enter option here: "))
if account_choice <= 0 and account_choice >= 7:
account_choice = int(input("Enter option here: "))
else:
break
if account_choice == 6:
break
elif account_choice == 1:
bank_1 = open_bank_account(bank_1)
elif account_choice == 2:
balance = check_bank_blanance(bank_1)
main()
The program works just fine. I would like to seek pointers on improvement if I code this better and more efficiently.
I have designed and kept only one object in the main(); i.e. bank_1; this contains a dictionary of the multiple bank account information. I have elected to only create the object bank_account at the open_bank_account() and check_bank_blanance() only when needed and these objects disappear once the function is done.
The intention here is to keep as little objects available as possible at the main().
No errors encountered. The program runs just fine; just enter <1>, then enter <2>, then enter <777> followed by <777>. It will print the bank account balance of $1.00 of the account id 777.

Categories

Resources