我是一名新手学生并试图编写一个程序,将原始分数列表转换为字母等级列表。我需要循环,文件打开/关闭,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'
convertscore程序似乎可以自行运行,所以我很困惑。提前感谢您的帮助。
答案 0 :(得分: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
答案 1 :(得分:0)
默认情况下,Python将输入作为字符串,因此您需要将其转换为int 并且你需要从函数返回一些东西或者convertscore(line)将始终返回null。下面将在python 2.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)