-2

私は初心者で、生のスコアのリストを文字の成績のリストに変換するプログラムを作成しようとしています。私の割り当ての基準には、ループ、ファイルのオープン/クローズ、if-elif-else ステートメント、および 2 つの関数が必要です。

テスト用に開いているファイルは次のようになります。

108
99
0
-1

これまでのプログラムは次のとおりです。

def convertscore(score):
    grade = ""
    if score >=101:
        print("Score is over 100%. Are you sure this is right?")
        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:
        print("Score cannot be less than zero.")
    else:
        print("Unable to convert score.")

print(grade)


def main():
    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
        print(convertscore(line), file=outfile)

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

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

main()

実行しようとすると、型エラーが発生します。

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'

convertcore プログラムはそれ自体で正常に動作するように見えるので、混乱しています。よろしくお願いいたします。

4

2 に答える 2

0

ファイルを開いて値を読み取る場合、値は 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
于 2017-10-15T17:08:05.900 に答える