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.
Related
Below is my code. the issue is in MAIN. The code works as a person trying to buy items into a cart and you can see the total price of those items. They have to enter in the price for each item that they want. If a person inputs a number to two decimal places, it rounds it to the nearest whole number.
import locale
class CashRegister:
def __init__(self):
mself.items = 0
self.price = int(float(0.00))
def addItems(self,price): #keeps track of total number of items in cart
self.price += price
self.items += 1
print(self.price)
def getTotal(self): #returns total price
return self.price
def getCount(self): #return the item count of the cart
return self.items
def clearCart(self): #clears cart for another user or checkout
self.items = 0
self.price = int(float(0.00))
def main():
user_name = input('What is your name?\n') #weclomes user
print("Hello",user_name)
locale.setlocale(locale.LC_ALL, 'en_US')
user_name = CashRegister() #user is using the cash register
while True:
line = input ("Would you like to add another food item to your cart? Choose y or n \n")
if line == "y":
** price = int(float(input("please input the price of the item\n")))
print(price)**
user_name.addItems(price) #user adds prices to cart
elif line == "n":
print("Your total checkout price:", locale.currency(user_name.getTotal()) )
# int(float(locale.currency(user_name.getTotal())))
print("Your total item count", user_name.getCount())
user_name.clearCart() #clears cart for another user/checkout
break
else:
print("Error")
if __name__ == '__main__':
main()
As soon as the person inputs the number, I printed it to see if that's where the problems lies. I'll enter 3.20 but it automatically converts it to 3. I have no idea how to force it to keep those decimals. I even tried printing it with the int/float and it still doesn't work.
The int() function always returns an integer. An integer never has any decimal points. So use only
float(input("please input the price of the item\n"))
instead of
int(float(input("please input the price of the item\n")))
The input function of my code is repeating 3 times before going onto the next function. I have tried using while true and break and return None but none of that helps.
def welcome():
print("Welcome to the Interest Loan Calculator")
def inp():
loan = input("Enter loan amount: ")
rate = input("Enter interest rate: ")
return loan, rate
def conv():
loan, rate=inp()
if loan.endswith('K'):
multiplier = 1000
loan = loan[0:len(loan)-1]
elif loan.endswith('M'):
multiplier = 1000000
loan = loan[0:len(loan)-1]
return int(float(loan) * multiplier)
def calc():
loan = conv()
print (loan)
def close():
print ("close placeholder")
def main():
welcome()
inp()
conv()
calc()
close()
if __name__ == "__main__":
main()
When running the code it asks me to input both loan and rate 3 times before moving to the calc function.
If you don't want to call inp three times, then don't. You call it once directly from the main program; you call it a second time through the sequence main => conv => inp, and a third time through main => calc => conv => inp.
I think you need to draw out the call tree of your program, and then alter it to match the design you actually want.
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;")
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
I'm a beginner to Python and programming, and I'm trying to make a simple piggy bank that will be able to deposit or withdraw pennies, nickels, dimes, and quarters. I don't know how to loop the code or how to store the data if I enter a coin to be able to keep adding to the total number of coins in the bank. I can only do it so it runs and tells me if I add, for example, 100 pennies, that my bank has 100 pennies. but then it resets. How do I do this? my code is probably awful but here's what I have so far based off my current knowledge of python (added empty parts like the "return" and pennies_previous so anyone reading can understand my thought process, and the withdrawstep() function has not been added yet):
print "Welcome to the Piggy Bank!"
def depositstep():
deposit = raw_input("What would you like to deposit? (P for pennies, N for nickels, D for dimes, Q for quarters): ").upper()
if deposit == 'P':
pennies_previous =
pennies_instance = raw_input("How many pennies would you like to deposit?: ")
pennies_total = int(pennies_instance) + pennies_previous
print "There are %s pennies in your bank"% (pennies_total)
return execute()
elif deposit == 'N':
N = raw_input("How many nickels would you like to deposit?: ")
return
elif deposit == 'D':
D = raw_input("How many dimes would you like to deposit?: ")
return
elif deposit == 'Q':
Q = raw_input("How many quarters would you like to deposit?: ")
return
else:
return "Sorry. Please Type P for pennies, N for nickels, D for dimes, or Q for quarters."
def execute():
exc = raw_input("Would you like to deposit or withdraw money? (D for deposit, W for withdraw): ").upper()
if exc == 'D' or exc == 'DEPOSIT':
return depositstep()
elif exc == 'W' or exc == 'WITHDRAW':
return withdrawstep()
else:
return "Sorry. Please type D for deposit or W for withdrawal."
print execute()
You should store your total amount of pennies in the original variable.
pennies_previous= int(pennies_instance) + pennies_previous then the amount of pennies will be stored there.
If you are looking to make the bank continue to store the value of the bank for each session, then you are going to want to save the bank's value to a file. You could do it like this:
1. First, make a file with a name like bankvalue.txt.
2. Then, add these lines before every return:
value = open(bankvalue.txt, 'w') # that opens your bankvalue.txt file in write mode
value.write('\n'pennies_previous) #You should use the answer above for the pennies_previous
value.close() #saves the file
3.Then, in order to tell a person their balance you would use the readline() function
I hope that was what you were looking for
I would use a python dictionary instead of variables:
do so as:
bank = {'pennies':0, 'nickles':1, 'dimes':0, 'quarter':0}
to increase either of those you do
bank['pennies'] += int(pennies_instance) # not need the pennies_previous
Then you need to write that to a file which you could do:
f = open('filename','w')
f.write(bank.items())
f.close
But that don't preserve the python structure. But you can use json module, which is simple as:
import json
f = open('filename','wb')
json.dump(bank,f)
f.close()
And at the start of the script you need to fetch the data from the file, you do this with
f = open('bank.dat','rb')
bank = json.load(f)
It would look like this:
import json
f = open('bank.dat','rb')
bank = json.load(f)
f.close()
## you code goes here.
f = open('bank.dat','wb')
json.dump(bank,f)
f.close()
There are some other problems in your code that should be addressed too.
1) In the 'else' part of your code, if the user inputs the wrong letter it terminates, instead it should call the function again.
2) You don't need to return a string and print it in the 'print execute()', you could just print it in place and don't return anything.