Python Repetition Structures and Files - python

I have a question about my python program . I have trouble finding the total and ntotal in this program. Rest works fine. Is there any way i can fix this? I have this program due soon. I'd appreciate any tips I can get :D Thanks
midSalary = 50000
maxSalary = 60000
def main():
inFile = open('program7.txt', 'r')
lineRead = inFile.readline()
total = 0.0
ntotal = 0.0
count = 0
while lineRead != '':
words = lineRead.split()
for word in words:
num = float(word)
total += num
count += 1
print("\nFaculty Member # ",count, ": $" , format(num, '.2f'), sep ="")
if num >= maxSalary:
payIncrease(num, .04)
elif num >= midSalary:
payIncrease(num, .07)
else:
payIncrease(num , .055)
lineRead = inFile.readline()
#averagePayRaise = (ntotal - total) / count
inFile.close()
for divider in range(45):
print("-", end ='')
print("\nTotal Faculty payroll : $", format(total , ",.2f"),sep ="")
print("The New Total Faculty payroll : $", format(ntotal , ",.2f"),sep ="")
print("Average Pay Raise : $", format(averagePayRaise, ",.2f"), sep ="")
def payIncrease(amount, prcnt):
print("Pay Raise Percent : ", format(prcnt*100, ".1f")+"%")
total = 0.0
ntotal = 0.0
count = 0
salRaise = amount * prcnt
newSal = amount + salRaise
print("Pay Raise : $", format(salRaise, ',.2f'), sep ="")
print("New Salary : $", format(newSal, ',.2f'), sep = "")
total += amount
count += 1
ntotal += newSal
averagePayRaise = (ntotal - total) / count
main()

By default, names that you assign to in Python are local to the function in which they are declared. So, if you have:
def main():
total = 0
def payIncrease():
total = 0
total += amount
then you have two independent values named total. One way to solve this is to make it global:
total = 0
def main():
global total
total = 0
def payIncrease():
global total
total += amount
Note that you don't want to assign total = 0 inside payIncrease(), because that would reset your running total to 0. You probably added that when you broke out your code into the payIncrease() function because Python gave you an error without that.

def payIncrease(salary):
if current_sal >= maxSalary: return 0.04
if current_sal >= midSalary: return 0.07
return 0.055
def processSalaryData(line):
"""take a line and return current salary and new salary (note that a line is actually just a float)"""
try:
current_sal = float(line)
except ValueError:
return None
return current_sal,current_sal + current_sal*payIncrease(current_sal)
def main():
salaryData = [processSalaryData(line) for line in open("salaries.txt")]
salaryData = filter(None,salaryData) #filter out invalid data
adjustments = [b-a for a,b in salaryData]
old_salaries,new_salaries = zip(*salaryData)
print "OLD TOTAL PAYROLL :",sum(old_salaries)
print "NEW TOTAL PAYROLL :",sum(new_salaries)
print "AVG ADJUSTMENT:",sum(adjustments)/len(adjustments)
print "MAX SALARY:",max(new_salaries)
print "MIN SALARY:",min(new_salaries)

Related

How to count the total amount of list correctly

I am trying to write an accounting book and got struggled with total amount counting, it can be count after the list print out but the number is incorrect. I tried to do it with + to count for total amount, but is not working.
What am I doing wrong?
import os
def read_file(filename):
items = []
with open(filename, 'r', encoding='utf-8') as f:
for line in f:
if 'your product,your price' in line:
continue
#product,price = line.strip().split(',')
#item.append([product, price])
else:
print("list>>> ----v")
return item
def user_input(item):
while True:
product = input("\nitem:")
if product == 'q':
break
price = input("\nprice:")
price = int(price)
item.append([product, price])
return item
def print_file(item):
for price in item:
print(price[0], 'is: ', price[1])
#total amount
count = price[1]
total_count = count + count
num = (f"you spend total {total_count}")
print(num)
def write_file(filename, item):
with open(filename, 'w', encoding='utf-8') as f:
f.write('your product,your price\n')
for price in item:
f.write(price[0] + ':' + str(price[1]) + '\n')
def main():
filename = 'list.text'
if os.path.isfile(filename):
print("File Found")
file = read_file(filename)
else:
print("Wlecome")
item = []
item = user_input(item)
print_file(item)
write_file('list.txt', item)
main()
You made a small naming error when adding the counts, try this:
def print_file(item):
total_count = 0
for price in item:
print(price[0], 'is: ', price[1])
#total amount
count = price[1]
total_count += count
num = (f"you spend total {total_count}")
print(num)
Alternative:
def print_file(item):
total = 0
for price in item:
print(price[0], 'is: ', price[1])
total += price[1]
num = (f"you spend total {total_count}")
print(num)
or simply
def print_file(item):
total = sum([price[1] for price in item])
print(f"you spend total {total}")

How to iterate code and save each output to a list

I'm just learning how to code and I've encountered a problem I can't seem to work around. I've built a strategy for a simple game of chance (similar to the Martingale strategy for those familiar) and I want to run the code n number of times and save the output of each iteration so I can aggregate the results. Note the current 'for' loop is part of my code, I tried using another 'for' loop to run the entire program n times to no avail. Thanks heaps in advance. Apologies if this is a silly question. Here is my code:
import math
import random
import heartrate
heartrate.trace(browser=True)
mult = 1.2
winChance = 0.8250
balance = 259
x = 0
for i in range (0,500):
bet1 = balance/259
balance = balance-bet1
print(balance)
n = random.random()
if n > winChance:
bet2 = (bet1*(1/(mult-1)))+bet1
balance = balance-bet2
n = random.random()
if n > winChance:
bet3 = ((bet1+bet2)*(1/(mult-1)))+bet1
balance = balance-bet3
n = random.random()
if n > winChance:
bet4 = ((bet1+bet2+bet3)*(1/(mult-1)))+bet1
balance = balance-bet4
n = random.random()
if n > winChance:
bet5 = ((bet1+bet2+bet3+bet4)*(1/(mult-1)))+bet1
balance = balance-bet5
print("end")
break
else:
balance = balance = bet4*mult
else:
balance = balance + bet3*mult
else:
balance = balance + bet2*mult
else:
balance = balance + bet1*mult
If I understand the question and code correctly (doubtful), this change would do what you ask for: Running your original code N times (with N = 10):
$ diff -u iterate.py.orig iterate.py
--- iterate.py.orig 2022-03-20 13:02:54.010642003 +0100
+++ iterate.py 2022-03-20 13:17:35.368615800 +0100
## -5,10 +5,12 ##
mult = 1.2
winChance = 0.8250
+end_balances = []
-balance = 259
-x = 0
-for i in range (0,500):
+for _ in range(10):
+ balance = 259
+ x = 0
+ for i in range (0,500):
bet1 = balance/259
balance = balance-bet1
print(balance)
## -35,7 +37,7 ##
break
else:
- balance = balance = bet4*mult
+ balance = balance + bet4*mult
else:
balance = balance + bet3*mult
## -47,3 +49,6 ##
else:
balance = balance + bet1*mult
+ end_balances.append(balance)
+
+print(end_balances)
Here is the full code:
import math
import random
import heartrate
heartrate.trace(browser=True)
mult = 1.2
winChance = 0.8250
end_balances = []
for _ in range(10):
balance = 259
x = 0
for i in range (0,500):
bet1 = balance/259
balance = balance-bet1
print(balance)
n = random.random()
if n > winChance:
bet2 = (bet1*(1/(mult-1)))+bet1
balance = balance-bet2
n = random.random()
if n > winChance:
bet3 = ((bet1+bet2)*(1/(mult-1)))+bet1
balance = balance-bet3
n = random.random()
if n > winChance:
bet4 = ((bet1+bet2+bet3)*(1/(mult-1)))+bet1
balance = balance-bet4
n = random.random()
if n > winChance:
bet5 = ((bet1+bet2+bet3+bet4)*(1/(mult-1)))+bet1
balance = balance-bet5
print("end")
break
else:
balance = balance + bet4*mult
else:
balance = balance + bet3*mult
else:
balance = balance + bet2*mult
else:
balance = balance + bet1*mult
end_balances.append(balance)
print(end_balances)
Note that you normally would extract the inner loop into a separate function.
Edit: Fixed the typo in the innermost else as well.
You can start by creating an empty list such as:
balance_end = []
And then appending the final balance after each iteration (I have fixed the first else which had a typo as well), such as:
else:
balance = balance + bet4*mult
balance_end.append(balance)
else:
balance = balance + bet3*mult
balance_end.append(balance)
else:
balance = balance + bet2*mult
balance_end.append(balance)
else:
balance = balance + bet1*mult
balance_end.append(balance)
Finally, you can safely assume that the balance_end index will match the number of iteration - 1 and the value, is the corresponding value of said iteration.
Here's my attempt to simplify things (to be honest, the code is quite convoluted and difficult to understand):
def bet(win_chance, previous_bets, mult):
if random.random() > win_chance:
this_bet = -1 * ((sum(previous_bets)*(1/(mult-1)))+previous_bets[0])
else:
this_bet = previous_bets[-1]*mult
return this_bet
# initialise variables
mult = 1.2
win_chance = 0.8250
balance = 259
for i in range(500):
previous_bets = []
previous_bets.append(balance/259)
balance -= previous_bets[0]
for i in range(5):
lost = bet(win_chance, previous_bets, mult)
balance += previous_bets[-1]
if not lost:
break
else:
# lost streak after 5 attempts
print('end')
print(balance)
create a list and append balance values to it
import math
import random
import heartrate
heartrate.trace(browser=True)
mult = 1.2
winChance = 0.8250
balance = 259
x = 0
values = list()
for i in range (0,500):
stop = False
bet1 = balance/259
balance = balance-bet1
print(balance)
n = random.random()
if n > winChance:
bet2 = (bet1*(1/(mult-1)))+bet1
balance = balance-bet2
n = random.random()
if n > winChance:
bet3 = ((bet1+bet2)*(1/(mult-1)))+bet1
balance = balance-bet3
n = random.random()
if n > winChance:
bet4 = ((bet1+bet2+bet3)*(1/(mult-1)))+bet1
balance = balance-bet4
n = random.random()
if n > winChance:
bet5 = ((bet1+bet2+bet3+bet4)*(1/(mult-1)))+bet1
balance = balance-bet5
print("end")
stop = True
else:
balance = balance = bet4*mult
else:
balance = balance + bet3*mult
else:
balance = balance + bet2*mult
else:
balance = balance + bet1*mult
values.append(balance)
if stop:
break

Donation system loop where the system will ask again until the fixed target amount is reached

I wrote this code but I don't know how to add all donations for each donor when the loop runs several times.
It should print like this:
Donor 1 has donated £10 in total
Donor 2 has donated £15 in total...
import random
number_of_staff = (random.randint(3,5))
suggested_donation = (random.randint(10, 20))
amount_to_be_raised = number_of_staff * suggested_donation
a = []
def amount():
print('Amount to be raised by team number ______is £', amount_to_be_raised, '.')
print('Number of staff that will contribute is', number_of_staff)
print('Suggested donation is', suggested_donation)
def donation_loop(number_of_staff):
for j in range(number_of_staff):
print('Donor', j + 1)
actual_donation = int(input('Please enter donation £'))
a.append(actual_donation)
global b
b = sum(a)
print('The total sum donated is', b)
def stop():
while b < amount_to_be_raised:
donation_loop(number_of_staff)
else:
pass
amount()
donation_loop(number_of_staff)
stop()
Your code is almost correct, you have several ways to fix it, my favorite one is as follows:
import random
number_of_staff = (random.randint(3,5))
suggested_donation = (random.randint(10, 20))
amount_to_be_raised = number_of_staff * suggested_donation
a = {}
def amount():
print('Amount to be raised by team number ______is £', amount_to_be_raised, '.')
print('Number of staff that will contribute is', number_of_staff)
print('Suggested donation is', suggested_donation)
def donation_loop(number_of_staff):
global total_donations
for j in range(number_of_staff):
print('Donor', j + 1)
actual_donation = int(input('Please enter donation £'))
total_donations += actual_donation
if f'Donor{j + 1}' not in a:
a[f'Donor{j + 1}'] = []
a[f'Donor{j + 1}'].append(actual_donation)
print('The total sum donated is', total_donations)
def stop():
while total_donations < amount_to_be_raised:
donation_loop(number_of_staff)
amount()
total_donations = 0
stop()

updating a return value within a function

The issue i am having is getting the value of a returned item to update from different functions within a main function.
I have tried syntax to see if that changed anything, but I am not sure what needs to happen to get (in this case: the count and total).
I have also tried setting the functions = count, total but that returned an error.
def main():
terminate = False
print("Welcome to the self-checkout system at Wake-Mart.")
count, total = scan_prices()
print('')
disc = discount(count, total)
print('')
promo = promotion(count, total)
balance = total
def scan_prices():
total = 0
count = 0
prices = float(input("Enter the price of the first item:"))
while prices > 0:
count +=1
total = total + prices
print("Number of items:", count, "Total:", total)
prices = float(input("Eneter the price of the next item [or 0 to stop]:"))
while prices < 0:
print("Price cannot be negative.")
prices = float(input("Eneter the price of the next item [or 0 to stop]:"))
if prices > 0:
count +=1
total = total + prices
print("Number of items:", count, "Total:", total)
prices = float(input("Eneter the price of the next item [or 0 to stop]:"))
continue
return count, total
def discount(count, total):
if count >= 10:
print("You've got a 10% discount for buying 10 items or more.")
total = total * .9
print("Number of items:", count, "Total:", total)
return total
def promotion(count, total):
if total >= 50:
card = input(print("Do you want to buy a $50 gift card for $40 [y/n]:"))
if card == 'Y' or 'y':
print("Thank you for buying a giftcard.")
count +=1
total = (total * .9) + 40
print("Number if items:", count, "Total:", total)
else:
print("Thank for your purchases.")
print("Number if items:", count, "Total:", (total * .9))
return count, total
main()
I am just wanting the total and count to be updated as I move from one function execution to the next within the main function.
It looks like your main should take the return of one function and pass it to the next:
def main():
terminate = False
print("Welcome to the self-checkout system at Wake-Mart.")
count, total = scan_prices()
print('')
total = discount(count, total)
print('')
count, total = promotion(count, total)
balance = total

Function not defined, although its been defined... Going Insane

So I am quite new to python and have been working on this assignment for a week now on and off and can't quite get it to run correctly. I am now getting errors that tell me the function get_in_code is not defined although I've defined it. Any help would be greatly appreciated!
SENTINEL = 'XXX'
DAY_CHARGE = 1500.00
#Define get_days
def get_days():
good_data = False
while not good_data:
try:
n_days = int(input("Please enter the number of days you stayed: "))
except ValueError:
print("Error, Bad Data")
else:
if n_days > 0:
good_data = True
else:
print("This is bad data, please re enter data")
return n_days
#define get_cost(p)
def get_cost():
cost = float(input("Please enter the cost for the procedures: "))
while cost < 0:
print("Procedure cost cant be negative: ")
cost = float(input("Please enter the cost for the procedures: "))
return cost
#define med cost
def med_cost():
med_cost = float(input("Enter the cost of your medicine: "))
while med_cost < 0:
print("Medicine cost cant be negative: ")
med_cost = float(input("Enter the cost of your medicine: "))
return med_cost
#Find day cost
def find_day_cost(in_code, n_days):
day_cost = n_days * DAY_CHARGE
if in_code == 'ZH':
p_day_cost = day_cost * 0.20
in_day_cost = day_cost *0.80
elif in_code == 'HH':
p_day_cost = day_cost * 0.10
in_day_cost = day_cost * 0.90
elif in_code == 'CH':
p_day_cost = day_cost * 0.25
in_day_cost = day_cost * 0.75
else:
p_day_cost = day_cost
in_day_cost = 0
return p_day_cost, in_day_cost
#find procedure cost
def find_proc_cost(in_code, cost):
if in_code == 'ZH':
p_proc_cost = 0
in_proc_cost = cost
elif in_code == 'HH':
p_proc_cost = cost * 0.10
in_proc_cost = cost * 0.90
elif in_code == 'CH':
p_proc_cost = cost * 0.50
in_proc_cost = cost * 0.50
else:
p_proc_cost = cost
in_proc_cost = 0
return p_proc_cost, in_proc_cost
#find medicine cost
def find_med_cost(in_code, med_cost):
if in_code == 'ZH':
p_med_cost = 0
in_med_cost = med_cost
elif in_code == 'HH':
p_med_cost = med_cost * 0.10
in_med_cost = med_cost * 0.90
elif in_code == 'CH':
p_med_cost = med_cost * 0.50
in_med_cost = med_cost * 0.50
else:
p_med_cost = med_cost
in_med_cost = 0
return p_med_cost, in_med_cost
#Display pat_info
def display_pat_info(pat_name, in_name):
print("City Hospital - Patient Invoice")
print("Patient Name: ", pat_name)
print("Insurance: ", in_name)
#display day cost
def display_day_cost(p_day_cost, in_day_cost):
print("Patient Day Cost: ", p_day_cost,"\tInsurance Day Cost: ", in_day_cost)
#display procedure cost
def display_proc_cost(p_proc_cost, in_proc_cost):
print("Patient Procedure Cost: ", p_proc_cost, "\tInsurance Procedure Cost: ", in_proc_cost)
#display medicine cost
def display_med_cost(p_med_cost, in_med_cost):
print("Patient Medicine Cost: ", p_med_cost, "\tInsurce Medicine Cost: ", in_med_cost)
#Display totals
def display_totals(total_pat, total_in):
print("Total Billed To Patient: ", total_pat, "\tTotal Billed To Insurance: ", total_in, "\tTotal Bill: ", (total_pat + total_in))
#display day_totals
def display_day_totals(total_zip, total_happy, total_cheap, total_pat):
print("City Hospital - End Of Day Billing Report")
print("Total Dollar Amount Billed Today: ", total_zip+total_happy+total_cheap+total_pat)
print("Total Billed To Zippy Healthcare: ", total_zip)
print("Total Billed To Happy Healthcare: ", total_happy)
print("Total Billed To Cheap Healthcare: ", total_cheap)
print("Total Billed To Uninsured: ", total_pat)
#display day_counts()
def display_day_counts(zip_count, happy_count, cheap_count, no_in_count):
print("The total amount of Zippy Healthcare patients is: ", zip_count)
print("The total amount of Happy Healthcare patients is: ", happy_count)
print("The total amount of Cheap Healthcare patients is: ", cheap_count)
print("The total amount of Uninsured patients is: ", no_in_count)
#def main
def main():
#Counters and accumulators
total_zip= 0.00
total_cheap= 0.00
total_happy= 0.00
total_pat= 0.00
zip_count= 0
cheap_count= 0
happy_count= 0
no_in_count= 0
total_in = 0
#Open file
try:
Pat_File = open('PatientBill.txt', 'w')
except ValueError:
print("*****ERROR***** - Corrupt File")
else:
file_exist = True
#Priming read
pat_name = input("Please enter the patients name: (XXX to stop program)")
#Processing loop
while pat_name != SENTINEL:
#Input data
in_code = get_in_code()
num_days = get_days()
proc_cost = get_cost()
med_cost = med_cost()
#find each cost
pat_day, insure_day = find_day_cost(in_code, num_days)
pat_proc, insure_proc = find_proc_cost(in_code, proc_cost)
pat_med, insure_med = find_med_cost(in_code, med_cost)
#update accumulators and totals
total_pat += pat_day + pat_proc + pat_med
if in_code == 'ZH':
zip_count += 1
total_zip += in_day_cost + in_proc_cost + in_med_cost
in_name = 'Zippy Healthcare'
elif in_code == 'HH':
happy_count += 1
total_happy += in_day_cost + in_proc_cost + in_med_cost
in_name = 'Happy Healthcare'
elif in_code == 'CH':
cheap_count += 1
total_cheap += in_day_cost + in_proc_cost + in_med_cost
in_name = 'Cheap Healthcare'
else:
no_in_count += 1
in_name = 'Uninsured'
total_in = total_zip + total_happy + total_cheap
#displays patients invoice
display_pat_info(pat_name,in_name)
display_day_cost(pat_day, insure_day)
display_proc_cost(pat_proc, insure_proc)
display_med_cost(pat_med, insure_med)
display_totals(pat_day + pat_proc + pat_med, insure_day + insure_proc + insure_med)
#Write output to file
if file_exist:
Pat_File.write(pat_name, pat_day+pat_med+pat_proc )
#Get next patients name
pat_name = input("Please enter the patients name: (XXX to stop program)")
#Close the output file
if file_exist:
Pat_File.close()
#display the accumlators and totals
display_day_totals(total_zip, total_happy, total_cheap, total_pat)
display_day_counts(zip_count,happy_count,cheap_count,no_in_count)
#define get_in_code
def get_in_code():
in_code = input("Please enter one of the insurance codes, ZH, CH, HH, XX")
while in_code not in ('ZH', 'HH', 'CH', 'XX'):
print("***Please enter a proper insurance code***")
in_code = input("Please enter one of the insurance codes, ZH, CH, HH, XX")
return in_code
main()
Python is a interpreted language. You need to define function prior to its usage. Just move a function definitions at the top of a file.
The problem is also with indentation. You're defining your methods inside while, just after a return statement. Actual functions aren't defined at all - interpreter doesn't reach those lines.
Besides, the code is "dirty". Split the code into separate classes/modules. Create well defined areas of responsibility, that would improve the code and it'll be easier to work with it.

Categories

Resources