Need help on loop and on this program in general

  • (2 Pages)
  • +
  • 1
  • 2

16 Replies - 1659 Views - Last Post: 19 April 2016 - 01:30 PM Rate Topic: -----

#1 bird13   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 27-March 16

Need help on loop and on this program in general

Posted 13 April 2016 - 09:48 AM

Program is below:

The results of a survey of the households in your township are available for public scrutiny.
Each record contains data for one household, including a four-digit integer identification
number, the annual income for the household, and the number of household members.
Write a program to read the survey results into three lists and perform the following
analysis.
a. Count the number of households included in the survey and print it in a three-column
format.
b. Calculate the average household income, and list the identification number and income
of each household that exceeds the average.
c. Determine the percentage of households that have incomes below the 2015 United
States’ Contiguous States poverty level. Compute the poverty level income using the
formula below.
povertyLevel = 15930.00 + 4160.00 * (m – 2)
where m is the number of members of each household. This formula shows that the
poverty level depends on the number of family members, m, and the poverty level income
increases as m gets larger.


So far I have below. I can get the average and list the households, etc. I am having a hardtime trying to figure out what loop I need to do to find out the households that are above the poverty level. Do i need to write it to a list? Im not getting an error, I just need some guidance.

def lists():
    
    inFile = open('program9.txt', 'r')
    outFile= open('program8.txt', 'w')

    outFile.write(str("%12s %12s %15s" % ("Account #", "Income", "Members")))
    
    allIncome = []
    acctNum = []
    accountNum=[]
    annualIncome = []
    members = []
    numofmem=[]
    count = 0
    total = 0
    household  =0

    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
       print('The numbers of households included in the survey are',acctNum, format(annualIncome, '.2f'), members, sep=' ')
       print('')
       total+=members
       household+=annualIncome
       allIncome.append(annualIncome)
       numofmem.append(members)
       accountNum.append(acctNum)


       outFile.write(str("%10d  %15.2f  %10d" % (acctNum, annualIncome, members)))


       
       lineRead = inFile.readline()    # Read next record
       outFile.write('-------------------------------------------------------')
       
       
 

    

    average_household = (avg(allIncome))

    outFile.write("Families above the average income of " + str(average_household) + '') 

    print('The total average household income is',format(average_household, '.2f'))

    
    outfile.write(str(aboveAverage)
    

    inFile.close()
    
    
    
def avg(income):

    return(sum(income)/len(income))

    

def exceeds():

    acct=[0]
    mem=[2]
    annual=[1]
    above_average=[]
    more=[]
    above=0
    count=0
    morethan=0
    inFile = open('program9.txt', 'r')

    lineRead = inFile.readline()

    words_words = lineRead.split()
    acct=int(words_words[0])
    annual=float(words_words[1])
    mem=int(words_words[2])
    above_average.append(annual) 
    poverty=15930.00 + 4160.00 * (mem - 2 )
    aboveitall=above_average


    
    if annual < poverty:
        below=poverty/mem * 100
        print('The percentage of households that have incomes below the poverty level is',format(below,'.2f'))
    elif annual > poverty:
        print('the houses above poverty are',aboveitall)
    else:
        print('error')


 def povLevel(themembers):
     povertLevel = 15730.00+ 4060.00 *((themembers) - 2)


Is This A Good Question/Topic? 0
  • +

Replies To: Need help on loop and on this program in general

#2 DK3250   User is offline

  • Pythonian
  • member icon

Reputation: 562
  • View blog
  • Posts: 1,798
  • Joined: 27-December 13

Re: Need help on loop and on this program in general

Posted 14 April 2016 - 03:58 AM

In line 8, 11 and 13 you make three list; later, in line 28-30 you add values to those lists.
Suppose you make one more list named 'poverty'; this list you update (below existing line 30) with the value '0' or '1' depending of whether this household is below or above the poverty threshold. Then you just need to determine the percentage of '0's in the 'poverty' list.

The calculation of below/above poverty threshold can be made in a small function; a simplified version of the current 'exceeds' function. Or you can do it directly in the code and skip the 'exceeds' function.
Was This Post Helpful? 0
  • +
  • -

#3 bird13   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 27-March 16

Re: Need help on loop and on this program in general

Posted 14 April 2016 - 04:53 AM

Thanks for the response. I dont think we are allowed to use the exceeds function, so how would i do this in directly in the code? This is the part where we did not learn or were told how to calculate this kind of info, especially from a file. I think making lists and appending the info to the list would be easier, if I can get an example that would be great.
Was This Post Helpful? 0
  • +
  • -

#4 DK3250   User is offline

  • Pythonian
  • member icon

Reputation: 562
  • View blog
  • Posts: 1,798
  • Joined: 27-December 13

Re: Need help on loop and on this program in general

Posted 14 April 2016 - 05:57 AM

Ok, then...
def lists():
    
    inFile = open('program9.txt', 'r')
    outFile= open('program8.txt', 'w')

    outFile.write(str("%12s %12s %15s" % ("Account #", "Income", "Members")))
    
    allIncome = []
    acctNum = []
    accountNum=[]
    annualIncome = []
    members = []
    numofmem=[]
    poverty = []  # new empty list
    count = 0
    total = 0
    household  =0

    lineRead = inFile.readline()       # Read first record
    while lineRead != '':              # While there are more records    ## NOTE: you only use three space as indent here...
       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
       print('The numbers of households included in the survey are',acctNum, format(annualIncome, '.2f'), members, sep=' ')
       print('')
       total+=members
       household+=annualIncome
       allIncome.append(annualIncome)
       numofmem.append(members)
       accountNum.append(acctNum)

       if annualIncome <= 15930 + 4160 * (numofmem – 2):  # new condition
           poverty.append(0)  # add zero to the list if below threshold
       else:
           poverty.append(1)  # ..or add '1' if above


       outFile.write(str("%10d  %15.2f  %10d" % (acctNum, annualIncome, members)))


       
       lineRead = inFile.readline()    # Read next record
       outFile.write('-------------------------------------------------------')
       
       
 

    
    non_poverty_pct = sum(poverty) / len(poverty) * 100  # calculation of percentage non-poverty

    average_household = (avg(allIncome))

    outFile.write("Families above the average income of " + str(average_household) + '') 

    print('The total average household income is',format(average_household, '.2f'))

    
    outfile.write(str(aboveAverage)
    

    inFile.close()
    
    
I've just re-read the post#1, - maybe you should switch '0' and '1' for calculation of the percentage below the limit. Or subtract from 100 the value found here.
Was This Post Helpful? 0
  • +
  • -

#5 bird13   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 27-March 16

Re: Need help on loop and on this program in general

Posted 14 April 2016 - 06:32 AM

Thank you so much, that makes alot more sense!
Was This Post Helpful? 0
  • +
  • -

#6 bird13   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 27-March 16

Re: Need help on loop and on this program in general

Posted 19 April 2016 - 09:58 AM

So now I am getting an error below about the annualIncome <= part and I cannot figure out what it wants me to do. Do i need to change anything to float or? see below the error:

Traceback (most recent call last):
File "C:\Python33\Program9-Template.py", line 123, in <module>
main()
File "C:\Python33\Program9-Template.py", line 23, in main
lists()
File "C:\Python33\Program9-Template.py", line 67, in lists
if annualIncome <= 15930 + 4160 * (numofmem + 2):
TypeError: can only concatenate list (not "int") to list

I also need another function, so maybe if I add the formula for the poverty level somehow like below:
def lists():
    
    inFile = open('program9.txt', 'r')
    outFile= open('program9-outfile.txt', 'w')

    outFile.write(str("%12s %12s %15s" % ("Account #", "Income", "Members")))
    
    allIncome = []
    acctNum = []
    accountNum=[]
    annualIncome = []
    members = []
    numofmem=[]
    poverty=[]
    count = 0
    total = 0
    household = 0

    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
       print('The numbers of households included in the survey are',acctNum, format(annualIncome, '.2f'), members, sep=' ')
       print('')
       total += members
       household += annualIncome
       allIncome.append(annualIncome)
       numofmem.append(members)
       accountNum.append(acctNum)
       count += 1

       

       if annualIncome <= 15930 + 4160 * (numofmem + 2):
          poverty.append(0)   # add zero to the list if below threshold
       else:
         poverty.append(1) #..r add '1' if above


       outFile.write(str("%10d  %15.2f  %10d" % (acctNum, annualIncome, members)))


       
       lineRead = inFile.readline()    # Read next record
       outFile.write('-------------------------------------------------------')
       
    non_poverty_pct= sum(poverty) / len(poverty) * 100   #calculation of percentage non-poverty
 

    average_household = (avg(allIncome))

    outFile.write("Families above the average income of " + str(poverty(1) + ''))

    inFile.close()

    print('The total average household income is',format(average_household, '.2f'))
    print('The percentage of households that have incomes below the poverty level is',format(poverty(0),'.2f'))

    
      
  
    
    
    
def avg(income):

    return(sum(income)/len(income))

    


def povLevel(themembers):
     povertyLevel = 15730.00+ 4060.00 *((themembers) - 2)

Was This Post Helpful? 0
  • +
  • -

#7 andrewsw   User is offline

  • never lube your breaks
  • member icon

Reputation: 6829
  • View blog
  • Posts: 28,318
  • Joined: 12-December 12

Re: Need help on loop and on this program in general

Posted 19 April 2016 - 10:03 AM

Quote

File "C:\Python33\Program9-Template.py", line 67, in lists
if annualIncome <= 15930 + 4160 * (numofmem + 2):
TypeError: can only concatenate list (not "int") to list

numofmem is a list, 2 is an int, you cannot join/concatenate them together.

If numofmem should be an integer, as the name suggests, then you wouldn't be appending anything to it, numofmem.append(members).
Was This Post Helpful? 0
  • +
  • -

#8 bird13   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 27-March 16

Re: Need help on loop and on this program in general

Posted 19 April 2016 - 10:19 AM

Okay, but even if i change it to total which is not a list, like below, i get the same error:

This program will calculate households incomes, display the average and determine the percentage of households that are below the poverty level

The numbers of households included in the survey are 1042 12180.06 3

Traceback (most recent call last):
File "C:\Python33\Program9-Template.py", line 124, in <module>
main()
File "C:\Python33\Program9-Template.py", line 23, in main
lists()
File "C:\Python33\Program9-Template.py", line 66, in lists
if allIncome <= 15930 + 4160 * (total - 2):
TypeError: unorderable types: list() <= int()
Was This Post Helpful? 0
  • +
  • -

#9 andrewsw   User is offline

  • never lube your breaks
  • member icon

Reputation: 6829
  • View blog
  • Posts: 28,318
  • Joined: 12-December 12

Re: Need help on loop and on this program in general

Posted 19 April 2016 - 10:23 AM

Quote

File "C:\Python33\Program9-Template.py", line 66, in lists
if allIncome <= 15930 + 4160 * (total - 2):
TypeError: unorderable types: list() <= int()

That isn't the same error. allIncome is a list and you cannot compare it to an integer; the two cannot be put in order.
Was This Post Helpful? 0
  • +
  • -

#10 bird13   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 27-March 16

Re: Need help on loop and on this program in general

Posted 19 April 2016 - 10:27 AM

I see, i changed it to household and just calculated the annualIncome into household. That doesnt error out anymore, but not sure if that is correct. Now I am getting an error about the Families above the average income string. Im guessing because something with the list again.


Traceback (most recent call last):
File "C:\Python33\Program9-Template.py", line 125, in <module>
main()
File "C:\Python33\Program9-Template.py", line 23, in main
lists()
File "C:\Python33\Program9-Template.py", line 85, in lists
outFile.write("Families above the average income of " + str(poverty(1) + ''))
TypeError: 'list' object is not callable


def lists():
    
    inFile = open('program9.txt', 'r')
    outFile= open('program9-outfile.txt', 'w')

    outFile.write(str("%12s %12s %15s" % ("Account #", "Income", "Members")))
    
    allIncome = []
    acctNum = []
    accountNum=[]
    annualIncome = []
    members = []
    numofmem = []
    poverty = []
    count = 0
    total = 0
    household = 0
    

    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
       print('The numbers of households included in the survey are',acctNum, format(annualIncome, '.2f'), members, sep=' ')
       print('')
       total += members
       allIncome.append(annualIncome)
       household += annualIncome
       accountNum.append(acctNum)
       count += 1

       

       if household <= 15930 + 4160 * (total - 2):
          poverty.append(0)   # add zero to the list if below threshold
       else:
         poverty.append(1) #..r add '1' if above


       outFile.write(str("%10d  %15.2f  %10d" % (acctNum, annualIncome, members)))

Was This Post Helpful? 0
  • +
  • -

#11 andrewsw   User is offline

  • never lube your breaks
  • member icon

Reputation: 6829
  • View blog
  • Posts: 28,318
  • Joined: 12-December 12

Re: Need help on loop and on this program in general

Posted 19 April 2016 - 10:36 AM

Quote

TypeError: 'list' object is not callable

poverty(1) should be poverty[1]; it is not callable like a function, some_function().

You need to start looking up these errors and trying to understand them.
Was This Post Helpful? 0
  • +
  • -

#12 bird13   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 27-March 16

Re: Need help on loop and on this program in general

Posted 19 April 2016 - 10:37 AM

Aww okay, now its giving me an invalid string error: Do I need to put format in there somewhere? I didnt understand this part as I was advised to add it.

Traceback (most recent call last):
File "C:\Python33\Program9-Template.py", line 125, in <module>
main()
File "C:\Python33\Program9-Template.py", line 23, in main
lists()
File "C:\Python33\Program9-Template.py", line 85, in lists
outFile.write("Families above the average income of " + str(poverty[1] + ''))
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Was This Post Helpful? 0
  • +
  • -

#13 andrewsw   User is offline

  • never lube your breaks
  • member icon

Reputation: 6829
  • View blog
  • Posts: 28,318
  • Joined: 12-December 12

Re: Need help on loop and on this program in general

Posted 19 April 2016 - 10:39 AM

Quote

outFile.write("Families above the average income of " + str(poverty[1] + ''))
TypeError: unsupported operand type(s) for +: 'int' and 'str'

What do you think this is telling you?

You cannot add + an integer and a string. Which integer is it referring to?
Was This Post Helpful? 1
  • +
  • -

#14 bird13   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 27-March 16

Re: Need help on loop and on this program in general

Posted 19 April 2016 - 10:55 AM

Okay i think i fixed that part. I am getting a 0 for the percentage below. Do i need to add a counter in the if loop or do i need to take the 0 out and make two separate lists for below the poverty and above? :

print('The percentage of households that have incomes below the poverty level is',format(poverty[0],'.2f'))
Was This Post Helpful? 0
  • +
  • -

#15 bird13   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 27-March 16

Re: Need help on loop and on this program in general

Posted 19 April 2016 - 11:23 AM

I think i fixed that also, i just change it to append everything to the list. I am now having issues with the function called avg(income). I cannot figure out how to input or return the income.

def lists():
    
    inFile = open('program9.txt', 'r')
    outFile= open('program9-outfile.txt', 'w')

    outFile.write(str("%12s %12s %15s" % ("Account #", "Income", "Members")))
    
    allIncome = []
    acctNum = []
    accountNum=[]
    annualIncome = []
    members = []
    numofmem = []
    poverty = []
    count = 0
    total = 0
    household = 0
    

    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
       print('The numbers of households included in the survey are',acctNum, format(annualIncome, '.2f'), members, sep=' ')
       print('')
       total += members
       allIncome.append(annualIncome)
       household += annualIncome
       accountNum.append(acctNum)
       count += 1

       

       if household <= 15930 + 4160 * (total - 2):
          poverty.append(household)   # add zero to the list if below threshold
          outFile.write(str(poverty[0]))
          
       else:
         poverty.append(household) #..r add '1' if above
         outFile.write(str(poverty[1]))
     


       outFile.write(str("%10d  %15.2f  %10d" % (acctNum, annualIncome, members)))
       


       
       lineRead = inFile.readline()    # Read next record
       outFile.write('-------------------------------------------------------')
       
    non_poverty_pct= sum(poverty) / len(poverty) * 100   #calculation of percentage non-poverty
 

    average_household = (avg(allIncome))

    

    inFile.close()

    print('The total average household income is',format(average_household, '.2f'))
    print('The percentage of households that have incomes below the poverty level is',format(poverty[0],'.2f'))
    print('The percentage of households that have incomes above the poverty level is',format(poverty[1],'.2f'))

    
      
  
    
def avg(income):

   aver=sum(income)/len(income)

   return aver


error is :

The numbers of households included in the survey are 9101 67590.40 6

The total average household income is 41061.76
The percentage of households that have incomes below the poverty level is 12180.06
The percentage of households that have incomes above the poverty level is 25420.51
Traceback (most recent call last):
File "C:\Python33\Program9-Template.py", line 133, in <module>
main()
File "C:\Python33\Program9-Template.py", line 24, in main
avg(income)
NameError: name 'income' is not defined
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2