0

I need to create a program that imports annual rainfalls from an external file, assigns it to a variable, then in another function recalls that variable in order to calculate the average and total of the rainfalls.

The following is the code I tried and I keep getting an error saying that annualRainfall is not defined. Please help.

def main():


    inFile = open('program9.txt', 'r')

    lineRead = inFile.readline()       # Read first record
    while lineRead != '':              # While there are more records
       words = lineRead.split()        # Split the records into substrings
       annualRainfall = float(words[0])
       print(format(annualRainfall, '.2f'))

    lineRead = inFile.readline()    # Read next record


    # Close the file.
    inFile.close() # Close file



# Call the main function.
main()

def calculations():

    low=min(annualRainfall)
    high=max(annualRainfall)
    total=sum(annualRainfall)
    average=total/12.0

    print("The smallest amount of rainfall was",low,"in",
          "the month of")
    print("The largest amount of rainfall was",high,"in",
          "the month of")
    print("Total rainfall for the year was",total,"inches")
    print("Average rainfall for the year was",average,"inches")

calculations()
  • Possible duplicate of [Using global variables in a function](https://stackoverflow.com/questions/423379/using-global-variables-in-a-function) – Joseph Sible-Reinstate Monica Apr 19 '19 at 01:46
  • pass "annualRainfall" as an argument for your calculations() function in both definition and call, i.e. def calculations(annualRainfall):, and last line also calculations(annualRainfall), or recommended to change the one inside the def body of your function to other name to avoid misunderstanding while reading your code – Mahmoud Elshahat Apr 19 '19 at 01:48

0 Answers0