为什么会出现这种类型的错误?TypeError:“str”和“int”的实例之间不支持“>=”

2024-10-03 11:18:42 发布

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

我是一个新手学生,正在尝试编写一个程序,将原始分数列表转换为字母等级列表。我需要循环、文件打开/关闭、if elif else语句和2个函数作为赋值条件。在

我要打开进行测试的文件如下所示:

108
99
0
-1

以下是目前为止的计划:

^{pr2}$

如果我尝试运行它,我会得到一个类型错误:

Traceback (most recent call last):
  File "/Users/xxxx/Documents/convertscore.py", line 54, in <module>
main()
  File "/Users/xxxx/Documents/convertscore.py", line 45, in main
    print(convertscore(line), file=outfile)
  File "/Users/xxxx/Documents/convertscore.py", line 10, in convertscore
    if score >=101:
TypeError: '>=' not supported between instances of 'str' and 'int'

convertscore程序本身似乎可以正常工作,所以我很困惑。提前谢谢你的帮助。在


Tags: 文件inpy程序列表ifmainline
2条回答

默认情况下,Python将输入作为字符串,因此需要将其转换为int 您需要从函数中返回一些内容,否则convertscore(line)将始终返回null。下面将在Python2.7中使用。请检查一下

def convertscore(score):
    grade = ""
    if score >=101:
        grade = "Score is over 100%. Are you sure this is right? \n"
        grade += "A"
    elif score >=90:
        grade = "A"
    elif score >=80 <=89:
        grade = "B"
    elif score >=70 <=79:
        grade = "C"
    elif score >= 60 <=69:
        grade = "D"
    elif score >=0 <=59:
        grade = "F"
    elif score < 0:
        grade = "Score cannot be less than zero."
    else:
        grade = "Unable to convert score."

    return grade


print("This program creates a file of letter grades from a file of scores on a 100-point scale.")
#print()

    #get the file names
infileName = input("What file are the raw scores in? ")
outfileName = input("What file should the letter grades go in? ")

    #open the files
infile = open(infileName, 'r')
outfile = open(outfileName, 'w')

    #process each line of the output file
for line in infile:
        #write to output file
    outfile.write(convertscore(int(line)))
    outfile.write("\n")

    #close both files
infile.close()
outfile.close()

#print()
print("Letter grades were saved to", outfileName)

打开文件并读入值时,它们的类型(或类)为str,因此需要将它们转换为int或float来进行数学检查。在

>>> prompt = 'What...is the airspeed velocity of an unladen swallow?\n'
>>> speed = input(prompt)
What...is the airspeed velocity of an unladen swallow?
17
>>> type(speed)
<class str>
>>> speed = int(speed)
17
>>> int(speed) + 5
22

相关问题 更多 >