I want to store my data and add them after every command, but when I choose a new command again, the initial data will be disappeared.
How do I store my data and continue adding?
My code:
initial_money = int(input('How much money do you have? '))
def records():
return
def add(records):
records = input('Add an expense or income record with description and amount:\n').split()
amount = initial_money #I don't know how to modify ...
amt = records[1]
amount += int(amt)
print('Total amount',amount)
while True:
command = input('\nWhat do you want to do (add / view / delete / exit)? ')
if command == 'add':
records = add(records)
The output:
How much money do you have? 1000
What do you want to do (add / view / delete / exit)? add
Add an expense or income record with description and amount:
tree 40
Total amount 1040
What do you want to do (add / view / delete / exit)? add
Add an expense or income record with description and amount:
mouse 70
Total amount 1070
Output I want:
How much money do you have? 1000
What do you want to do (add / view / delete / exit)? add
Add an expense or income record with description and amount:
tree 40
Total amount 1040
What do you want to do (add / view / delete / exit)? add
Add an expense or income record with description and amount:
mouse 70
Total amount 1110
You need to declare the initial_money variable a global inside the add function:
initial_money = int(input('How much money do you have? '))
def records():
return
def add(records):
records = input('Add an expense or income record with description and
amount:\n').split()
amt = records[1]
global initial_money
initial_money += int(amt)
print('Total amount', initial_money)
while True:
command = input('\nWhat do you want to do (add / view / delete / exit)? ')
if command == 'add':
records = add(records)
This should work.
Your amount variable is local and when the function exits it is not saved. You can use it as a global variable by putting it outside of the function and declaring global amount at the beginning and that way you can edit it during the run.
You just need to save it into your variable.
global initial_money # this will let you use it anywhere in the code
initial_money = int(input('How much money do you have? '))
def records():
return
def add(records):
records = input('Add an expense or income record with description and amount:\n').split()
amount = initial_money #I don't know how to modify ...
amt = records[1]
amount += int(amt)
initial_money = amount #this saves it
print('Total amount',amount)
while True:
command = input('\nWhat do you want to do (add / view / delete / exit)? ')
if command == 'add':
records = add(records)
Related
How can I fix the inputs? Because they do not show up when I run my program.
## Define the main module
def main():
## Initialize local Variables / Set Constant
homeValue = 0
propertyTaxRate = 0
bedrooms = 0
BEDROOMSURCHARGERATE = 0.0025
## Set initialized varialbes to user inputs
homeValue = float(input("How much is your home worth?"))
propertyTaxRate = float(input("What is your Property Tax Rate entered as a decimal?"))
bedrooms = int(input("How many bedrooms will your house have?"))
## Set Variables equal to results of module outputs
propertyTax = getPropertyTax(homeValue, propertyTaxRate)
bedroomSurcharge = getBedroomSurcharge(BEDROOMSURCHARGERATE, bedrooms, homeValue)
totalPropertyTax = getTotalPropertyTax(propertyTax, bedroomSurcharge)
## Report All information with a propertyTaxReport
propertyTaxReport(homeValue, propertyTaxRate, bedrooms, propertyTax, bedroomSurcharge, totalPropertyTax)
## Define getPropertyTax Module
def getPropertyTax(homeValue, propertyTaxRate):
## Calculate property tax
propertyTax = homeValue*propertyTaxRate
return propertyTax
## Define getBedroomSurcharge
def getBedroomSurcharge(BEDROOMSURCHARGERATE, bedrooms, homeValue):
## Calculate Bedroom Surcharge
bedroomSurcharge = BEDROOMSURCHARGERATE*bedrooms*homeValue
return bedroomSurcharge
## Define getTotalPropertyTax
def getTotalPropertyTax(propertyTax, bedroomSurcharge):
## Calculate totalProperty Tax
totalPropertyTax = propertyTax + bedroomSurcharge
return totalPropertyTax
## Define propertyTaxReport
def propertyTaxReport(homeValue, propertyTaxRate, bedrooms, propertyTax, bedroomSurcharge, totalPropertyTax):
## Output Variables
print("Your home costs ", homeValue, " dollars.")
print("Your property tax rate is ", propertyTaxRate)
print("Your house has ", bedrooms, "bedrooms")
print("Your property tax is equal to ", propertyTax, " dollars.")
print("Your bedroom surcharge is equal to ", bedroomSurchage, " dollars")
print("Your total property tax comes out to ", totalPropertyTax, " dollars")
return
I think you are drying a bit with your code.
A few suggestions:
You do not need to initialise a variable if this is an input from the user.
If you can simplify a calculation, just do it. Do not create many functions if they are not necessary.
You do not to print as output variables that the user gives as input. I guess the user already knows that. But if it is a serious report, maybe I can give you that.
Try this and let me know:
def main_function():
BEDROOMSURCHARGERATE = 0.0025
## Set initialized variables to user inputs
homeValue = float(input("How much is your home worth?"))
propertyTaxRate = float(input("What is your Property Tax Rate entered as a decimal?"))
bedrooms = int(input("How many bedrooms will your house have?"))
## Set Variables equal to results of module outputs
propertyTax = homeValue*propertyTaxRate
bedroomSurcharge = BEDROOMSURCHARGERATE*bedrooms*homeValue
totalPropertyTax = propertyTax + bedroomSurcharge
## Report all information with a propertyTaxReport
return (totalPropertyTax, f"bedroom Surcharge was {bedroomSurcharge}")
To call the function just do:
main_function()
You can return this tuple or print the whole thing you have at the end, up to you. I just point out that you can return just a value or a sentence.
As an assignment I am making a simple interface in python which can show a balance, add to that balance, take out money from that balance, check the interest rate and then lastly check the three previous actions done. This will be choice == 5. So what do I write in the bottom def in order to do so?
usd = 500
def main():
print("""
1. Balance
2. Add
3. Retrieve
4. Interest
5. Last Changes
""")
choice = int(input("Choose: "))
if choice == 1:
global usd
balance()
elif choice == 2:
add()
elif choice == 3:
retrieve()
elif choice == 4:
interest()
elif choice == 5:
changes()
def balance():
global usd
print("Balance: ", round((usd),2))
main()
def add():
global usd
amount = int(input("How much do you want to add? "))
usd = amount + usd
print("New balance = ", round((usd),2))
main()
def retrieve():
global usd
amount = int(input("How much do you want to retrieve: "))
usd = usd - amount
print("New balance = ", round((usd),2))
main()
def interest():
global usd
if usd<=1000000:
usd = ((usd/100)*101)
print("New balance: ", round(((usd/100)*101), 2))
elif usd>=1000000:
usd = ((usd/100)*102)
print("New balance: ", round(((usd/100)*102), 2))
main()
def changes():
main()
main()
The desired output will look a little like this;
Choose: 5
+6105
-500000
+1110000
It sounds like you want to keep a log of the previous actions. You could do this by creating a list and appending a new entry each time an action is done. Then your changes function could print out the last 3 items in the list.
You could make the list global and access it in the same way you access usd.
You could also make the list in main and pass it to changes as an argument. If you decide to do it this way, you could make each function return their log so that you can append it to the list in main.
For example (using only the add function illustrate)
Using a global variable (this is bad practice, but is shorter):
usd = 500
log = []
def add():
global usd
amount = int(input("How much do you want to add? "))
usd = amount + usd
print("New balance = ", round((usd),2))
log.append(f"+{amount}") # add change to log
main()
def changes():
# print last 3 items in log
for change in log[-3:]:
print(change)
main()
Or the more typical way, using a loop (without a global variable)
usd = 500
def main():
log = []
choice = 0
while choice != 6:
print("""
1. Balance
2. Add
3. Retrieve
4. Interest
5. Last Changes
6. Quit
""")
choice = int(input("Choose: "))
if choice == 1:
balance()
elif choice == 2:
log.append(add()) # add change to log
elif choice == 3:
log.append(retrieve()) # add change to log
elif choice == 4:
interest()
elif choice == 5:
changes(log)
def add():
global usd
amount = int(input("How much do you want to add? "))
usd = amount + usd
print("New balance = ", round((usd),2))
return f"+{amount}"
def changes(log):
# print last 3 items in log
for change in log[-3:]:
print(change)
main()
A potential problem with this approach is because you are adding items to the log list indefinitely, theoretically you may eventually run out of memory on your computer. To remedy, you can remove extra logs from the list whenever the length of the list is greater than 3.
Documentation for lists: https://docs.python.org/3/tutorial/datastructures.html
Global variables are bad practice in general, so it would be preferable to avoid making usd a global variable, but I'll leave that up to you
The last stretch of my banking project I've been working on is the deposit/withdraw function. I've gotten most of the other bits working (outside of cleaning up the code) I'm not fully understanding how one adds and subtracts a number from a sql statement inside of python...so here's the part of the code I'm struggling with:
here are my tables:
sqlite_file = 'banking2_db.sqlite'
table_1 = 'Bartertown'
table_2 = 'PINs'
id_column = 'Card_Numbers'
column_1 = 'Character_PINs'
column_2 = 'Balances'
column_3 = 'Card_Numbers'
column_4 = 'Characters'
class LoginPrompt:
def Login(self):
while True:
print(menu[1])
self.Card_number=str(input('>> '))
print(menu[2])
while True:
try:
self.Character_PINs = getpass.getpass('>> ')
self.one_row = c.execute('SELECT * FROM {tn} WHERE {cn}=? and {cnn}=?'.\
format(tn=table_1, cn=column_1, cnn=column_3), (self.Character_PINs, self.Card_number,))
for row in self.one_row.fetchone():
print('Welcome: ', row)
input('Press any key to continue... ')
return
except:
print('PIN incorrect; try again')
break
#MINOR ISSUE, ONLY QUERIES CHAR COLUMN
def loginMenu(self):
while True:
print(menu[5])
print("\n1 - Deposit funds")
print("2 - Withdraw funds")
print("3 - Check balance")
print("4 - Reset Pin")
print("5 - Exit")
while True:
try:
choice = int(input("Please enter a number: "))
except ValueError:
print("Please choose a valid entry")
if choice >= 1 and choice <=5:
choice == 1:
amount = input("\nPlease enter the deposit amount: ")
if amount != '' and amount.isdigit():
int(amount)
balance = c.execute('UPDATE {tn} SET {cn} = Balances +:amount WHERE Card_Numbers =:self.Card_number' .\
format(tn=table_1, cn=column_2,))
new_bal = balance + (int(amount))
print('${} has been deposited to account {} and the new balance is ${}'.\
format(amount, self.Card_number, balance + (int(amount))))
for row in self.Balances.fetchone():
print('Your new balance is: ', new_bal)
return self.loginMenu()
basically, I'm trying to make sure the program can only pull the balance where the PIN and the Card Number are specified. It selects the balance (This part is working, it is another option in the menu) however, the UPDATE function is still a mystery to me. I understand how to update both the ENTIRE column...on accident, and also how to change the value presented in the Balance field to the value the user submitted ie: the user selects to deposit 100 caps, and then their balance becomes 100 caps. The column I'm trying to update is called Balances, Card_Numbers is the column containing the users "credit card" and amount is the value the user just entered.
Thank you for your help.
edit: added tables, and initial input of the data.
If you want to update the column Balances then your statement should be:
...SET Balances = Balances + :amount...
so do it like this:
c.execute("UPDATE " + table_1 + " SET Balances = Balances + ? WHERE Card_Numbers = ?", (amount, self.Card_number,))
Finally figured it out, silly me.
choice == 1:
amount = input("\nPlease enter the deposit amount: ")
if amount != '' and amount.isdigit():
int(amount)
balance = c.execute('UPDATE {tn} SET {cn} = Balances +:amount WHERE Card_Numbers =:self.Card_number' .\
format(tn=table_1, cn=column_2,))
new_bal = balance + (int(amount))
I was trying to reference it by printing the output of the of the db while it hadn't been committed yet, :eyeroll:
Thank you for the help forpas, it worked like a charm.
Working on a homework problem. Have almost all of the code working but for some reason cant seem to get my program to save and exit properly.
here is the prompt given.
You should create a program that manages a tab-separated text file containing employees travel expenses. There are 4 and only 4 employees who travel for the company: alice, bob, carl, and diane. Each record in the data file will contain an employee name, a destination city, miles traveled, and gallons used.
For full credit:
Your program should properly read and store the given data to and from the tab-separated data file. That is, I should be able to use your program with my data file without error.
When the data is read into your program it should be organized as a list of dictionaries, where each dictionary is a row in the file, using these dictionary keys: name, city, miles, gallons.
You need to add functionality to display the user's name, total miles traveled, total gallons used, average mpg, and the expense of the total miles at 75 cents per mile. This should work for any of the 4 proper user names you enter.
You do not need to do any data validation unless just want to.
If and only if your program runs exactly like it should, I will add a 10 point bonus if, rather than using concatenation, you properly use the python CSV module to read and write the data to and from the file, converting the tab-separated data to a dictionary and vice versa.
You need to use the base code provided by the lecture notes, more or less. All 4 menu options should work.
Use formatting to have everything line up in neat columns for display option 1.
My problem is that I cannot get the 4th option "Save and exit" to function properly.
def read_file(travels):
salesperson_list = []
with open("travels.txt", 'r') as infile:
for line in infile.readlines():
line = line.strip().split('\t')
d = {}
d['name'] = line[0]
d['city'] = line[1]
d['miles'] = eval(line[2])
d['gallons'] = eval(line[3])
salesperson_list.append(d)
return salesperson_list
def display_all_data(data):
print('{0:<8}{1:<15}{2:<8}{3:<8}'.format('Name', 'City', 'Miles', 'Gallons'))
for row in data:
print('{0:<8}{1:<15}{2:^8}{3:^8}'.format(row.get('name'), row.get('city'), \
row.get('miles'), row.get('gallons')))
def calculate_user_data(data):
name = input('Enter user name: ').lower()
total_miles = sum([row.get('miles') for row in data if row.get('name') == name])
total_gallons = sum([row.get('gallons') for row in data if row.get('name') == name])
cities = [row.get('city') for row in data if row.get('name') == name]
mpg = total_miles/total_gallons
owed = mpg*0.75
print('Total miles travelled: {0}'.format(total_miles))
print('Total gallons used: {0}'.format(total_gallons))
print('mpg = ',mpg)
print('expense = $', owed, 'at 75 cents per mile')
def add_a_trip(data):
name = input('Input name: ').lower()
city = input('Input city travelled: ').lower()
miles = eval(input('Enter miles travelled: '))
gallons = eval(input('Enter gallons used: '))
d = {}
d['name'] = name
d['city'] = city
d['miles'] = miles
d['gallons'] = gallons
data.append(d)
print('Data added successfully')
def save_And_exit(data):
with open('F:\\travels.txt','w') as outfile:
for row in data:
outfile.write(row.get('name')+'\t'+row.get('city')+'\t'+\
str(row.get('miles'))+'\t'+str(row.get('gallons'))+'\n')
print('Saved to file')
def menu(salesperson_list):
print('Menu options. Choose 1, 2, 3, or 4')
print('[1] Display all trip data')
print('[2] Calculate user data')
print('[3] Add a trip')
print('[4] Save an exit')
while True:
choice = input('Enter choice --> ')
if choice == '1':
display_all_data(salesperson_list)
elif choice == '2':
calculate_user_data(salesperson_list)
elif choice == '3':
add_a_trip(salesperson_list)
elif choice == '4':
save_And_exit(salesperson_list)
print('Bye')
break
else:
print('Invalid selection')
def main():
salesperson_list = read_file('F:\\travels.txt')
menu(salesperson_list)
main()
I just need my program to save and exit properly with no global variables
def main():
totalprofit = 0
stockname = input("Enter the name of the stock or -999 to quit: ")
while stockname != "-999":
sharesbought, purchasingprice, sellingprice, brokercommission = load()
amountpaid, amountofpaidcommission, amountstocksoldfor, amountofsoldcommission, profitorloss = calc(sharesbought, purchasingprice, sellingprice, brokercommission)
output(stockname, amountpaid, amountofpaidcommission, amountstocksoldfor, amountofpaidcommission, profitorloss)
stockname = input("Enter the name of the next stock (or -999 to quit): ")
totalprofit += profitorloss
print("\n Total profit is: ", format(totalprofit, '.2f'))
def load():
sharesbought = int(input("Number of shares bought: "))
purchasingprice = float(input("Purchasing price: "))
sellingprice = float(input("Selling price: "))
brokercommission = float(input("Broker commission: "))
return sharesbought, purchasingprice, sellingprice, brokercommission
def calc(sharesbought, purchasingprice, sellingprice, brokercommission):
amountpaid = sharesbought * purchasingprice
amountofpaidcommission = amountpaid * (brokercommission/100)
amountstocksoldfor = sharesbought * sellingprice
amountofsoldcommission = amountstocksoldfor * (brokercommission/100)
profitorloss = (amountpaid + amountofpaidcommission) - (amountstocksoldfor - amountofsoldcommission)
return amountpaid, amountofpaidcommission, amountstocksoldfor, amountofsoldcommission, profitorloss
def output(stockname, amountpaid, amountofpaidcommission, amountstocksoldfor, amountofsoldcommission, profitorloss,):
print("\n Stock name: ", stockname, sep = '')
print("Amount paid for the stock: ", format(amountpaid, '.2f'))
print("Commission paid to broker when the stock was bought: ", format(amountofpaidcommission, '.2f'))
print("Amount the stock sold for: ", format(amountstocksoldfor, '.2f'))
print("Commission paid to broker when the stock was sold: ", format(amountofsoldcommission, '.2f'))
print("Profit or loss: ", format(profitorloss, '.2f'))
main ()
The objective of the first function is to allow a user to input the followings as many times as she or he wants until the user decides is done:
Stock name
Shares bought
Selling price
Broker commission
My main problem is then in the main function. I am skeptical whether I am using the while loop correctly or if it's correct at all. I tried to run the program but it won't output anything.
Also, shouldn't I add this at the end of the program with the values inputted to call all the functions above:
def main()
load()
calc()
output()
Or is it fine within the while loop?
I think a while loop is perfectly appropriate for this use case, where you want to loop an indeterminate number of times, stopping when some condition is not met.
There is one obvious problem, on this line:
stockname +=1
This doesn't make any sense. Since stockname is a string, you can't add one to it. Instead, you should be asking the user for the next stock name (or a "special" value to signal they're done). Try replacing that line with something like:
stockname = input("Enter the name of the next stock (or -999 to quit): ")
The rest of your code appears correct, if rather verbose. Unless you think it's likely you'll call some of your other functions in some other place in your code, it might be simpler and cleaner to include all the logic in one function. Functions are nice, but you should balance the benefits of isolating each part of your code in its own function against the effort of passing lots of values between them.