【发布时间】:2018-11-30 01:59:43
【问题描述】:
所以我仔细研究了如何做到这一点,但即便如此我还是遇到了问题。这是一个接一个的错误。例如
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'
我收到此代码的此错误。而且我不知道如何修复类型错误。而且我已经在这似乎几个小时了,我所做的每一个改变似乎都会产生更多的问题。我读过这本书,它什么也没提供。我得到了一些东西,但它根本不适合我。我无情地搜索了论坛。 主要是它需要让用户命名要写入的文件,这很有效。 当调用其他函数写入文件或从中读取时,还需要传递参数。 第二个函数,将一系列随机数写入 1-500 之间的文件,并且还需要询问要执行多少随机数,这是有效的。(意味着它让用户询问数字)之后它给出了错误。 最后,第三个函数需要显示生成的数字的数量、数字的总和以及数字的平均值!提前谢谢你。
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()
【问题讨论】:
标签: python function file random average