My program creates an Account object with an account id of 1122, a balance of $20,000, and an annual interest rate of 4.5%. It uses the withdraw method to withdraw $2,500, the deposit method to deposit $3,000, and print the id, balance, monthly interest rate, and monthly interest.
I am having problems with the next part which is that my program should also ask for the starting values for id, balance, and interest rate. Then it should present a menu where a user can modify their account. After each selection an appropriate message should be displayed. The menu should then be displayed again.
Example Menu:
(1): Display ID
(2): Display Balance
(3): Display Annual Interest Rate
(4): Display Monthly Interest Rate
(5): Display Monthly Interest
(6): Withdraw Money
(7): Deposit Money
(8): Exit
How can I modify my code to function properly with the user input? Right now it is working, but I don't have any code that asks the user for input.
This is the code that I have:
main module:
from Account import Account
def main():
updatedAccount = Account(1122,20000,4.5)
updatedAccount.withdraw(2500)
print("User ID : ", updatedAccount.id)
print("Beginning Balance: ", updatedAccount.balance)
print("Monthly Interest Rate: ", updatedAccount.monthly_interest_rate)
print("Monthly Interest: ", updatedAccount.get_monthly_interest())
main()
Account.py
class Account:
def __init__(self, id, initial_balance=0, rate=4.5):
self.id = id
self.balance = initial_balance
self.annual_interest_rate = rate
#property
def monthly_interest_rate(self):
return self.annual_interest_rate / 12
def get_monthly_interest(self):
return self.balance * self.monthly_interest_rate
def withdraw(self, amount):
if self.balance < amount:
raise ValueError(f"Overdraft, balance less than {amount}")
self.balance -= amount
def deposit(self, amount):
self.balance +=amount
I have tried writing user input for the starting account values, but I am having trouble using it to create the Account object and how to implement the menu.
userid = float(input("Enter User ID: "))
InterestRate = float(input("Enter Interest Rate: "))
balance = float(input("Enter balance: "))
print("User ID is: ", userid)
print("Interest Rate: ", InterestRate)
print("Balance is: ", balance)
You need to user the constructor of Account and provide the values you have
userid = float(input("Enter User ID: ")) // maybe use int() rather than float ?
interestRate = float(input("Enter Interest Rate: "))
balance = float(input("Enter balance: "))
acc = Account(userid, balance, interestRate)
print(acc)
If you override the __str__ method you can print the object just by calling print(acc)
// in Account class
def __str__(self):
return f"ID {self.id},Bal {self.balance}, Rat {self.annual_interest_rate}"
A simple way for the menu can be this, complete the if/elif code in the apply_actions and ad them in the same order in the actions array
def apply_actions(action, account):
if action == 0: # display ID
print(f"Your id is {account.id}")
elif action == 1: # display balance
print(f"Your balance is {account.balance}")
# ...
elif action == 6:
to_deposit = float(input("How many money for the deposit ?"))
account.deposit(to_deposit)
elif action == 7:
exit(1)
else:
print("Bad index")
if __name__ == '__main__':
# ...
acc = Account(userid, balance, interestRate)
actions = ["Display ID", "Display Balance", "Deposit", "Exit"]
while True:
choice = int(input("Choose index in " + str(list(enumerate(actions)))))
apply_actions(choice, acc)
You have two questions, regarding account creation, you do it normally using user input.
userid = float(input("Enter User ID: "))
InterestRate = float(input("Enter Interest Rate: "))
balance = float(input("Enter balance: "))
user_account = Account(userid, balance, InterestRate)
Now, for your menu, you can create a simple function displaying your menu and sending user to each function and when user is done send them back to your menu.
def menu():
possibilities = [(1, "Display ID", "id"), (2, "Display balance", "balance")]
while True:
for possibility in possibilities:
print(f"({possibility[0]}): {possibility[1]}")
User_input = int(input("Please select an option"))
if User_input in [pos[0] for pos in possibilities]:
option, name, attrib = [pos for pos in possibilities if pos[0] == User_input]
print(getattrib(Account, attrib))
else:
print("Option not avaliable")
Related
# PHASE 1 (FILE I/O with One Customer)
# Initialization of Current Balance ** Current Balance is the same for all users for the sake of simplicity **
myMoney = open("current_balance.txt")
currentBalance = int(myMoney.readline())
# Imports
import sqlite3
# Creation of Bank Account and Notifying User(s) of Current Balance
class Bank_Account:
def __init__(self):
self.balance= currentBalance
print("Welcome to Your Bank Account System!")
# If statements for first screen
def options_1(self):
ch = int(input("1. Create an Account\n2. Log into Your Account\nEnter a Choice: "))
if ch == 1:
self.create()
if ch == 2:
self.Log_in()
def options_2(self):
ch= int(input("1. Withdraw Money from Your Account\n2. Deposit Money to Your Account\nEnter a Choice: "))
if ch == 1:
self.withdraw()
if ch == 2:
self.deposit()
# Function to Create an Account
def create(self):
user_create = str(input("Enter a Username:"))
pin_create = int(input("Enter a Pin Number:" ))
print("Account successfully created!")
# Function to Log into Account
def Log_in(self):
user = str(input("Enter your username:"))
pin_create = int(input("Enter your Pin Number:"))
print("Welcome", user, "!")
# Function to Deposit Money
def deposit(self):
amount=float(input("Enter the amount you want to deposit: "))
self.balance += amount
print("Amount Deposited: ",amount)
# Function to Withdraw Money
def withdraw(self):
amount = float(input("Enter the amount you want to withdraw: "))
if self.balance>=amount:
self.balance-=amount
print("You withdrew: ",amount)
else:
print("Insufficient balance ")
def display(self):
print("Net Available Balance=",self.balance)
# Creating an object of class
self = Bank_Account()
# Calling functions with that class
self.options_1()
self.options_2()
self.create()
self.display()
# PHASE 2 (With Database)
# Define Connection and Cursor
connection = sqlite3.connect('Bank_Users.db')
cursor = connection.cursor()
# Create Users Table
command1 = """ CREATE TABLE IF NOT EXISTS
bank(pin INTEGER PRIMARY KEY, username TEXT)"""
cursor.execute(command1)
** This is my code so far. How do you create a database that represents each user? I'm trying to create a bank account management system where the user can create an account, log in, and withdraw/deposit money from that account. After completing the database portion of this project I plan on adding Tkinter GUI.***
I have create functions to simulate ATM system, when asking the user to make deposit everything goes well but the problem is when the user make a withdraw. If the amount is greater than the balance I have the new balance in negative value. And need some help to correct this behavior.
My functions:
def show_balance(balance):
print(f"Current Balance: ${balance}")
def deposit(balance):
amount = input("Enter amount to deposit: ")
amount = float(amount)
result = balance + amount
return result
def withdraw(balance):
withdraw = input("Enter amount to withdraw: ")
withdraw = float(withdraw)
result = balance - withdraw
return result
Here is when using the functions:
# Display ATM menu to user
while True:
option = input("Choose an option: ")
if option == "1":
account.show_balance(balance)
elif option == "2":
balance = account.deposit(balance)
account.show_balance(balance)
elif option == "3":
balance = account.withdraw(balance)
account.show_balance(balance)
while True:
if balance < 0:
print("You do not have this money?")
break
else:
print("Please, provide a valid option")
Now when adding 50 using option "2" everithing works well. When the withdraw is < the balance (55) it just return a nagative value (-5). I want to print the massage: "You do not have this money?", but also keep the balance to the right amount (50 -55) => balance remain 50 and ask the user to try again.
#AKX -> Based on your precious advice, I have fixed the function doing the following:
def withdraw(balance):
withdraw = input("Enter amount to withdraw: ")
withdraw = float(withdraw)
if withdraw <= balance:
result = balance - withdraw
return result
elif withdraw > balance:
print("You do not have this money?")
return balance
I have to write code to instantiate several objects (bank accounts) from a class. I wrote the functions for checking the balance, withdrawing, and depositing with a single object. However, I can't figure how to make it so that the class is repeated for each object. I also can't figure out how to make it so that the choice to check the balance, deposit, or withdraw from the object applies to the correct object. In addition to this, I don't know how to get the functions to check the balance, deposit, and withdraw to run for each object.
Code:
class Account:
def __init__(self, name, account_number, balance):
print("Welcome to the bank.")
self.name=name
self.account_number=account_number
self.balance=balance
def check_balance(self):
print ("Balance:", self.balance)
def deposit(self):
print("Current balance:", self.balance)
str2=input("How much would you like to deposit? ")
str2=int(str2)
print ("Current Balance:", self.balance + str2)
def withdraw(self):
print ("Current Balance", self.balance)
str4=input("How much would you like to withdraw? ")
str4=int(str4)
if self.balance - str4 < 0:
print("Unable to process. Doing this will result in a negative balance.")
elif self.balance - str4 >= 0:
print("Current Balance:", self.balance - str4)
str3=input("Would you like to check the balance of the account, deposit money into the account, or withdraw money from the account? ")
if str3=="check the balance":
self.check_balance()
elif str3=="deposit money":
self.deposit()
elif str3=="withdraw money":
self.withdraw()
else:
print("Unable to process.")
Fred=Account("Fred",20,30)
John=Account("John",30,40)
Michelle=Account("Michelle",40,50)
Ann=Account("Ann",50,60)
You have some design problems here.
Don't store the accounts in 4 separate variables. Store them in a list so you can look them up by account number (or by name, if you want to add that). That will make it easier to save the accounts to file and read them back, which you will need to do.
The Account is just a place to store information. Don't have it do any I/O. Don't have it interact with the user.
You need to ask the user which account to work with.
You should loop until they're done.
Here, I'm asking for an account number every time. To make this smarter, you would ask for an account one, and keep allowing options on that account, with another menu item to switch to a different account.
You COULD store the accounts in a dictionary with the account number as the key. That would be more sensible than a simple list.
class Account:
def __init__(self, name, account_number, balance):
self.name=name
self.account_number=account_number
self.balance=balance
def deposit(self, amt):
self.balance += amt
return self.balance
def withdraw(self,amt):
if self.balance < amt:
return self.balance - amt
self.balance -= amt
return self.balance
accounts = [
Account("Fred",20,30),
Account("John",30,40),
Account("Michelle",40,50),
Account("Ann",50,60)
]
print("Welcome to the bank.")
while True:
acct = int(input("Which account number are you working with today? "))
acct = [a for a in accounts if a.account_number == acct]
if not acct:
print("That account doesn't exist.")
continue
acct = acct[0]
print("\nBalance: ", acct.balance)
print("Would you like to:")
print(" 1. Check the balance")
print(" 2. Deposit money")
print(" 3. Withdraw money")
print(" 4. Quit")
str3 = input("Pick in option: ")
if str3=="1":
print("Balance: ", acct.balance)
elif str3=="2":
amt=int(input("How much would you like to deposit? "))
acct.deposit( amt )
elif str3=="3":
amt=int(input("How much would you like to withdraw? "))
if acct.withdraw( amt ) < 0:
print("Unable to process. Doing this will result in a negative balance.")
elif str3=="4":
break
else:
print("Unrecognized.")
I want to create small bank system in which user enters bank then options would be given to open a new account or use an existing account. Accordingly, functions will be called.
I am using PyCharm IDE ensured whitespace is correct.
My error message, showing that I can't access account_number:
AttributeError: 'Account' object has no attribute 'account_number'
import random as r
class Account():
print("Welcome to AV Bank")
def __init__(self,choice):
self.choice = choice
def open_account(self):
self.new_account_holder_name = str(input("Enter new account holder name: "))
self.account_number = r.randrange(999999)
print(f"Mr.{self.new_account_holder_name} your account has been successfully opened and account number is {self.account_number}, With balance 0. Please deposit minimum R.1000/-")
def existing_holder(self):
self.account_holder_name = str(input("Enter account holder name: "))
print(f"Welcome Mr.{self.account_holder_name}. Following are the choices. Please select : \nPress 1 deposit money \nPress 2 for withdraw money")
def deposit(self,amount_added):
self.balance = 0
self.amount_added = amount_added
self.balance = self.balance + self.amount_added
print(f"Added Rs. {self.amount_added} in account number {self.account_number}")
def withdraw(self,subtract):
self.balance = 0
self.subtract = subtract
if (self.balance<self.subtract):
print("In sufficient balance in account")
else:
self.balance = self.balance - self.subtract
print("Withrawal accepted")
return self.balance
def __str__(self):
return (f"Account Owner: {self.owner} \nAccount Balance: {self.balance}")
customer_visit = int(input("Press 1: To Open New Bank Account or Press 2: To Use Existing Account : "))
acct1 = Account(customer_visit)
if customer_visit ==1:
acct1.open_account()
amount_added = int(input("Enter the deposit amount: "))
acct1.deposit(amount_added)
if customer_visit ==2:
acct1.existing_holder()
holder_option = int(input())
if holder_option ==1:
amount_added = int(input("Enter the deposit amount: "))
acct1.deposit(amount_added)
if holder_option ==2:
withdraw_money = int(input("Enter amount you want to withdraw: "))
acct1.withdraw(withdraw_money)
It is because account_number is not being set as a class attribute. So after the open_account() method is called, it is immediately forgotten. You need to set account_number as an attribute if you would like to call it later on.
def open_account(self):
self.new_account_holder_name = str(input("Enter new account holder name: "))
self.account_number = r.randrange(999999)
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm trying to make a code for my python class and i'm making a wallet management system basic. but i cant get this infinite loop to work. What am i doing wrong?
def main():
# Initial balance
balance = input ('Wallet balance: ')
# This constructs the infinite loop
while true:
# Initial balance
balance = input ('Wallet balance: ')
# Withdraw amount from wallet balance
withdraw= input ('Withdraw amount: ')
#If there is no balance to withdraw from
if balance < 1:
print ('You have no funds to withdraw.')
# Withdraw process and new balance display
if balance > 0:
new = balance - withdraw
print ('Your new balance: '), new
main()
Fixed it for you, it had a few errors
True must be capitalized in Python
If you are passing an int into a str you need to cast the int as a str
Also, I'm not sure why what you're using the main function for? It doesn't pass the initial value into the infinite loop and seems redundant.
def main():
# Initial balance
balance = input ('Wallet balance: ')
# This constructs the infinite loop
while True:
# Initial balance
balance = input('Wallet balance: ')
# Withdraw amount from wallet balance
withdraw= input('Withdraw amount: ')
#If there is no balance to withdraw from
if balance < 1:
print('You have no funds to withdraw.')
# Withdraw process and new balance display
if balance > 0:
new = balance - withdraw
print('Your new balance: ' + str(new))
main()
However, I'm assuming you're trying to build a functional wallet that can withdraw and deposit. I'm not sure how comfortable you are with python and class construction, but I built a fully functional wallet for you to check out and learn from.
class Wallet:
#Grab the initial balance in the account
def __init__(self, initial_balance):
self.balance = initial_balance
#method that deposits funds to the balance
def deposit(self, deposit_amount):
self.balance += deposit_amount
#method that attempts to withdraw from the balance
def withdraw(self, withdraw_amount):
if withdraw_amount <= self.balance:
self.balance -= withdraw_amount
else:
print("Insufficient funds. You have " + str(self.balance) + " in your account. Please deposit more or withdraw less.")
#display the balance
def display_balance(self):
print("The current balance in the account is " + str(self.balance))
print("-----")
#Check if this module is the one currently being run
if __name__ == "__main__":
#Ask user for initial balance
initial_balance = int(input("Initial balance in account: "))
#initiate the class, passing the initial balance
wallet = Wallet(initial_balance)
wallet.display_balance()
while True:
#Pick an option to withdraw, deposit or exit
print("1: Deposit funds")
print("2: Withdraw funds")
print("3: Exit")
type = int(input("Please select an option (1, 2 or 3): "))
if type == 1:
deposit_amount = int(input("Please specify amount to deposit: "))
wallet.deposit(deposit_amount)
wallet.display_balance()
elif type == 2:
withdraw_amount = int(input("Please specify amount to withdraw: "))
wallet.withdraw(withdraw_amount)
wallet.display_balance()
elif type == 3:
break
else:
print("Invalid selection, please type either 1, 2 or 3")
I don't have python3, but this worked in python2 and I added the parentheses around the print-statement after.
def main():
# Initial balance
balance = int(input('Wallet balance: '))
# This constructs the infinite loop
while True:
# Withdraw amount from wallet balance
withdraw = int(input('Withdraw amount: '))
#If there is no balance to withdraw from
if balance < 1:
print ('You have no funds to withdraw.')
# Withdraw process and new balance display
if balance > 0:
new = balance - withdraw
print ('Your new balance: ', new)
main()