【问题标题】:How to fix TypeError?如何修复类型错误?
【发布时间】: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


    【解决方案1】:

    当您遇到回溯错误时,请查看最后一行以查看顶级错误原因。

    my_file.write(line +'\n') & TypeError: unsupported operand type(s) for +: 'int' and 'str'

    显然它暗示了line +'\n'这个表达式

    +operator 期望两个参数的类型相同。(它找不到任何采用 int 和字符串的重载函数定义。

    这是因为 line 是一个整数(由 randint 生成),而 '\n' 是一个字符串。

    所以将行类型转换为字符串 line -&gt; str(line).

    新的正确行应该是 my_file.write(str(line) +'\n')

    【讨论】:

      【解决方案2】:

      正如错误消息所解释的那样,TypeError: unsupported operand type(s) for +: 'int' and 'str'。您不能连接“整数”(line,即 random.randint(1,500) 与“字符串”'\n'

      您可以执行以下操作:

      my_file.write(str(line) +'\n')
      

      【讨论】:

        猜你喜欢
        • 2018-07-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-29
        • 1970-01-01
        • 1970-01-01
        • 2019-03-18
        • 2019-10-12
        相关资源
        最近更新 更多