I am working on this homework assignment and I am stuck on what I know to be a very simple problem. The premise of the code is a petty cash system in which the user can make deposits, withdraws, and get their current balance.
My problem is that the withdraws and deposits don't seem to be going through my Account class. Is it a global variable issue? I'll be adding timestamps later. Thank you in advance.
import datetime
import time
class Account:
def __init__(self, initial):
self.balance = initial
def deposit(self, amt):
self.balance = self.balance + amt
def withdraw(self,amt):
self.balance = self.balance - amt
def getbalance(self):
return self.balance
def yesno(prompt):
ans = raw_input(prompt)
return (ans[0]=='y' or ans[0]=='Y')
def run():
done = 0
while not done:
user_options()
print
done = not yesno("Do another? ")
print
def user_options():
print ("Here are your options:")
print
print (" (a) Deposit cash")
print (" (b) Withdraw cash")
print (" (c) Print Balance")
print
u = raw_input("Please select a letter option: ").lower()
user_input(u)
def user_input(choice):
account = Account(0.00)
if choice == "a" or choice == "b" or choice == "c":
if choice == "a":
d = input("Enter Deposit Amount: $")
account.deposit(d)
if choice == "b":
w = input ("Enter Withdraw Amount: $")
account.withdraw(w)
if choice == "c":
print ("Balance Amount: $"),
print account.getbalance()
else:
print ("Not a correct option")
run()
#now = datetime.datetime.now()
Python Version: 2.7.2
The problem is:
account = Account(0.00)
Every time user_input is called, you create a new, empty account. Since user_input is called from user_options which is called inside the while loop in run, this happens before every transaction.
You need to move that line out of the loop, for example:
def run():
done = 0
global account # just showing you one way, not recommending this
account = Account(0.00)
while not done:
user_options()
print
done = not yesno("Do another? ")
print
You don't need global variables, just restructure the code slightly like this
def run():
account = Account(0.00)
done = 0
while not done:
user_option = user_options()
user_input(user_option, account)
print
done = not yesno("Do another? ")
print
def user_options():
print ("Here are your options:")
print
print (" (a) Deposit cash")
print (" (b) Withdraw cash")
print (" (c) Print Balance")
print
return raw_input("Please select a letter option: ").lower()
def user_input(choice, account):
if choice == "a" or choice == "b" or choice == "c":
if choice == "a":
d = input("Enter Deposit Amount: $")
account.deposit(d)
if choice == "b":
w = input ("Enter Withdraw Amount: $")
account.withdraw(w)
if choice == "c":
print ("Balance Amount: $"),
print account.getbalance()
else:
print ("Not a correct option")
run()
You can still do more to make the code nicer, this is just enough to get the account part working
Related
if you choose to return a book at the start of the program, without checking out any books,
then it won't allow the return (intended). So say the user wants to check out 5/10 copies of
book1. It checks them out and subtracts them from the copies on shelf. They choose to return
3 one day, and 2 another day. (For testing purposes) the day after that, they return another
copy of book1, which is more than they checked out. It appends it to the book1.borrow aka
num of copies. It should not allow the user to return more copies than the original numbr of copies. So this is what I have in my main module. I can add the class LibraryBook if
needed.
from LibraryBook import *
book1 = LibraryBook()
book1.title = "not set"
book1.year = "no se"
book1.author = "set not"
book1.borrow = 10
book2 = LibraryBook()
book2.title = "tes ton"
book2.year = "es on"
book2.author = "ton tes"
book2.borrow = 8
selection = 0
amount = 0
amount1 = 0
while selection != 5:
print("Select an option")
print('1 - Borrow a book')
print('2 - Return a book')
print('3 - See info on available books')
print('4 - Exit')
print()
selection = int(input("What would you like to do? "))
print()
if selection == 1:
print("Book 1 is: ", book1.title)
print("Book 2 is: ", book2.title)
print()
bookNum = int(input("Enter the book number. "))
print()
if bookNum == 1:
print()
amount = int(input("Enter the number of copies you would like to check out. "))
print()
if (amount <= book1.borrow) and (amount > 0):
book1.borrowed(amount)
else:
print("We only have", book1.borrow, "copies available.")
print()
elif bookNum == 2:
print()
amount = int(input("Enter the number of copies you would like to check out. "))
print()
if (amount <= book2.borrow) and (amount > 0):
book2.borrowed(amount)
else:
print("We only have", book2.borrow, "copies available.")
print()
else:
print()
print("That book is not here. Enter 1 or 2. ")
print()
if selection == 2:
print("Book 1 is: ", book1.title)
print("Book 2 is: ", book2.title)
print()
bookNum = int(input("Which book would you like to return? "))
print()
if bookNum == 1:
print()
amount1 = int(input("Enter the amount of copies you would like to return. "))
print()
if amount1 <= amount:
book1.returned(amount1)
print()
elif book1.borrow == book1.borrow:
print("Invalid number of copies. Count the books and try again ")
print()
else:
print("You only checked out", amount)
print()
elif bookNum == 2:
print()
amount1 = int(input("Enter the amount of copies you would like to return. "))
print()
if amount1 <= amount:
book2.returned(amount1)
print()
elif book2.borrow == book2.borrow:
print("You did not check out this book.")
print()
else:
print("You only checked out", amount)
print()
else:
print("Invalid selection. Choose book 1 or book 2.")
print()
if selection == 3:
print()
print("Book 1:")
print(book1.__str__())
print()
print("Book 2:")
print(book2.__str__())
print()
if (selection <= 0) or (selection >= 5):
print("Invalid selection. Enter a number 1-4. ")
print()
if selection == 4:
break
I'm not the best programmer but I think I made and example here
Ofc is not the best I made it larger for you to understand, there are some bugs like when asked for book if u give bigger then 2 will break but I let you fix it ;D
import sys, os, time, re
class LibraryBook(object):
def __init__(self, title, year, author, borrow):
self.title = title
self.year = year
self.author = author
self.borrow = borrow
def borrow_add(self, amount: int):
self.borrow += amount
def left(self):
return self.borrow
def get_title(self):
return self.title
def borrow_sell(self, amount: int):
self.borrow -= amount
def get_book_info(self):
val = f'''
Book Title: {self.title}
Book Year: {self.year}
Book Author: {self.author}
Left in stock: {self.borrow}
'''
return val
book1 = LibraryBook('Prison Break', 2016, 'My House', 8)
book2 = LibraryBook('Hello', 1999, 'NO one', 10)
###########
#That is so you can do book3,4,5 etc.. without write in print all books on hand ;D
books = re.findall('book.', (str(globals().copy())).replace("'", ''))
books_titles = [eval(f'{o}.get_title()') for o in books]
##########
user_lib =[]
#You can use that in a function (def) and call it when you need it
while True:
os.system('cls')
option = int(input('''
Select an option
1 - Borrow a book
2 - Return a book
3 - See info on available books
4 - See my lib
5 - Exit
>>> '''))
if option == 1:
option_2 = input("\n".join(f"Book{o+1}:{i}" for o, i in enumerate(books_titles))+'\nWhat book(ex: 1):')
option_3 = int(input('How much?: '))
if int(eval(f'book{option_2}.left()'))-option_3 >= 0:
if x:=list(filter(lambda book: book['name'] == eval(f'book{option_2}.title'), user_lib)):
user_lib[user_lib.index(x[0])]['amount'] +=option_3
else:
user_lib.append({'name': eval(f'book{option_2}.get_title()'), 'amount': option_3})
print(f'You borrowed {option_3} books')
eval(f'book{option_2}.borrow_sell({option_3})') #Remove from store
else:
print(f'We have {eval(f"book{option_2}.left()")} books left...')
time.sleep(1) # wait 1 second for user to read then reset
elif option == 2:
option_2 = input("\n".join(f"Book{o+1}:{i}" for o, i in enumerate(books_titles))+'\nWhat book(ex: 1):')
if len(x:=list(filter(lambda book: book['name'] == eval(f'book{option_2}.get_title()'), user_lib))) > 0:
option_3 = int(input('How much?: '))
if user_lib[pos:=user_lib.index(x[0])]['amount'] -option_3 >= 0:
user_lib[pos]['amount'] -= option_3
if user_lib[pos]['amount'] == 0:
user_lib.pop(pos)
print(f'You returned {option_3} books')
eval(f'book{option_2}.borrow_add({option_3})') # Add them back to shop
else:
print(f"You don't have enogh books, you have only: {x[0]['amount']}")
time.sleep(1) # wait 1 second for user to read then reset
else:
print("You don't any books of thta kind")
time.sleep(1)
elif option == 3:
option_2 = input("\n".join(f"Book{o+1}:{i}" for o, i in enumerate(books_titles))+'\nWhat book(ex: 1):')
print(eval(f'book{option_2}.get_book_info()'))
input('Press enter to continue...')
elif option == 4:
print("\n".join(f"Book Name:{user_lib[o]['name']}\nAmount I have:{user_lib[o]['amount']}" for o, i in enumerate(user_lib)) if user_lib != [] else "You don't have any books")
elif option == 5:
sys.exit(1)
else:
print('Invalid number')
time.sleep(1) # wait 1 second for user to read then reset
I'm working on code to make a bank account. I can't figure out how to make it so that if the user inputs the right passcode the options appear and if the user inputs the wrong passcode the options do not appear. Currently, the options appear no matter what the user input is.
class Account: #Class1
def __init__(self, name, account_number, password, balance): #__init__ function
self.name=name #attribute of object
self.account_number=account_number #attribute of object
self.password=password
self.balance=balance #attribute of object
def password_check(self, password):
if str6 == password:
return True
else:
return False
def deposit(self, amount): #function to deposit money
self.balance += amount #deposits money
return self.balance
def withdraw(self,amount): #function to withdraw money
if self.balance < amount: #only executes if balance is less than amount being withdrawn
return self.balance - amount
self.balance -= amount #withdraws money
return self.balance
def __repr__(self):
return str(self.name)
accounts = [Account("Fred",2528318,"Fred123",300.00),Account("John",3076427,"John456",430.00),Account("Michelle",4829302,"Michelle135",570.00),Account("Ann",2918531,"Ann789",600.00)] #objects
print("Welcome to the bank.")
while True: #loops
def create_account():
str2=input("What is the name of the account? ")
str3=int(input("What would you like your account number to be?"))
str4=input("What will your password be? ")
str5=float(input("How much money will you deposit into the account for the initial balance? "))
gg=Account(str2,str3,str4,str5)
accounts.append(gg)
return("Okay.")
print("Would you like to:")
print("1. Create an account")
print("2. Access an account.")
str1=input("Pick an option. ")
if str1=="1":
print (create_account())
if str1=="2":
print("Accounts: ",accounts)
acct = (input("Which account are you working with today? ")) #choice of which account to access
acct=[a for a in accounts if a.name==acct]
if not acct: #executes if acct is not in accounts
print("Unable to process. That account doesn't exist.") #error message
continue #continues the loop
acct = acct[0]
str6=input("What is the password of the account? ")
acct.password_check(str6)
print("Account Number: ", acct.account_number)#prints the account number
print("Would you like to:")
print("1. Check the balance")
print("2. Deposit money")
print("3. Withdraw money")
print("4. Quit")
choice_of_what_to_do = input("Pick an option: ") #choice of what to do
if choice_of_what_to_do=="1": #only executes if choice_of_what_to_do is 1
print("Current Balance of the Account: ", acct.balance) #prints the balance
elif choice_of_what_to_do=="2": #only executes if choice_of_what_to_do is 2
amount=float(input("How much would you like to deposit? ")) #the amount that will be deposited
acct.deposit(amount) #deposits the money
print("Current Balance of the Account: ", acct.balance) #prints the balance
elif choice_of_what_to_do=="3": #only executes if choice_of_what_to_do is 3
amount=float(input("How much would you like to withdraw? ")) #the amount that will be withdrawn
if acct.withdraw(amount) < 0: #only executes if the balance of the account after withdrawing the money is less than 0
print("Unable to process. Doing this will result in a negative balance.")
print("Current Balance of the Account: ", acct.balance) #prints the balance
elif choice_of_what_to_do=="4": #only executes if choice_of_what_to_do is 4
print("Okay.")
break #ends the loop
else: #executes if choice_of_what_to_do is not 1, 2, 3, or 4
print("Unable to process.") #error message
choice_to_repeat=input("Would you like to see another (or the same) account (yes or no)? ") #choice to repeat the loop or not
if choice_to_repeat=="yes": #only executes if choice_to_repeat is yes
print("Okay.")
continue #continues the loop
elif choice_to_repeat=="no": #only executes if choice_to_repeat is no
print("Okay.")
break #ends the loop
else: #executes if choice_to_repeat is not yes or no
print("Unable to process.") #error message
Does anyone know how to solve this?
You need to add condition here:
acct.password_check(str6)
Because the above code only return false when invalid passcode inputted.
For example:
if acct.password_check(str6):
print("access successful")
else:
break
Also, the function password_check need to modify as follow, you need to pass the password from the input and validate against the password created in the account object creation:
def password_check(self, input_password):
if input_password == self.password:
return True
else:
return False
I'm trying to make a simple library where the user can add and remove books from his shopping cart, but I don't know how to use if statements with OOP and classes.
try:
class library:
def __init__(self, books, customer):
self.books = books
self.customer = customer
# sign:
check = input("manager account(1), customer account(2): ")
if check == "2":
#age >= 18
age = int(input("enter your age: "))
if age >= 18:
#name
name = input("enter your firstname: ")
# ID
import random
x = "ID"+str(random.randint(101,999))
print(f"your ID is: {x}")
print("you should memorize it")
y = input("enter password that has at list 8 caracterse: ")
# Password
while len(y) < 8:
y = input("enter password that has at list 8 caracterse: ")
print(f"your password is: {y}")
print("you should memorize it")
data = [x,y]
choice_1 = input("check your shopping cart(1): \nadd books to your shopping cart(2): \nremove books from your shopping cart(3): ")
if choice_1 == "1":
def __str__(self):
return f"customer {self.customer} bought those books{self.books}"
elif choice_1 == "2":
def __iadd__(self, other):
self.books.append(other)
return self
order = library(["the golsen company"],"Mr.asad")
print(order.books)
order += input("enter a book: ")
print(order.books)
except ValueError as ages:
print(ages)
I don't know if this is the right way to use the if statement with classes so if you can just give me an example to show how it's done correctly?
OK, I have rewritten your code to implement it in a more organized way. Your class "library" was not really a library at all; it is a class for "orders", and I have renamed it as such. I didn't know what you wanted for the manager account, so the manager account just assigns a fake user name without requiring a signup. I also fixed the spelling errors and the tabbing.
import random
import sys
class Order:
def __init__(self, books, customer):
self.books = books
self.customer = customer
def __iadd__(self, other):
self.books.append(other)
return self
def __isub__(self, other):
self.books.remove(other)
return self
def __str__(self):
return f"custumer {self.customer} bought those books {self.books}"
# sign in.
check = input("manager account(1),custumer account(2): ")
if check == '1':
x = 'manager'
if check == "2":
#age >= 18
age = int(input("enter your age: "))
if age < 18:
print("Sorry, you must be at least 18.")
sys.exit(0)
#name
name = input("enter your firstname: ")
# ID
x = "ID"+str(random.randint(101,999))
print(f"your ID is: {x}")
print("you should memorize it")
# Password
y = input("enter password that has at least 8 characters: ")
while len(y) < 8:
y = input("enter password that has at least 8 characters: ")
print(f"your password is: {y}")
print("you should memorize it")
# Main menu.
order = Order( [], x )
while True:
print('---')
choice_1 = input("1. check your shopping cart\n2. add books to your shopping cart\n3. remove books from your shopping cart\n4. quit: ")
if choice_1 == "1":
print( order )
elif choice_1 == "2":
order += input("enter a book: ")
elif choice_1 == "3":
book = input("enter a book: ")
if book in order.books:
order -= book
else:
print( f"{book} is not in your cart." )
elif choice_1 == "4":
break
when you said "fonction", I think you mean "function". When you make a try: block, you must also add an except: block. Also, don't put code directly in the class. Put it inside a function (a.k.a methods). I put the code starting from # sign in the __int__ method. We generally don't put methods (functions) inside other methods. So, put the __str__ and __iadd__ methods outside the __init__ method. To call it, use self.__str__() and self.__iadd__().
Here is the updated code:
try:
class library:
def __init__(self, books, customer):
self.books = books
self.customer = customer
# sign:
check = input("manager account(1), customer account(2): ")
if check == "2":
# age >= 18
age = int(input("enter your age: "))
if age >= 18:
# name
name = input("enter your firstname: ")
# ID
import random
x = "ID" + str(random.randint(101, 999))
print(f"your ID is: {x}")
print("you should memorize it")
y = input("enter password that has at list 8 caracterse: ")
# Password
while len(y) < 8:
y = input("enter password that has at list 8 caracterse: ")
print(f"your password is: {y}")
print("you should memorize it")
data = [x, y]
choice_1 = input("check your shopping cart(1): \nadd books to your shopping cart(2): ")
if choice_1 == "1":
self.__str__()
elif choice_1 == "2":
self.__iadd__()
# age < 18
elif age < 18:
print("this library is not for your age")
def __iadd__(self, other):
self.books.append(other)
return self
def __str__(self):
return f"customer {self.customer} bought those books{self.books}"
except:
pass
order = library(["the golsen company"], "Mr.asad")
print(order.books)
order += input("enter a book: ")
print(order.books)
The deposit function and the withdraw function doesn't work. After populating the accounts, I can select D or W menu options and input any number without causing the program to crash or causing an error. The program seems it is working correctly but when you check the balances using the S option, they are not updated.
Names=[]
accountnumbers=[]
balance=[]
def populatelist():
position=0
while(position<=2):
yourname= str(input("Please enter a name: "))
Names.append(yourname)
account = int( input("Please enter an account number: " ))
accountnumbers.append(account)
totalbalance = int( input("Please enter a balance: "))
balance.append(totalbalance)
position = position + 1
##################################### DEPOSIT FUCNTION
def deposit(accountnumber):
foundposition=-1
position=0
if (len(accountnumbers)>0):
while (position <=2):
if (accountnumber==accountnumbers[position]):
return position
position = position + 1
return foundposition
#################################### WITHDRAW FUNCTION
def withdraw(accountnumber):
foundposition=-1
position=0
if (len(accountnumbers)>0):
while (position <=2):
if (accountnumber==accountnumbers[position]):
return position
position = position + 1
return foundposition
def findingaccount(accountnumber):
foundposition=-1
position=0
if (len(accountnumbers)>0):
while (position <=2):
if (accountnumber==accountnumbers[position]):
return position
position = position + 1
return foundposition
def menuoptions():
print ("**** MENU OPTIONS ****")
print ("Type P to populate accounts")
print ( "Type S to search for account")
print ("Type E to exit")
print ("Type D to deposit Amount")
print ("Type W to withdraw Amount")
choice = str(input("Please enter your choice: "))
return choice
response=""
while response!= "E":
response = menuoptions()
if response=="P":
populatelist()
########################### Deposit OPTION
elif response=="D":
searchaccount = int(input("Please enter the account number to add deposit: "))
foundtheposition = deposit(searchaccount)
money = int(input("Please enter the amount to be deposited: "))
money + (balance[foundtheposition])
########################### WITHDRAW OPTION
elif response=="W":
searchaccount = int(input("Please enter the account number to withdraw: "))
thenumber = withdraw(searchaccount)
withdraw = int(input("how much for withdraw"))
withdraw - (balance[thenumber])
if (balance[thenumber]) < withdraw :
print("ERROR: Not enough balance")
elif response=="S":
searchaccount = int(input("Please enter the account number to search: "))
foundaposition = findingaccount(searchaccount)
if ( foundaposition == -1 ):
print ("The account number not found!")
else:
print ("Name is:" + str( Names[foundaposition]))
print (str(Names[foundaposition]) + " " + "account has the balance of :" +str(balance[foundaposition]))
elif response=="E":
print ("Thank you for using the program.")
print ("Bye")
exit
else:
print ("Invalid choice. Please try again!")
You have logic error.
Just change
money + (balance[foundtheposition])
to
balance[foundtheposition] = balance[foundtheposition] + money
or using short-hand operator like
balance[foundtheposition] += money
Same for
withdraw - (balance[thenumber])
Cheers ...
Your deposit scenario needs to add the amount into the selected account:
balance[thenumber] += money
Fair warning there are other errors in your program besides the accounts not updating.
I'm writing this program that lets users choose an option to display, change,add, remove, write or quit
I keep getting invalid syntax error on this elif statement in my program and i dont know why?
DISPLAY = 'D'
CHANGE = 'C'
ADD = 'A'
REMOVE = 'R'
WRITE = 'W'
QUIT = 'Q'
#main function
def main ():
print()
print()
print('\t Wombat Valley Tennis Club')
print('\t Member Register')
print('\t =======================')
main_dic = {}
with open ('wvtc_data.txt','r')as x:
for line in x:
line = line.rstrip ('\n')
items = line.split (':')
key,value = items[0], items[1:]
main_dic[key] = values
choice = input('choice: ')
while choice != QUIT:
choice = get_menu_choice()
if choice==DISPLAY:
display(main_dic)
elif choice==CHANGE:
change(main_dic)
elif choice== REMOVE:
remove (main_dic)
elif choice==WRITE:
write(main_dic)
def get_menu_choice():
print()
print("\t\t Main Menu")
print()
print('\t<D>isplay member details')
print('\t<C>hange member details')
print('\t<A>dd a new member')
print('\t<R>emove a member')
print('\t<W>rite updated details to file')
print('\t<Q>uit')
print()
print('Your choice (D, C, A, R, W OR Q)?\t[Note: Only Uppercase]')
print()
choice = input("Enter your choice: ")
while choice < DISPLAY and choice < CHANGE or choice > QUIT:
choice = input ('Enter your choice: ')
return choice
def display(main_dic):
name = input('Type the name of the member:')
print()
print (main_dic.get(name, 'not found!'))
print()
print()
def change(main_dic):
name=input("Enter the member number")
print()
print(main_dic.get(name,'not found!'))
print()
NAME = 1
EMAIL = 2
PHONE = 3
print('Please select')
print('==============')
print('Change Name<1>')
print('Change E-mail<2>')
print('Change Phone Number<3>')
print()
if choose == NAME:
new_name = input('Enter the name: ')
print()
print("Data has been changed")
main_dic[name][0]=new_name
print (mem_info[name])
print()
elif choose == EMAIL:
new_email=input('Enter the new email address:')
print ('Email address has been changed')
#change the data
main_dic[name][1]=new_email
print(mem_info[name])
print()
elif choose == PHONE:
new_phone = int (input('Enter the new phone number'))
print ("phone number has been changed")
main_dic[name][2]=new_phone
print(main_dic[name])
print
def write(main_dic):
print()
name = input ("Enter the name of a member:")
print()
print (mem_info.get(name,'Not found!'))
print()
main()
main()
Also any help or suggestions in making this code work are appreciated.
It's a formatting problem. The elifs have to start in the same column as the if to which they belong.
Example
if something:
do_somtething()
elif something_else:
do_the_other_thing()