首页 > 解决方案 > 程序随机重启

问题描述

我编写了这个小程序来生成单词,然后提示用户输入以键入单词。每隔一段时间,程序会在第 22 行的循环中随机提示用户输入第 7 行(屏幕截图)的输入。知道为什么会发生这种情况吗?

这是我的代码,word_list 是另一个 python 文件,其中包含一个名为 words 的列表中的单词。

随机提示用户输入

from word_list import words
import random
import time

order = []

rand = input('random words? y/n ')
if rand == 'y':
    i = 0
    while i < len(words):
        i = random.randint(1, len(words))
        if i not in order:
            order.append(i)
            i += 1
elif rand == 'n':
    order = [i for i in range(len(words))]

start = time.perf_counter()

word_count = words_wrong = words_correct = 0
word = ''
for i in order:
    attempt = 0
    if word == '0':
        break
    while word != words[i] and word != '0':
        attempt += 1
        print(words[i])
        word = input()
        print('-'*20)
    if attempt == 1:
        words_correct += 1
    else: 
        words_wrong += 1
    word_count += 1

stop = time.perf_counter()
total_time = (stop - start) / 60

print('======= Stats =======')
print('Total words:      {}'.format(word_count))
print('Total errors:     {}'.format(words_wrong))
print('Accuracy:         {:.3f}'.format(words_correct/ word_count))
print('Total time:       {:.3f}'.format(total_time) + ' miutes')
print('Words per Minute: {:.3f}'.format(words_correct/total_time))

标签: python

解决方案


如果您想通过这样的索引器循环遍历 python,请使用以下任一方法(其中 i 是索引):

对于 i, e in enumerate(order):

您需要定义两个变量的地方,i 是索引,e 是元素。

或者:

对于范围内的 i (0, len(order)):

在哪里,您不需要使用 e,但它有点难以阅读,并且是一种不那么 Pythonic 的方法


推荐阅读