Python打字测试程序错误计数异常求助:始终输出5
问题:打字测试程序错误次数总是显示5?
我是编程新手,为何错误次数总是显示5?即使输入正确,程序也总是输出5。无需关注time和matplotlib模块,我会在后续项目中使用,恳请帮忙解决此问题。
我的代码:
import random import time import matplotlib.pyplot print(" Welcome to type tester") words = ["running","kangroo","girrafe","banana","donkey"] word = random.choice(words) typed = 0 wrong = 0 while typed < 5: word_typed = input("type the word : "+word+". then press enter : ").lower typed += 1 if word_typed != word: wrong += 1 continue else: continue print(wrong)
问题原因与修复方法
- 核心问题:代码中
word_typed = input(...).lower少了一对括号。lower是字符串的方法,必须通过()调用才能返回转换为小写后的字符串;如果不加括号,word_typed存储的是方法对象本身,而不是输入的文本内容。方法对象和字符串word永远不相等,所以每次循环都会执行wrong += 1,循环5次后错误次数就固定为5。 - 修复代码:把
.lower改成.lower():
word_typed = input("type the word : "+word+". then press enter : ").lower()
- 额外优化:你的
else分支里的continue是多余的,可以直接删掉,不影响逻辑。
内容的提问来源于stack exchange,提问作者Mohan
相关产品推荐
相关产品推荐

