python - 程序随机重启
问题描述
我编写了这个小程序来生成单词,然后提示用户输入以键入单词。每隔一段时间,程序会在第 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,请使用以下任一方法(其中 i 是索引):
对于 i, e in enumerate(order):
您需要定义两个变量的地方,i 是索引,e 是元素。
或者:
对于范围内的 i (0, len(order)):
在哪里,您不需要使用 e,但它有点难以阅读,并且是一种不那么 Pythonic 的方法
推荐阅读
- python - 继承类的 __init__ 调用内部函数的类
- google-photos - 尝试获取 oauth2 访问令牌时出现“invalid_scope”
- visual-studio-code - Cpplint 找不到可执行文件
- javascript - cb=gapi.loaded_0:76 未捕获的 uO {消息:“无效的 cookiePolicy”
- python - 如何在 Python 的字符串列表中使用“.endswith”?
- html - 停止在桌面上制作大于原始尺寸的图像
- asp.net-core-signalr - 什么是默认的 Javascript SignalR 客户端身份验证方案?
- python - 如何在不和谐[Python]中制作随机输出命令
- firebase - Google Cloud Firestore - 如何显示整个文档的一部分
- java - 我的套接字应用程序停止工作 - 如何修复它?