shell ValueError中的Python错误:基为10的int()的文本无效:

2024-04-25 03:31:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个程序。如果短火柴和长火柴混在一起。这个程序是要看看哪些匹配项将在短框中匹配。 这是我的代码:

import math
def q2():

    fin = open('input.txt','rt')
    fout = open('output.txt', 'wt')
    a= int(fin.readline().strip())
    b = [int(b) for b in str(a)]
    count = -1
    nMatches = b[0]
    width = b[1]
    heigth = b[2]
    length = width**2 + heigth**2
    length = length**(.5)
    while count <= nMatches:
        match = int(fin.readline().strip())
        count = count+ 1
        if match <= length:
            print('YES')
        else:
            print('NO')

这是输出:

^{pr2}$

谢谢你的帮助 fin的内容是: 534 三 4 5 6 7


Tags: 程序txtreadlinematchcountopenwidthlength
3条回答

我在这里做了很多假设,因为我不知道fin文件中有什么。这就是我认为你想做的: nMatches = 534是框中匹配的数目。 width = 3height = 4,这使得框的length为5

我假设fin文件中前3后的所有数字都是每个匹配项的长度。在

    from math import sqrt
    def q2():

    fin = open('text.txt','r')
    fout = open('output.txt', 'w')
    a = fin.readline().strip().split()
    b = [int(x) for x in a]
    nMatches = b[0]
    width = b[1]
    height = b[2]
    length = sqrt(width**2 + height**2)

    for match in b[3:]:

        if match <= length:
            print ('YES')
        else:
            print ('NO')

    q2()

这会将文件中的每个数字与框的长度进行比较。在

问题是你的循环数。为什么不使用while count < nMatches而不使用for i in range(nMatches)?因为循环计数是关闭的,所以读取的内容超过了文件的结尾,当您试图转换空字符串时,这将给出一个错误。在

看起来你想把一个空字符串转换成一个整数,但那是不可能的。 看看你的例外情况:。。。基数10:''<;这是一个空字符串。在

所以你读一行,去掉它,只剩下一个空字符串。这就产生了值误差

这里有一个stackoverflow答案(google上的1或2结果): ValueError: invalid literal for int() with base 10: ''

相关问题 更多 >