我对python还很陌生,并且已经在这个问题上挣扎了很长一段时间了。我不明白为什么我的代码会生成此错误消息,并突然在以下两种情况之间停止:
Traceback (most recent call last):
File "C:/...some path../Random_marks.py", line 70, in <module>
total_marks = int(total)
ValueError: invalid literal for int() with base 10: 'A\n'
据我所知,它永远不会进入
if
我的代码第66行中的语句(在下面用注释标记)。但我不明白为什么以及如何修复?变量total仅为字符串类型,因此
isalpha()
应该回来
True
. 但当我打印出来的时候,上面写着
False
不知为什么。
这是enitre代码,但问题只在while循环的底部。
from random import *
infile = open("Compb12-81test1.txt", "r")
outfile = open("Compb12-81test1_marks.txt", "w")
def alldone(done):
for i in done:
if i == 0:
return False
return True
def assign2m(marks,done,total):
extra = randint(0,5)
done[extra] = 1
while not alldone(done[0:6]):
mark = randint(0,2)
select = randint(0,5)
if total - mark >= 0 and done[select] == 0 and select != extra:
total -= mark
marks[select] = mark
done[select] = 1
return total
def assign5m(marks,done,total):
extra1 = randint(6,7)
extra2 = randint(8,9)
done[extra1] = 1
done[extra2] = 1
while not alldone(done[6:10]):
mark = randint(0,5)
select = randint(6,9)
if total - mark >= 0 and done[select] == 0 and select != extra1 and select != extra2:
total -= mark
marks[select] = mark
done[select] = 1
return total
def adjust(marks,total,questions):
for i in range(questions):
if total > 0:
if i < 6 and str(marks[i]).isdigit():
diff = 2 - marks[i]
if total - diff >= 0:
marks[i] = 2
total -= diff
else:
marks[i] += total
total = 0
elif i < 10 and str(marks[i]).isdigit():
diff = 5 - marks[i]
if total - diff >= 0:
marks[i] = 5
total -= diff
else:
marks[i] += total
total = 0
else:
break
questions = 10
total = str(infile.readline())
while total != '-1':
marks = [" "] * questions
done = [0] * questions
if total.isalpha(): # This is line 66
outfile.write("A," * (questions - 1))
outfile.write("A" + "\n")
else:
total_marks = int(total)
total = assign2m(marks,done,int(total))
if int(total) > 0:
total = assign5m(marks,done,int(total))
if int(total) > 0:
adjust(marks,int(total),questions)
total = str(infile.readline())
print(marks,total_marks)
print(total, type(total))
infile.close()
outfile.close()
这是我输入的TXT文件内容:
12
2
13
12
9
16
10
6
20
8
6
5
10
5
13
5
9
5
14
14
8
8
9
9
13
A
10
9
10
12
18
13
9
20
16
14
7
3
11
5
8
9
17
8
11
12
13
8
8
16
4
8
1
9
13
17
19
10
6
18
9
15
12
5
4
8
8
16
15
7
-1
读取字符时出现问题
'A'
。