jeudi 29 novembre 2018

How to fix TypeError?

So I have thoutghly researched how to do this, but even then I am coming accross problems. It is one error after another. For example

Traceback (most recent call last):
  File "C:/Users/Owner.OWNER-PC/AppData/Local/Programs/Python/Python37-32/lab 5 maybe.py", line 41, in <module>
    main()
  File "C:/Users/Owner.OWNER-PC/AppData/Local/Programs/Python/Python37-32/lab 5 maybe.py", line 8, in main
    rand_gen(myfile)
  File "C:/Users/Owner.OWNER-PC/AppData/Local/Programs/Python/Python37-32/lab 5 maybe.py", line 19, in rand_gen
    my_file.write(line +'\n')
TypeError: unsupported operand type(s) for +: 'int' and 'str'

I get this error with this code. And I have no clue how to fix a type error. And I have been at this for what seems hours, and every change I make seems to create more of a problem. I have read through the book, and it has offered nothing. I get some things, but it is just not working for me at all. I have scoured the forums relentlessly. In the main it needs to ask the user to name the file to write into, which works. also needs to pass the argruments when the other functions are called either to write into the file or read from it. The second function, writes a series of random numbers to a file between 1-500 and also needs to ask how many random numbers to do, which works.(meaning it lets the user ask for the number) after that it gives the error. lastly, the third function need to show the amount of numbers that were generated, the sum of the numbers, and the average of numbers! Thank you in advance.

import random
import math


def main():
    myfile = str(input("Enter file name here "))
    with open(myfile, 'w+') as f:
        rand_gen(myfile)

    return f
    myfile.close

    disp_stats()

def rand_gen(myfile):
    my_file = open(myfile, 'w')
    for count in range(int(input('How many random numbers should we use?'))):
        line = random.randint(1,500)
        my_file.write(line +'\n')
    my_file.close()

def disp_stats():
    myfile = open(f,"r")
    total = 0
    count = 0
    print('The numbers are: ')
    for line in myfile:
        number = int(line)
        total += number
        count += 1
        print(number)

    average = total / count
    data = np.loadtxt(f)
    print('The count is ',count,)
    print('The sum is',total,)
    print('The average is ',format(average, '.2f'))

    myfile.close
main()




Aucun commentaire:

Enregistrer un commentaire