【发布时间】:2018-10-18 08:39:07
【问题描述】:
我的任务是随机分配具有名称和四个类别的卡片,然后将它们从文本文件中取出并将完成的卡片保存回另一个文本文件。随机卡片的数量取决于用户输入,但它只会在显示此错误之前循环几次。
line 35, in <module>
exercise = lines5[exerlinenum]
IndexError: list index out of range
这是我正在使用的代码。
x = 0
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
user = int(input("Please enter your even number: "))
if user % 2 == 0:
answer = list.index(user)
split_list = list[0:answer+1]
loop = len(split_list)
else:
print("Input not even!")
import random
while x < loop:
file = open("dognames.txt", "r")
lines1=file.readlines()
namelinenum=random.randint(0, 17)
dogname = lines1[namelinenum]
print("Name:", dogname)
file2 = open("friendliness.txt", "r")
lines2=file2.readlines()
frenlinenum=random.randint(0, 10)
friendliness = lines2[frenlinenum]
print("Friendliness:", friendliness)
file4 = open("intelligence.txt", "r")
lines4=file4.readlines()
intlinenum=random.randint(0, 100)
intelligence = lines4[intlinenum]
print("Intelligence:", intelligence)
file5 = open("exercise.txt", "r")
lines5=file5.readlines()
exerlinenum=random.randint(0, 5)
exercise = lines5[exerlinenum]
print("Exercise:", exercise)
file6 = open("drool.txt", "r")
lines6=file6.readlines()
droollinenum=random.randint(0, 10)
drool = lines6[droollinenum]
print("Drool:", drool)
doginfo=(dogname, friendliness, intelligence, exercise, drool)
file3 = open("dogs.txt", "a")
file3.write(repr(doginfo))
x += 1
file3.close()
这里是有问题的文本文件,如果有帮助的话。
dognames.txt
Jack
Harry
Lyla
Lucky
Ringo
Sadie
Pinkie
Teddy
Simrin
Andie
Willow
Luna
Bailey
Zoey
Checkers
Cheddar
Arlo
Humphrey
友好性.txt
1
2
3
4
5
6
7
8
9
10
智能.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
练习.txt
1
2
3
4
5
流口水.txt
1
2
3
4
5
6
7
8
9
10
非常感谢,请对我放轻松。我是初学者。
【问题讨论】:
-
生成一个随机数 n 以读取仅包含数字 n 的文本文件的第 n 行有什么意义?我不清楚这其中的逻辑。
-
如果你想学习如何写更多地道的python,请发帖codereview.stackexchange.com,你可以做得更好,我相信那里的人会给你一个很好的解释
-
@chris - 直到它正常工作。 Code Review 不喜欢看到已知损坏的代码。
-
@TobySpeight 如果不是很明显这是分开的,假设他先听了下面的答案