I'm new to python and I am still trying to get the hang of it. I'm attempting to change the processing function in the following code so that the user can not withdraw more money then what the "bank" has on record, which is 500. I was hoping that someone could help. Would I enter an if statement for >500?
#Simple Bank Atm
def main():
PIN=7777;balance=500;pin=0;success=False
Pin=getInput(pin)
Pin,PIN,balance,success=processing(pin,PIN,balance,success)
Display(success,balance)
#Input Function
def getInput(pin):
pin=int(input(“Please enter your PIN:”))
return pin
#Processing Function
def processing(pin,PIN,balance,success):
if pin==PIN:
success=True
amt=float(input(“How much would you like to withdraw?”))
balance=balance-amt
return pin,PIN,balance,success
else:
success=false
return pin,PIN,balance,success
You can use an if condition to do this.
if amt <= balance: #Can't withdraw over your current balance
balance -= amt
else:
print("Error. Amount exceeds funds on record.")
Also, other things aside you're returning the same thing inside your if and else condition and if this is what you really want to return it's redundant to have it in both. You can just have it after your else statement at the same indentation level
def main():
PIN=7777;balance=500;pin=0;success=False
Pin=getInput(pin)
Pin,PIN,balance,success=processing(pin,PIN,balance,success)
Display(success,balance)
#Input Function
def getInput(pin):
pin=int(input("Please enter your PIN:"))
return pin
#Processing Function
def processing(pin,PIN,balance,success):
if pin==PIN:
success=True
amt=float(input("How much would you like to withdraw?"))
if balance<amt:
print("Amount to draw is greater than balance.")
return pin,PIN,balance,false
balance=balance-amt
return pin,PIN,balance,success
else:
success=false
return pin,PIN,balance,success
Yes. You should use an if statement - this should happen before they can withdrawal the amount (balance = balance - amt).
So you could do something like this:
if amt <= balance:
balance -= amt
return True
else:
# do not change balance and stop withdrawal
return False
Related
For example, let's say I'm trying to create a wallet system in python where money can be add to and taken out of. I try this code here:
balance = 0
def addmoney(x):
x += balance
addmoney(10000)
print(balance)
but it just gave me 0.
so then I tried this:
def addmoney(x):
balance = 0
balance += x
And I realized that this would set the money back to 0 every time the user adds money, which I didn't want. Is there a solution to this?
You could declare the balance variable as global inside the function.
balance = 0
def addmoney(x):
global balance
balance += x
addmoney(10000)
print(balance)
This is usually do with OOP:
class BankAccount:
def __init__(self, owner, balance, currency):
self.owner = owner
self.balance = balance
self.currency = currency
def print_balance(self):
print("Your current balance is:")
print(self.balance)
def make_deposit(self, amount):
if amount > 0:
self.balance += amount
else:
print("Please enter a valid amount.")
def make_withdrawal(self, amount):
if self.balance - amount >= 0:
self.balance -= amount
else:
print("You don't have enough funds to make this withdrawal.")
To call the function:
my_savings_account = BankAccount("Pepita Perez", 45600, "USD")
my_savings_account.print_balance()
my_savings_account.make_deposit(5000)
my_savings_account.make_withdrawal(200)
my_savings_account.print_balance()
In Python, you must use the global keyword when accessing global variables from within a function. See here.
One way to keep track of the changes is to store the previous values in a list outside the function. Again, using the global keyword
Also your logic for the balance is backwards. You should be adding x to the balance.
balance = 0
historyLst = []
def addmoney(x):
global balance
global historyLst
historyLst.append(balance)
balance += x
addmoney(10000)
print(balance)
Beginner Pythonista here
Making a betting game as part of an OOP exercise.
made a Player class with a bet function:
# Player Class
class Player():
def __init__(self,name):
self.name = name
self.hand = []
self.chips = 0
def deposit(self,amount):
self.chips += int(amount)
print(f"{amount} chips deposited.\nTotal available funds: {self.chips}")
def bet(self):
amount = int(input("Place your bet: "))
if not amount > self.chips:
self.chips -= amount
print(f"You bet {amount}. New Balance: {self.chips}")
return amount
else:
print("You cannot bet above your chips")
I was under the impression that a method within a class acted as a function, but the "return amount" command returns "None/NoneType".
How can I return the integer value to add to assign to a variable?
Thanks in advance
Probably went through else statement, that does not return anything. Tried your code and it works as expected if you meet if criteria in bet function (one that has return)
a.chips = 100
a.bet()
Place your bet: >? 1
You bet 1. New Balance: 99
Out[8]: 1
Your code seems right except for the else condition. You should add to else condition in the method bet
return 0
or raise an error
raise ValueError('You cannot bet above your chips')
then you should handle it wherever you want to use it.
There is an indentation Error for me. The If statement in the bet method shouldnt be indented. After fixing that it works fine for me.
Creating an object from class Player:
test_player = Player("TestName")
Giving some deposit:
test_player.deposit(10)
10 chips deposited.
Total available funds: 10
And finally the betting:
test_player.bet()
Place your bet: >? 5
You bet 5. New Balance: 5
The last bet gives:
test_player.bet()
Place your bet: >? 6
You cannot bet above your chips
so my classes won't recognize each other but when left to work alone they do work as seen in the consult printing at the bottom of the post. However the deposit and transfer are popping up the ram location, however, they do work fine when done separately just as shown in the consult action in the bottom part.
<function cashier.deposit at 0x0000023A9B656048>
import datetime
now = datetime.datetime.now()
class account:
owner = "name"
pin = "1823"
balance = 800
def __init__(self, transfer, withdraw, deposit, consult):
self.transfer = transfer
self.withdraw = withdraw
self.deposit = deposit
self.consult = consult
class cashier:
def __init__(self, withdraw, deposit, transfer, consult):
self.transfer = transfer
self.consult = consult
self.withdraw = withdraw
self.deposit = deposit
def deposit(self):
print("Please type pin to proceed")
if account.pin == 1823:
print("who would you like to send money to?")
else:
print("Invalid pin")
def transfer(self):
pass
def withdraw(self):
withdrawal = input("How much money do you want to withdraw? (there is a limit up to 10,000$ a day!)")
account.balance -= int(withdrawal)
if int(withdrawal) > 10000:
print("withdrawals cannot be larger than 10,000 a day!")
exit()
elif int(withdrawal) > account.balance:
print("your account does not have enough funds to complete your transaction")
else:
print("Transaction succesfull!\nPlease collect your money")
print('Today is', now)
print("Hello %s!\nWhat can I do for you today?" % account.owner)
action = input("Use commands such as withdraw, deposit, transfer or consult to continue!\n")
if action == "withdraw":
print(cashier.withdraw)
if action == "consult":
print("Your account's balance is %s $" % str(account.balance))
if action == "transfer":
print(cashier.transfer)
if action == "deposit":
print(cashier.deposit)
else:
print("Uknown command, exiting programm")
exit()
The various functions of cashier do not return anything, so the prints are just printing the string representation of the function. You could have the functions return a string like so:
class Cashier: # PEP8 calls for CamelCase here
def deposit(self):
pin = input("Please type pin to proceed")
if Account.pin == pin:
return "who would you like to send money to?"
else:
return "Invalid pin"
def transfer(self):
pass
def withdraw(self):
withdrawal = input("How much money do you want to withdraw? (there is a limit up to 10,000$ a day!)")
Account.balance -= int(withdrawal)
if int(withdrawal) > 10000:
return "withdrawals cannot be larger than 10,000 a day!"
elif int(withdrawal) > Account.balance:
return "your Account does not have enough funds to complete your transaction"
else:
return "Transaction successful!\nPlease collect your money"
Edit: I removed the initializer, as these weren't doing anything. You need to instantiate your cashier with cashier = Cashier(), then call the functions of Cashier with cashier.withdraw().
There's a fundamental misunderstanding on how classes work here (and OOP in general). You should read through the Python docs on building classes before you go any further.
To use your classes, you need to instantate them like this
Cashier = cashier()//I don't think you should ask for the transfer details while instantiating. But you can do that by adding the parameter in the bracket
Now you can use the functions on the Cashier variable like:-
Cashier.deposit(deposit_money)
I think if you don't want to instantiate and want a function which does not actually store data, you can use a static function but I don't think that is what you want to do
So I basically created my functions ( def main(), load(), calc(), and print().
But I do not know how I can allow the user to input the information as many times as he/she wants until they want to stop. Like I they input 5 times, it would also output 5 times. I have tried putting the while loop in the def main() function and the load function but it won't stop when I want it to. Can someone help? Thanks!
def load():
stock_name=input("Enter Stock Name:")
num_share=int(input("Enter Number of shares:"))
purchase=float(input("Enter Purchase Price:"))
selling_price=float(input("Enter selling price:"))
commission=float(input("Enter Commission:"))
return stock_name,num_share,purchase,selling_price,commission
def calc(num_share, purchase, selling_price, commission):
paid_stock = num_share * purchase
commission_purchase = paid_stock * commission
stock_sold = num_share * selling_price
commission_sale = stock_sold * commission
profit = (stock_sold - commission_sale) - ( paid_stock + commission_purchase)
return paid_stock, commission_purchase, stock_sold, commission_sale, profit
def Print(stock_name,paid_stock, commission_purchase, stock_sold, commission_sale, profit):
print("Stock Name:",stock_name)
print("Amount paid for the stock:\t$",format(paid_stock,'10,.2f'))
print("Commission paid on the purchase:$", format(commission_purchase,'10,.2f'))
print("Amount the stock sold for:\t$", format(stock_sold,'10,.2f'))
print("Commission paid on the sale:\t$", format(commission_sale,'10,.2f'))
print("Profit(or loss if negative):\t$", format(profit,'10,.2f'))
def main():
stock_name,num_share,purchase,selling_price,commission = load()
paid_stock,commission_purchase,stock_sold,commission_sale,profit = calc(num_share, purchase, selling_price, commission)
Print(stock_name, paid_stock,commission_purchase, stock_sold, commission_sale, profit)
main()
You have to give the user some kind of way to declare their wish to stop the input. A very simple way for your code would be to include the whole body of the main() function in a while loop:
response = "y"
while response == "y":
stock_name,num_share,purchase,selling_price,commission = load()
paid_stock,commission_purchase,stock_sold,commission_sale,profit = calc(num_share, purchase, selling_price, commission)
Print(stock_name, paid_stock,commission_purchase, stock_sold, commission_sale, profit)
response = input("Continue input? (y/n):")
an even simpler way would be two do the following....
while True:
<do body>
answer = input("press enter to quit ")
if not answer: break
alternatively
initialize a variable and avoid the inner if statement
sentinel = True
while sentinel:
<do body>
sentinel = input("Press enter to quit")
if enter is pressed sentinel is set to the empty str, which will evaluate to False ending the while loop.
First, I will warn you, I am new at this so please bear with me. I created the following program (for a class, of course) and everything works except that the withdrawal calculation spits out a negative number when the value shouldn't be negative. Can you guys see what I'm doing wrong?
Thanks in advance
#define the main
def main():
name=input('Enter the customer\'s name: ')
account_id=input('Enter the account ID: ')
code=input('Enter the transaction code:')
previous_balance=float(input('Enter the previous balance: '))
transaction_amount=float(input('Enter the transaction amount: '))
if code == "w" or code == "W":
process_withdrawal (transaction_amount, previous_balance)
else:
if code == "d" or code == "D":
process_deposit (transaction_amount, previous_balance)
else:
process_invalid_transaction_code (previous_balance)
#define process withdrawal
def process_withdrawal (previous_balance, transaction_amount):
if previous_balance >= transaction_amount:
print('You have entered an invalid transaction amount')
balance=previous_balance
print_balance (balance)
else:
balance=previous_balance-transaction_amount
print_balance (balance)
#define process deposit
def process_deposit (previous_balance, transaction_amount):
balance=previous_balance+transaction_amount
print_balance (balance)
#define invalid transaction code
def process_invalid_transaction_code (previous_balance):
print('You have entered an invalid transaction code.')
balance=previous_balance
print_balance (balance)
#define print balance
def print_balance(balance):
print('Your current balance is :', format(balance, '.2f'))
main()
Your call to process_withdrawal has the first argument as transaction_amount and the second as previous_balance, but the function declaration has previous_balance as the first argument and transaction_amount as the second.
Try this:
if code == "w" or code == "W":
process_withdrawal(previous_balance, transaction_amount)
You are passing the arguments backwards.
process_withdrawal (transaction_amount, previous_balance)
and
def process_withdrawal (previous_balance, transaction_amount):
I think your if statement within process withdrawl should be
if previous_balance < transaction_amount: