I'm learning Python and went with a simple ATM code. I've tested it and everything works DownStream - what I mean by this is:
I have a few options when the class is initialized - Balance, Deposit, Withdraw, Exit.
When I run Balance I receive the amount set.
2.1. I go with Deposit - it shows the new amount the person has in their account
2.2. When I use Withdraw I get correct amount as well
Question - When I Deposit and then type Balance I'm getting the initial Balance of the user - that is expected. How can I change the code so after Depositing Money and select Balance to show me the new Balance?
Is this possible to be performed without much complicating the code?
The code:
class User:
def __init__(self):
self.fname = input('Enter your first name: ')
self.lname = input('Enter your last name: ')
self.age = input('Enter your age: ')
def user_details(self):
print('Details:')
print(f"First Name: {self.fname}")
print(f"Last Name: {self.lname}")
print(f"User age: {self.age}")
def deposit_money(self):
self.deposit_amount = 100
return self.deposit_amount
def withdraw_money(self, withdraw_amount):
self.withdraw_amount = withdraw_amount
return self.withdraw_amount
class ATM:
atm_balance = 10000
def __init__(self):
self.machine_balance = self.atm_balance
def user_bank_balance(self):
self.user_balance = 300
print ('Your current balance is ${}'.format(self.user_balance))
def deposit_atm(self, user):
self.total_savings = 0
deposit_m = float(input('How much do you want to deposit? '))
if deposit_m > user.deposit_money():
print('You do not have enough money to deposit')
elif deposit_m == user.deposit_money():
print('Amount deposited: ${}'.format(deposit_m))
self.total_savings = self.user_balance + deposit_m
print('Total amount in your account: ${}'.format(self.total_savings))
def withdraw_atm(self):
savings_left = 0
sum_to_withdraw = float(input('How much do you want to withdraw? '))
if self.atm_balance > sum_to_withdraw and self.user_balance > sum_to_withdraw:
savings_left = self.total_savings - sum_to_withdraw
print("You have withdraw {}".format(sum_to_withdraw))
print('You balance is {}'.format(savings_left))
elif self.atm_balance > sum_to_withdraw and self.user_balance < sum_to_withdraw:
print('Daily limit eceeded')
else:
print('ATM out of service')
class ATMUsage:
#classmethod
def run(cls):
print('Bulbank ATM')
instructions = print("""
Type 'Balance' to check your current balance,
Type 'Deposit' to deposit amount into your account,
Type 'Withdraw' to withdraw from your account,
Type 'Exit' to exit from your account,
""")
active = True
user1 = User()
atm1 = ATM()
user1.user_details()
while active:
selection = input("What would you like to do: 'Balance', 'Deposit', 'Withdraw', 'Exit': ")
if selection == 'Balance'.lower():
atm1.user_bank_balance()
elif selection == 'Deposit'.lower():
atm1.deposit_atm(user1)
elif selection == "Withdraw".lower():
atm1.withdraw_atm()
elif selection == 'Exit'.lower():
print('Thanks for passing by. Have a good one!')
break
else:
print('Wrong selection. Please, try again')
ATMUsage.run()
That's because every time you call the user_bank_balance method, you set the user_balance attribute to 300. So it wouldn't matter what updates you did on the user_balance, whenever you call the user_bank_balance method, you'll get 300
class ATM:
atm_balance = 10000
def __init__(self):
self.machine_balance = self.atm_balance
self.user_balance = 300
def user_bank_balance(self):
print ('Your current balance is ${}'.format(self.user_balance))
Related
I cannot get Pytest to test anything involving this code. It always says no tests ran when I use the code below. I'm trying to just get it to test and from there I can tinker with the rest, I'm just a bit stuck on this and can't figure it out. The code runs well, exactly as intended it's just when I try to pytest with it that I'm reciving a problem.
import datetime
tday = datetime.date.today()
balance = 1000.0
amount = float
transaction_list = []
class Account(amount):
def get_balance(self):
print("\n This is your account balance: " + str(balance))
def deposit(self, amount):
global balance
amount = float(input("\n How much would you like to deposit? "))
if amount > 10000:
print("\n Do you want to swim in the vualt? ")
transaction_list.append("You deposited " + str(amount))
balance = balance + amount
print("\n You're balance is now " + str(balance))
def withdrawl(self, amount):
global balance
amount = float(input("\n How much do you wanna take out? "))
while amount > balance:
amount = float(input("\n You don't have enough funds. Enter a new value "))
transaction_list.append("\n You withdrew " + str(amount))
balance = balance - amount
print("\n You're balance is now " + str(balance))
class Transaction(amount):
def transaction(self):
print("\n")
print(" " + str(card_number) + " " + str(tday))
print("\n Recipt: HM21-1926\n")
print("\n Account: Chequing. Primary\n")
print("\n Here is your transaction history!\n")
for i in transaction_list:
print(i)
print("\n Account Balance: " + str(balance))
print("\n Limited time offer: get a personal loan starting at Prime + 1.99%*")
print("\n Offer valid until September 2, 2022.")
print("\n Conditions apply & approval required. Ask us for details.\n")
account = Account()
transaction = Transaction()
if __name__ == "__main__":
mike_lane = Account()
print(repr(mike_lane))
print(str(mike_lane))
The code below is the code I'm trying to use pytest on. I don't know if there is something wrong with what I'm trying to test or if there is something wrong with the main code. I'm just starting out with programming and this is a bit complicated for me still (However, I have to learn to do this for the class so I'm not able to come back to learn TDD later on)
import bank_program
def test_deposit():
account = Account(100)
assert balance.amount == 1100
def test_depos():
with pytest.raises(ValueError):
assert amount = Account("ABC")
def test_transactions():
account = Account(100)
assert tday() >= now
class client:
def __init__(self):
self.name = str(input("Name: "))
self.surname = str(input("Surname: "))
self.year = str(input("Year of birth: "))
self.id =(self.name[0] + self.surname[0] + self.year)
self.balance = 0
def Transfer(self):
balance = self.balance
action = int(input("How much would you like to transfer ?"))
if action > balance:
print("Not enough money")
else:
id = str(input("choose user you want to send money to:"))
self.balance = balance - action
#call id of crated client here to choose him as reciever of transfer
print(f"Succesfully transfered {action}$, your balance right now is {self.balance}$ have a nice day !!")
def Balance(self):
print(f"Your account balance is: {self.balance}")
Task : Send money between users
Problem : i have no idea how to call specific ID of class object that will be created
# 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 = 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)
print("Net Available Balance=",self.balance)
# 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)
print("Net Available Balance=",self.balance)
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)
# Add to Users/Bank
cursor.execute("INSERT INTO bank VALUES (7620, 'Kailas Kurup')")
cursor.execute("INSERT INTO bank VALUES (4638, 'Bethany Watkins')")
cursor.execute("INSERT INTO bank VALUES (3482, 'John Hammond')")
cursor.execute("INSERT INTO bank VALUES (3493, 'Melissa Rodriguez')")
cursor.execute("INSERT INTO bank VALUES (9891, 'Gopalakrishnan Nair')")
# Get Results
cursor.execute("SELECT * FROM bank")
results = cursor.fetchall()
print(results)
This is my code so far. I have not completed the database portion of this project yet. 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 am totally lost on what to do with this code. But im getting an error on the line
account.append(BankAccount(lst[0],lst[1],float(lst[2]),float(lst[3].replace('\n',''))))
can anyone help me with how to correct this?
Thank you!
FULL CODE:
class BankAccount: #BankAccount class implementation
def __init__(self, ID,PIN,checking,savings):
self.ID = ID
self.PIN = PIN
self.checking = checking
self.savings = savings
def getID(self):
return self.ID
def getPIN(self):
return self.PIN
def getSavings(self):
return self.savings
def getChecking(self):
return self.checking
def withdraw(self,amount,type): #withdraw method returns False if
if(type==1):
#amount is greater than savings balance
if(self.savings<amount):
return False
else: #else deducts amount from savings balance and returns True
self.savings -= amount
elif(type==2):
#amount is greater than savings balance
if(self.checking<amount):
return False
else:
self.checking -= amount
return True
def deposit(self,amount,type):
if(type==1):
self.savings += amount
elif(type==2):
self.checking += amount
def main():
account = []
n=0
with open("accounts.txt") as file: #reads data from file named accounts.txt
for line in file: #reads line by line from file
li = line.split(' ') #splits the line based on ' '
#creates an object of BankAccount and appends it to account list
account.append(BankAccount(li[0],li[1],float(li[2]),float(li[3].replace('\n',''))))
n += 1 #to keep track of number of accounts read from file
userid = input("Enter ID: ")
userpin = input("Enter PIN: ")
i=0
#loops through accounts and performs respective operations
while i<n:
if(account[i].getID()==userid):
if(account[i].getPIN()==userpin):
option = int(input('Enter 1 for withdraw 2 for transfer 3 for balance: '))
if(option==1):
type = int(input('Select type 1. Savings 2.checking: '))
amount = float(input("Enter amount: "))
if(account[i].withdraw(amount,type)):
if(type==1):
print(amount,'withdrawn. Closing balance: ',account[i].getSavings())
else:
print(amount,'withdrwan. Closing balance: ',account[i].getChecking())
else:
print('insufficient funds in your account')
elif(option==2):
option = int(input('Enter 1 for within account transfer 2 for other account: '))
if(option==1): #within account transfer
fromto = int(input('Enter 1. transfer from savings to checking 2. transfer from checking to savings: '))
amount = float(input('Enter amount: '))
if(fromto==1):
account[i].withdraw(amount,1)
account[i].deposit(amount,2)
print('Transfer successful from savings to checking')
else:
account[i].withdraw(amount,2)
account[i].deposit(amount,1)
print('Transfer successful from checking to savings')
else: #other account transfer
accID = input('Enter account ID to transfer money: ')
j=0
while j<n:
if(account[j].getID()==accID):
break
j += 1
if(j<n):
type = int(input('Select type 1. Savings 2.checking: '))
amount = float(input("enter amount: "))
account[i].withdraw(amount,type)
account[j].deposit(amount,type)
print('Transfer successful to account :',account[j].getID())
if(type==1):
print(amount,'transferred. Your savings balance: ',account[i].getSavings())
else:
print(amount,'transferred. Your checking balance: ',account[i].getChecking())
else:
print('Invalid account ID. Transfer of funds terminated.')
else:
type = int(input('Select type 1. Savings 2.checking: '))
if(type==1):
print('Your savings balance:',account[i].getSavings())
else:
print('Your checking balance:',account[i].getChecking())
break
i += 1
if(i==n): #if i reaches n then it's an invalid login
print('invalid login')
else: #writes the account details into the file accounts.txt
file = open('accounts.txt','w')
j=0
while j<n:
file.write(account[j].getID()+' '+account[j].getPIN()+' '+str(account[j].getChecking())+' '+str(account[j].getSavings())+' ')
j += 1
file.close() #closes file stream
print('Thank you!!')
main()
There is most likely a line with less than 4 elements in your accounts.txt file (possibly an empty line at the end).
My goal is to have a small program which checks if a customer is approved for a bank loan. It requires the customer to earn > 30k per year and to have atleast 2 years of experience on his/her current job. The values are get via user input. I implemented regexs to validate the input to be only digits without any strigns or negatives, nor 0.
But the 3rd function asses_customer is always executing the else part. I think everytime the parameters are either None, either 0
here's the source code:
import sys
import re
import logging
import self as self
class loan_qualifier():
# This program determines whether a bank customer
# qualifies for a loan.
def __init__(self): #creates object
pass
def main():
salary_check()
work_exp_check()
asses_customer(salary = 0, years_on_job = 0)
def salary_check():
input_counter = 0 # local variable
# Get the customer's annual salary.
salary = raw_input('Enter your annual salary: ')
salary = re.match(r"(?<![-.])\b[1-9][0-9]*\b", salary)
while not salary:
salary = raw_input('Wrong value. Enter again: ')
salary = re.match(r"(?<![-.])\b[1-9][0-9]*\b", salary)
input_counter += 1
if input_counter >= 6:
print ("No more tries! No loan!")
sys.exit(0)
else:
return salary
def work_exp_check():
input_counter = 0 #local variable to this function
# Get the number of years on the current job.
years_on_job = raw_input('Enter the number of ' +
'years on your current job: ')
years_on_job = re.match(r"(?<![-.])\b[1-9][0-9]*\b", years_on_job)
while not years_on_job:
years_on_job = raw_input('Wrong work experience. Enter again: ')
years_on_job = re.match(r"(?<![-.])\b[1-9][0-9]*\b", years_on_job)
input_counter += 1
if input_counter >= 6:
print ("No more tries! No loan!")
sys.exit(0)
else:
return years_on_job
def asses_customer(salary, years_on_job):
# Determine whether the customer qualifies.
if salary >= 30000.0 or years_on_job >= 2:
print 'You qualify for the loan. '
else:
print 'You do not qualify for this loan. '
# Call main()
main()
You have stated:
It requires the customer to earn > 30k per year and to have at least 2 years of experience on his/her current job.
We can write some simple statements that request a number and if a number is not given then ask for that number again.
The following code is a very simple approach to achieving that goal.
class Loan_Checker():
def __init__(self):
self.salary = 0
self.years_on_job = 0
self.request_salary()
self.request_years()
self.check_if_qualified()
def request_salary(self):
x = raw_input('Enter your annual salary: ')
try:
self.salary = int(x)
except:
print("Please enter a valid number")
self.request_salary()
def request_years(self):
x = raw_input('Enter the number of years on your current job: ')
try:
self.years_on_job = int(x)
except:
print("Please enter a valid number")
self.request_years()
def check_if_qualified(self):
if self.salary >= 30000 and self.years_on_job >= 2:
print 'You qualify for the loan. '
else:
print 'You do not qualify for this loan. '
Loan_Checker()
You have a few errors in your code, and I've refactored it to use the class structure you seemed to want to imply.
import sys
import re
import logging
class loan_qualifier():
# This program determines whether a bank customer
# qualifies for a loan.
def __init__(self): #creates object
self.salary = self.salary_check()
self.years_on_job = self.work_exp_check()
def salary_check(self):
input_counter = 0 # local variable
# Get the customer's annual salary.
salary = None
while salary is None:
if input_counter >= 6:
print ("No more tries! No loan!")
sys.exit(0)
elif input_counter >= 1:
print ("Invalid salary.")
salary = raw_input('Enter your salary: ')
salary = re.match(r"(?<![-.])\b[1-9][0-9]*\b", salary).group(0)
input_counter += 1
# broke out of loop, so valid salary
return salary
def work_exp_check(self):
input_counter = 0 #local variable to this function
# Get the number of years on the current job.
years_on_job = None
while years_on_job is None:
if input_counter >= 6:
print ("No more tries! No loan!")
sys.exit(0)
elif input_counter >= 1:
print ("Invalid year amount")
years_on_job = raw_input('Enter the number of years at your current job: ')
years_on_job = re.match(r"(?<![-.])\b[1-9][0-9]*\b", years_on_job).group(0)
input_counter += 1
# broke out of loop, so valid years_on_job
return years_on_job
def assess_customer(self):
# Determine whether the customer qualifies.
if int(self.salary) >= 30000.0 and int(self.years_on_job) >= 2:
print 'You qualify for the loan. '
else:
print 'You do not qualify for this loan. '
if __name__ == "__main__":
lq = loan_qualifier()
lq.assess_customer()
Some of the errors fixed include the way you were calling assess_customer initially (you were assigning 0's to both values in the function call), as well as the spelling of assess :p. Your condition in assess_customer should also have been an and instead of an or (you wanted both conditions to be true for them to qualify, not for either condition to be true).
You actually don't even really need to do the:
self.salary = self.salary_check()
self.years_on_job = self.work_exp_check()
lines. You could just directly assign the class variables in the functions (i.e. instead of returning, just set self.salary = blah in salary_check). That's kind of a personal choice thing though. I think this makes it clear.
Hopefully this is all clear to you. Let me know if you have any questions. The code can be called by simply typing python NAME_OF_YOUR_FILE.py.
Edit: I didn't realize how broken the salary and years checks were, the new code should fix them.
Edit: Fixed the regex results in this version. My bad.
In this fragment you pass third function always salary = 0 and years_on_job = 0
Try this way:
salary = salary_check()
years_on_job = work_exp_check()
asses_customer(salary, years_on_job)