I have a python problem almost done with the problem..but still have a few more question :( will fan
def povertyLevel(): inFile = open('program10.txt', 'r') outFile = open('program10-out.txt', 'w') outFile.write(str("%12s %12s %15s\n" % ("Account #", "Income", "Members"))) lineRead = inFile.readline() # Read first record while lineRead != '': # While there are more records words = lineRead.split() # Split the records into substrings acctNum = int(words[0]) # Convert first substring to integer annualIncome = float(words[1]) # Convert second substring to float members = int(words[2]) # Convert third substring to integer outFile.write(str("%10d %15.2f %10d\n" % (acctNum, annualIncome, members))) lineRead = inFile.readline() # Read next record # Close the file. inFile.close() # Close file # Call the main function. povertyLevel() I am trying to find the average of annualIncome and what i tried to do was avgIncome = (sum(annualIncome)/len(annualIncome)) outFile.write(avgIncome) i did this inside the while lineRead. however it gave me an error saying avgIncome = (sum(annualIncome)/len(annualIncome)) TypeError: 'float' object is not iterable
@e.mccormick
First, I am not sure why you are goint to an outfile. You want to read in the data, work on it, print out the results.
we need an output file that gives the result for the assignment
Ah, OK. It also needs at least 5 functions.
The avereage household income would be the sum of all the household incomes divided by the number of housholds. So you need to keep track of bot of those things.
this is my updated code def povertyLevel(): inFile = open('program10.txt', 'r') outFile = open('program10-out.txt', 'w') outFile.write(str("%12s %12s %15s\n" % ("Account #", "Income", "Members"))) allIncomes = [] lineRead = inFile.readline() # Read first record while lineRead != '': # While there are more records words = lineRead.split() # Split the records into substrings acctNum = int(words[0]) # Convert first substring to integer annualIncome = float(words[1]) # Convert second substring to float members = int(words[2]) # Convert third substring to integer allIncomes.append(annualIncome) outFile.write(str("%10d %15.2f %10d\n" % (acctNum, annualIncome, members))) lineRead = inFile.readline() # Read next record averageInc = avgIncome(allIncomes) outFile.write(str(averageInc)) # Close the file. inFile.close() # Close file def avgIncome(income): avgInc = (sum(income)/len(income)) # Call the main function. povertyLevel() however right now i get NONE as the output for outFile.write(str(averageInc))
this is my input file
"Write a program to read the survey results into three lists and perform the following analysis." You need to read everything into the three lists firsts, then do the analysis. It does look like you will output everything into the Program10-out.txt file... though the program is a bit vague on some of the output.
See, "Count the number of households included in the survey and print it in a three-column format." Ummm... the count of the number will be just a number, so how would a number be a 3 column format? That is the vague part.
i got the 3 column part done for my program. now im trying to finish the average income and families above average income and poverty level
OK, well, for the average income you need to sum all incomes and divide by the number of households. Lets see... hmm... so the problem is it is returning none. Wellm have you tried printing what is passed to it? See if you are actually seinding something to it. Then, see what it is getting.
when i print print(averageInc) i also get non
OK, so it is not getting anything back from the function... do you see why?
Have you been taught about the scope of a function?
yeah. the local and global variables right?
i know if i print inside def avgIncome(income) i will get the answer. however i got stuck when i tried to do def avgIncome(income): avgInc = (sum(income)/len(income)) outFile = open('program10-out.txt', 'w') outFile.write("average income is " + str(avgInc)) as this wont do anything
Had a browser lockup, wheee... Yes, in that case the outfile is not open in that function. So it knows nothing about the file. Now, here is another thing to think about: ``` allincome = [12180, 13240, 19800] def avgIncome1(input): average = sum(input)/len(input) def avgIncome2(input): return sum(input)/len(input) avg1 = avgIncome1(allincome) avg2 = avgIncome2(allincome) print(avg1) print(avg2) ``` Try that code.
avg1 came up none avg 2 gave solution
omg you're a genius! instead of doing average = i had to change the code to def avgIncome(income): return(sum(income)/len(income))
Yah, you were not returning anything, which is wat the whole none was about. Your scope restrictions caused you to get none because you never used return to pass it back.
If you do things in another funtion, they need to have no need for a return (AKA: A void function/method that just outputs something) or have it return what is needed. You could return a list, a tuple of lists, etc. You could try to do something and return true for if it worked and false for if it failed, which is used in error handling.
now i need to make an if statement to find each household that exceeds the average. so would this make sense? def povertyLevel(): inFile = open('program10.txt', 'r') outFile = open('program10-out.txt', 'w') outFile.write(str("%12s %12s %15s\n" % ("Account #", "Income", "Members"))) allIncomes = [] lineRead = inFile.readline() # Read first record while lineRead != '': # While there are more records words = lineRead.split() # Split the records into substrings acctNum = int(words[0]) # Convert first substring to integer annualIncome = float(words[1]) # Convert second substring to float members = int(words[2]) # Convert third substring to integer allIncomes.append(annualIncome) outFile.write(str("%10d %15.2f %10d\n" % (acctNum, annualIncome, members))) lineRead = inFile.readline() # Read next record averageInc = (avgIncome(allIncomes)) outFile.write("average income is " + str(averageInc)) if annualIncome > averageInc : print(acctNum, annualIncome, members) # Close the file. inFile.close() # Close file def avgIncome(income): return(sum(income)/len(income)) # Call the main function. povertyLevel()
this is the solution for the program.
See, if you load everyting into lists, you can loop through them again and again as needed. This is important because you need all the incomes to find the average, Once you have the average you can use it to print out who is above that.
if i try if annualIncome > averageInc : print(acctNum, annualIncome, members) i will only get the very last one and if i try if allIncomes > averageInc : print(acctNum, annualIncome, members) i get an error :(
Like I said, you missed one of the original instructions which is why you can't do it.
T_T not quite getting it :(
One way to solve these type of problems is to diagram out something that will satisfy the instructions given. For example: ``` main: list_of_lists = readin(filename) average = findAvg(list_of_lists[1]) output3col(list_of_lists, filename) outputAbobeAvg(list_of_lists, average, filename) outputBelowPoverty(list_of_lists, filename) readin(fn): reds in a file parses it returns a list of the lists you need average(list) takes in a list returns average of that list etc... ``` Then you just need to make code that does those actual things. In your instructions, one of the key concepts that made me organize it this way is at the top. "Write a program to read the survey results into three lists and perform the following analysis." So I must have three lists. Now, I can deal with these as a list of lists, or because this is Python, I think you can actually return it to three seperate lists.
Heck,, if you only wanted one output, you could also pass around a string to output, or make a global, keep adding to it and when it is done, push the string to a file.
You have made only one list. A list of the incomes. You can cycle through that list, but it does not let you access the other information. You do not have the ID numbers or the number of people in the household. You need two more lists to have all of those. Once you have all three lists made, you can do the other evaluations. So you need to build them while you are reding in the file.
:D gotcha.... I'll try to grasp everything you just told me! i think im getting it! (My 3rd month doing programming)
Nother example for you to thiink about: ``` allIDNum = [1234, 1235, 1236] allincome = [12180, 13240, 19800] allHeadcount = [2, 3, 7] for i in range(0, len(allIDNum)): print(str(allIDNum[i]) + " " + str(allincome[i]) + " " + str(allHeadcount[i]) ) ``` I do not know what loops you have done yet, but you should be able to see a path with that. I am going to head out now. Need to get home!
@e.mccormick thank you very much for helping me so far! i couldn't have gotten this far without you! thanks
np. Don't have too much fun. And I think as long as you remember the stuff about returns, that plus doing multiple lists will let you finish this.
thanks! i'll keep that in my mind
i'm overwhelmed by this problem.. i have no idea how to figure it out :(
What are you stuck on?
Like I said, you have one list and you need three. If you make three lists when you are loading stuff from the file, then you can do the rest.
def povertyLevel(): inFile = open('program10.txt', 'r') outFile = open('program10-out.txt', 'w') outFile.write(str("%12s %12s %15s\n" % ("Account #", "Income", "Members"))) allIncomes = [] numMembers = [] accountNum = [] lineRead = inFile.readline() # Read first record while lineRead != '': # While there are more records words = lineRead.split() # Split the records into substrings acctNum = int(words[0]) # Convert first substring to integer annualIncome = float(words[1]) # Convert second substring to float members = int(words[2]) # Convert third substring to integer allIncomes.append(annualIncome) numMembers.append(members) accountNum.append(acctNum) outFile.write(str("%10d %15.2f %10d\n" % (acctNum, annualIncome, members))) lineRead = inFile.readline() # Read next record outFile.write('---------------------------------------------''\n''\n') averageInc = (avgIncome(allIncomes)) outFile.write("Families above the average income of " + str(averageInc) + '\n') aboveAverage = aboveAvg(allIncomes,[averageInc]) outFile.write(str(aboveAverage)) for length in range(len(allIncomes)): return(str(allIncomes[length]) + str(numMembers[length]) + str(accountNum[length])) #povertyLevel = povLevel(numMembers) #outFile.write(povertyLevel) # Close the file. inFile.close() # Close file def avgIncome(income): return(sum(income)/len(income)) def aboveAvg(income,avg): average = avg return income > average def povLevel(family): poevrtLevel = 15730.00+ 4060.00 *((family) - 2) # Call the main function. povertyLevel() this is my updated code list.... i have three lists... but idk how to continue from there. anything below that for loop doesn't work in the outputfile. and I'm mentally tired :'(
aboveAverage = aboveAvg(allIncomes) outFile.write("\n" + str(aboveAverage)) def aboveAvg(income): avg = avgIncome(income) return [inc for inc in income if inc > avg] this only prints the income. what can i do to print both income, membercount , accountnumber?
i'm also getting a type error for povLevel (which calculates the poverty level)
Can you attach program10.txt
this is my updated povLevel def povLevel(income,family): fam1 = [mem - 2 for mem in family] fam2 = [fam * 4060.00 for fam in fam1] fam = [fami + 15730.00 for fami in fam2] poverty = [a- b for(a,b) in zip (fam, income)] return [inc for inc in income if inc > poverty]
Nevermind, you already did.
Paste the entire up to date version of the program you currently have and I'll try to help you solve your problems.
def povertyLevel(): inFile = open('program10.txt', 'r') outFile = open('program10-out.txt', 'w') outFile.write(str("%12s %12s %15s\n" % ("Account #", "Income", "Members"))) allIncomes = [] numMembers = [] accountNum = [] lineRead = inFile.readline() # Read first record while lineRead != '': # While there are more records words = lineRead.split() # Split the records into substrings acctNum = int(words[0]) # Convert first substring to integer annualIncome = float(words[1]) # Convert second substring to float members = int(words[2]) # Convert third substring to integer allIncomes.append(annualIncome) numMembers.append(members) accountNum.append(acctNum) outFile.write(str("%10d %15.2f %10d\n" % (acctNum, annualIncome, members))) lineRead = inFile.readline() # Read next record outFile.write('---------------------------------------------''\n''\n') averageInc = (avgIncome(allIncomes)) outFile.write("Families above the average income of " + str(averageInc) + '\n') aboveAverage = aboveAvg(allIncomes) outFile.write("\n" + str(aboveAverage)+ '\n') povertyLevel = povLevel(allIncomes,numMembers) outFile.write("\n" + str(povertyLevel)) # Close the file. inFile.close() # Close file def avgIncome(income): return(sum(income)/len(income)) def aboveAvg(income): avg = avgIncome(income) return [inc for inc in income if inc > avg] def povLevel(income,family): fam1 = [mem - 2 for mem in family] fam2 = [fam * 4060.00 for fam in fam1] fam = [fami + 15730.00 for fami in fam2] poverty = [a- b for(a,b) in zip (fam, income)] return [inc for inc in income if inc > poverty] # Call the main function. povertyLevel()
def povLevel wont work right now.
my solution is supposed to look something like this
From the PDF it doesn't seem like he requires it to be sorted, and yet the sample solution is indeed sorted. Do you know anything about this?
it doesn't need to be sorted. my professor just did the solution like that
So start by defining a function that returns the poverty level based on the number of family members.
You've misunderstood the PDF. You iterate over each household and based on the number of members check to see if it is below the poverty level.
if(allIncomes[i] < povertyLevel(numMembers[i])) append household i to the list
Don't you see?
Still here?
this is the first time i'm writing to a file.. which had me confused on a lot of part
yep :(
povertyLevel = povLevel(allIncomes,numMembers) if(allIncomes[i] < povertyLevel(numMembers[i])): numMembers.append(members) something like that?
sorry my open study crashed :(
Look at the sample output
You need to list the members below the poverty level. So you need to return the list below the poverty level.
man.. coding is soo hard :(
for some reason this one is not clicking to me
do i need to make another list for members?
Have you worked with dictionaries yet?
i've seen it.. but have not used it in my codes yet
other than append and a few ones
dictionaries lets you have anything in your list right?
i just wanna give up :(
can you give me another hint plz ;(
Just use it as a reference, you should still write your own.
Thanks man...I'll definitely use this as a reference..I don't know some of your functions..but thank you
If you are fairly new to Python my style might be a bit confusing.
Sorry
I'm new to coding itself... I'll figure it out once I have a reference :) thanks @Alchemista
@Alchemista i had a few questions about the program which you gave me
Sure
what does lambda do?
allIncomes = [] numMembers = [] accountNum = [] def main(): database() #userinfo() def database(): inFile = open('program10.txt', 'r') outFile = open('program10-out.txt', 'w') outFile.write(str("%15s %12s %12s\n\n" % ("Account #", "Members", "Income"))) lineRead = inFile.readline() # Read first record while lineRead != '': # While there are more records words = lineRead.split() # Split the records into substrings acctNum = int(words[0]) # Convert first substring to integer annualIncome = float(words[1]) # Convert second substring to float members = int(words[2]) # Convert third substring to integer allIncomes.append(annualIncome) numMembers.append(members) accountNum.append(acctNum) outFile.write(str("%12d %12d %15.2f\n" % (acctNum, members, annualIncome ))) lineRead = inFile.readline() # Read next record outFile.write('---------------------------------------------''\n''\n') averageInc = (avgIncome(allIncomes)) outFile.write("Families above the average income of " + str(averageInc) + '\n'+'\n') householdsAboveAvg(outFile,accountNum,numMembers,allIncomes,averageInc) poverty_level(outFile) # Close the file. inFile.close() # Close file def avgIncome(income): return(sum(income)/len(income)) def householdsAboveAvg(outFile,accountNum,members,annualIncome,average): for idx in range(len(accountNum)): if annualIncome[idx] > average: outFile.write('\t'+ str(accountNum[idx]) + '\t''\t' + str(members[idx])+ '\t''\t'+ str(annualIncome[idx])+'\n') def poverty_level(outFile): account = 0 headCount =0 for mem in numMembers: povLv = (15730.00 + 4060.00 * (mem - 2)) headCount+=1 for inc in allIncomes: if inc < povLv: account+= 1 avgPoverty = account / headCount outFile.write("\nPercentage of Households below the 2014 poverty level is: " + str(avgPoverty*100)) This is my final code!... thanks man! i couldn;t have done this without you!!
So all working now, eh?
yeah! :D @e.mccormick i just have starting trouble T_T if you believe in such thing lol....
People tend to wall at some point. They miss one or two concepts and now everything starts to need to work together. In programming, nothing works if one thing fails. So you have people with their frustration levels suddenly going up.
Join our real-time social learning platform and learn together with your friends!