Python saying 'int' object isn't callable - python

I got a small project for my course, I am to write a program that simulates a person's bank account.
I'll spare the talk, the code is down below, along with the commenting....
# -*- coding: utf-8 -*-
#This program starts by taking in a user input as shown in the While loop..
#the 2 Methods in the class, 1 is for depositing money and the second is for a withdrawal..
class Account:
newBal = 0
post_bal=0
def __init__(self, balance):
self.balance = balance
def deposit(self, deposit):
self.deposit = int(deposit)
#newBal is the variable that takes the new Balance
Account.newBal = self.balance + self.deposit
print("Your Balance is now {}".format(Account.newBal))
return Account.newBal
def withdraw(self, withdraw):
self.withdraw = int(withdraw)
if self.withdraw > Account.newBal:
return "Error, we have a hard time finding that kind of money..."
else:
print("Withdrawal Accepted, have fun with that dough!")
#post_bal is the variable that stores the balance with the withdrawal taken from it
Account.post_bal = Account.newBal - self.withdraw
return("Your Balance is now {}".format(Account.post_bal))
a = Account(balance=0)
while True:
input_1 = input("What would you like to do today? [1] Deposit, [2] Withdraw ")
if int(input_1) == 1:
print(a.deposit(input("How much would you like to deposit? ")))
elif int(input_1) == 2:
print(a.withdraw(input("How much would you like to withdraw? ")))
else:
print(" I'm not too sure I understand what you're saying...")
With this I've been able to run a full loop successfully, depositing and amount and then withdrawing another, with all the outputs being returned. However, once I get either action for the second time in the loop, I get the error call...
TypeError
Traceback (most recent call last)
<ipython-input-4-6a19e620e3d6> in <module>
33 print(a.deposit(input("How much would you like to deposit? ")))
34 elif int(input_1) == 2:
---> 35 print(a.withdraw(input("How much would you like to withdraw? ")))
36 else:
37 print(" I'm not too sure I understand what you're saying...")
TypeError: 'int' object is not callable
I'm not sure what I did wrong here...

You are changing the withdraw to an int here.
def withdraw(self, withdraw):
self.withdraw = int(withdraw)
Use a different name like
def withdraw(self, withdraw):
self.withdraw_value = int(withdraw)

Related

Banking Code assignment, calling methods within a class

Being relatively new to coding, some of the small issues I have not yet learn to tweak out. In this code my goal is to print the account's name, plus their balance based off of a withdraw, deposit, or simply checking. The name and values will print, however, they are not in a line, as well as "none" prints at the end, and i cannot seem to rid it. I need suggestions on how to fix. I believe the problem stems somewhere within the methods and calling them but am not sure.
class Account:
def __init__(self, name, balance):
self.name = name
self.balance = balance
def Withdraw(self):
if Amount1 > self.balance:
self.withdraw = "You have exceeded your balance."
print (self.withdraw)
elif Amount1 < self.balance:
self.withdraw = (self.balance - Amount1)
print (self.withdraw)
def Deposit(self):
self.deposit = (self.balance + Amount2)
print (self.deposit)
def CheckBalance(self):
self.check = self.balance
print (self.check)
account1 = Account("Barbara", 500.00)
account2 = Account("Joe", 150.00)
account3 = Account("Frank", 20.00)
Action = input("What would you like to do; check balance(c), deposit(d), or withdraw(w)? ")
if Action == "w":
Amount1 = int(input("What amount would you like to withraw?"))
print (account1.name + str(account1.Withdraw()))
print (account2.name + str(account2.Withdraw()))
print (account3.name + str(account3.Withdraw()))
if Action == "d":
Amount2 = int(input("What amount would you like to deposit? "))
print (account1.name + str(account1.Deposit()))
print (account2.name + str(account2.Deposit()))
print (account3.name + str(account3.Deposit()))
if Action == "c":
print (account1.name + str(account1.CheckBalance()))
print (account2.name + str(account2.CheckBalance()))
print (account3.name + str(account3.CheckBalance()))
This is the code i have running so far

Python - class object return value

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

TypeError: insert_expenses() missing 1 required positional argument: 'amt'

I am building a budget program, and I am new to python,a month into it. I started this project in class to push myself. Well I haven't taken a database class yet and we only briefly touch on it. The issue I am having is when I am passing a tuple to sqlite3 to put the values into the corresponding fields. I have 2 files. The functions file, that is only for the functions not relating to direct database manipulation. The other file contains all the functions for database creation to manipulation.
Here is the code that is giving me problems
import budget_buddy
total_money = 0
def deposits():
"""Deposits function so we can call it later on"""
return float(input('Please enter deposit amount:'))
def input_expense_item() -> tuple:
"""
Prompt the user to enter an expense type, and the amount for the expense
:return: Tuple - expense type, amount
"""
expense_type = input("What is the expense item?\n").capitalize()
cost = None
# must ensure that the user provides a valid number! In this case, a valid decimal!
while not cost:
temp = input(f"How much was '{expense_type}'?\n")
try:
cost = float(temp)
except ValueError:
print(f"{temp} - was an invalid entry. Please make sure you entered a valid number")
# This is how to return a tuple. This means you can assign two variables when calling this function as seen below
return expense_type, cost
#def balance(expense_amount: int):
#"""Balance function to be used later on as well"""
#return total_money - expense_amount
def cash_on_hand():
"""
Cash_on_hand function, this is asking how much money not in bank
accounts do you have.
"""
return float(input('How much money do you have on hand:'))
while True:
menu_option = input("What option do you want to do?\n"
"1: Enter deposit\n"
"2: Enter cash on hand\n"
"3: Enter expenses\n"
"4: Monthly Deposit Total\n")
if menu_option == "1":
deposit_amount = deposits()
#total_money += deposit_amount
budget_buddy.insert_deposits(deposit_amount)
elif menu_option == "2":
cash_amount = cash_on_hand()
#total_money += cash_amount
budget_buddy.insert_cash(cash_amount)
elif menu_option == "3":
#new_expense_type, new_expense_amount = input_expense_item()
#print(f"The user wants to add {new_expense_type} for ${new_expense_amount}")
expense_type, cost = input_expense_item()
budget_buddy.insert_expenses(input_expense_item)
#Code below was used previously, attempting changes but keeping the code just in case for a fall back
#current_balance = balance(new_expense_amount) + cash_on_hand()
#total_money = current_balance
#print(f"Total balance is ${total_money}")
elif menu_option == "4":
budget_buddy.monthly_deposit_total()
Please ignore the comments, this code has been changed a lot since making the start of the program. And I am actively changing the way I do it.
The next is my database code,
# Importing OS module to determine desktop path
import os
import sqlite3
from datetime import datetime
from sqlite3 import Error
"""Current month with %B argument,which displays entire month name"""
current_month = datetime.now().strftime('%B')
"""Current time in year-month-day. Followed by Hour:Minute.
Used to track when data was entered.
Not used as of yet on 2020-10-17, but will be as the program develops."""
current_time = datetime.now().strftime('%Y-%m-%d')
current_time_iso = datetime.now().isoformat(sep=' ',timespec='minutes')
"""Using os module to determine the current users desktop path so we can
make the budget database file on the desktop so it is easier to find.
Sqlite3 module and Error module as well to create a connection to the
database after it is made, returning error (e) if the database does not exist."""
desktop = os.path.join(os.path.join(os.environ["USERPROFILE"]), "Desktop")
default_path = os.path.join(desktop, "budget.db")
if os.path.exists(default_path):
print('Database already exists\n')
pass
else:
print(f'Creating database budget.db at {desktop}')
pass
def sql_connection(db_file):
conn = None
try:
conn = sqlite3.connect(db_file)
print('Connected succsefully to budget.db using Sqlite3 version {}!'.format(sqlite3.version))
return conn
except Error as e:
print(e)
finally:
if not conn:
conn.close()
def monthly_table(conn):
cursorObj = conn.cursor()
cursorObj.execute(f"CREATE TABLE IF NOT EXISTS {current_month} (Deposit float, Deposit_Date real, Expense_Amount float, Expense_Type text, Cash_on_Hand float, Balance float)")
conn.commit()
print(f'Table {current_month} successfully created in budget.db')
conn = sql_connection(default_path)
if conn:
monthly_table(conn)
else:
print('Exiting')
def insert_deposits(amt):
insert_command_amt = """insert into {} (Deposit, Deposit_Date) values (?,?)""".format(current_month)
insert_amount = amt
insert_timestamp = current_time_iso
multi_insert_date_amount = insert_amount, insert_timestamp
conn.execute(insert_command_amt, multi_insert_date_amount)
conn.execute("commit;")
def monthly_deposit_total():
# mdt = monthly deposit total
mdt_query = """Select (Deposit) From {}""".format(current_month)
cursor = conn.cursor()
cursor.execute(mdt_query)
total = 0
for row in cursor:
total += row[0]
print(f"Your total deposits this month is: ${total}")
def insert_expenses(text,amt):
insert_expense_command = """insert into {} (Expense_Type, Expense_Amount) values (?,?)""".format(current_month)
insert_expense_name = str()
insert_expense_amt = amt
multi_expense_insert = insert_expense_name, insert_expense_amt
conn.execute(insert_expense_command, multi_expense_insert)
conn.execute("commit;")
My issue is the last function here,
def insert_expenses(text,amt):
insert_expense_command = """insert into {} (Expense_Type, Expense_Amount) values (?,?)""".format(current_month)
insert_expense_name = str()
insert_expense_amt = amt
multi_expense_insert = insert_expense_name, insert_expense_amt
conn.execute(insert_expense_command, multi_expense_insert)
conn.execute("commit;")
which is used by the input_expense_item function in the first code block which is my functions file.
I have been pouring over the code to find my error causing the issue but I cannot find it.
I understand it may not make sense to others why I am doing seperate tables in the database but it is how it will be done, that is not changing because I have plans for it.
The exact error I am getting is this
File "F:\Documents\GitHub\Budget_buddy\functions_for_BB.py", line
80, in
budget_buddy.insert_expenses(input_expense_item)
TypeError: insert_expenses() missing 1 required positional argument:
'amt'**
The program works as intended up until it tries to push the values to the database for the expense command.
input_expense_items returns a tuple, which is one "object", therefore, nothing is being sent to amt when insert_expenses is called. The tuple represents the exact object needed for the placeholder argument to execute. If insert_expenses takes one argument, the parsing steps can be eliminated and the argument variable will be the second arg to execute.
Okay so I finally got it fixed thank to some help. Here is what I did to get it to work as intended.
import budget_buddy
def deposits():
"""Deposits function so we can call it later on"""
return float(input('Please enter deposit amount:'))
def input_expense_item() -> tuple:
"""
Prompt the user to enter an expense type, and the amount for the expense
:return: Tuple - expense type, amount
"""
expense_type = input("What is the expense item?\n").capitalize()
cost = None
# must ensure that the user provides a valid number! In this case, a valid decimal!
while not cost:
temp = input(f"How much was '{expense_type}'?\n")
try:
cost = float(temp)
except ValueError:
print(f"{temp} - was an invalid entry. Please make sure you entered a valid number\n")
print(f'User wants to add {expense_type} for ${cost}\n')
return expense_type, cost
def cash_on_hand():
"""
Cash_on_hand function, this is asking how much money not in bank
accounts do you have.
"""
return float(input('How much money do you have on hand:'))
while True:
menu_option = input("What option do you want to do?\n"
"1: Enter deposit\n"
"2: Enter Expenses\n"
"3: Monthly Deposits Total\n"
"4: Monthly Balance\n\n")
if menu_option == "1":
deposit_amount = deposits()
budget_buddy.insert_deposits(deposit_amount)
elif menu_option == "2":
budget_buddy.insert_expenses(*input_expense_item())
elif menu_option == "3":
budget_buddy.monthly_deposit_total()
elif menu_option == "4":
#this command will take the deposits, subtract expenses and ask user if they want to add cash on hand
print('Command not implimented yet, please try again later')
below is what changed in the functions file, I unpacked the tuple in place(?) while calling the function to be used and it passes the tuple values on over
elif menu_option == "2":
budget_buddy.insert_expenses(*input_expense_item())
As you can see below where it uses the values.
def insert_expenses(expense_type, cost):
insert_expense_command = """insert into {} (Expense_Type, Expense_Amount) values (?,?)""".format(current_month)
insert_expense_name = expense_type
insert_expense_amt = cost
multi_expense_insert = insert_expense_name, insert_expense_amt
conn.execute(insert_expense_command, multi_expense_insert)
conn.execute("commit;")

Why are my classes not working properly? even though they work when only one class is active

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

Python: setting max for bank withdraw

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

Categories