对于使用List的函数内部循环:不迭代

时间:2013-06-05 00:56:38

标签: python for-loop python-3.x iteration

你好:)在我在python 3中创建的打字练习程序中,我有一个for ...循环,它从一个特定段落字符的全局列表中获取字符,并将其与用户键入的字符进行比较。 出于某种原因,for循环不会迭代,也不会继续下一个字符。经过一些研究,我发现你必须使用局部变量才能做到这一点,但这也不起作用。这是我的代码:

import random
from tkinter import *
root=Tk()
a_var = StringVar()
words = []
eachword = []
global eachchar
charlist = []
x=random.randint(0,10)

def typingpractice():
    realcharlist = []
    something = []
    paralist = []
    #x=random.randint(0,10)
    file = open("groupproject.txt")
    line = file.readline()
    paraWords = []
    for line in file:
        newline = line.replace("\n","")
        paralist.append(line.replace("\n", ""))
        paraWords.append(newline.split(" "))
    wordList = []
    for c in paraWords[x]:
        charlist.append(c)
    for b in range(0,len(charlist)):
        wordList.append(charlist[b])
        #print (wordList)
        for p in charlist[b]:
            realcharlist.append(p)
    #print(realcharlist)
    a=Canvas(root, width=500, height=500)
    a.pack()
    a.create_text(250,50, text = "Typing Fun", width = 500, font = "Verdana", fill = "purple")
    a.create_text(250,300, text = paralist[x], width = 500, font = "Times", fill = "purple")  
    a = Entry(root, width = 100)
    a.pack()
    a.focus_set()
    a["textvariable"] = a_var


    def compare(s, realcharlist):         
        for g in realcharlist:
            print ("s:",s)
            print ("g:",g)            
            if s == g:
                print ("y")
                a['fg'] = 'green'
                break
            else:
                print ("n")
                a['fg'] = 'red'
                break

    def callback(*args):
        global s
       # print ("b:",xcount)
        s = a.get()
        s = s[-1:]
        compare(s, realcharlist)

    a_var.trace_variable("w", callback) #CALL WHEN VARIABLE IS WRITTEN


def practicetest():
    print ("nothing here yet")

b = Button(root, text="Start Practice", command=typingpractice)
b.pack()

d = Button(root, text="Test", command=practicetest)
d.pack()

root.mainloop()

文本文件“groupproject.txt”是一个包含10个单行段落的外部文本文件,每个段落的每个字符都与用户输入的内容进行比较。

任何有关如何使for循环工作的帮助将不胜感激。谢谢:D

1 个答案:

答案 0 :(得分:0)

基本上发生的事情是for循环中断了所以它总是从0开始迭代自己。