我读到有关“随机”的信息,这使我开始考虑通过制作一个显示单词并需要输入单词的程序来帮助我的孩子进行读写。因为这是一个小程序,所以我可以很容易地通过过程编程来做到这一点,但是为了使其对她更具“吸引力”,我决定不妨使用tkinter。
Tkinter强制创建可以通过“命令”调用的函数,但是现在我遇到了问题。如果运行check()函数,它将无法从dictee()函数获取变量。我从将函数嵌套在函数中(未定义的变量问题),或通过带有return的参数传递(以递归结束),使用全局(单词列表不会为空)等方式找到了几个答案。我无法获得他们中的任何一个都在工作...我一直在寻找答案,但我找不到正确的解决方案。
谢谢!
"""import nescessary."""
import sys
import random
def main():
"""Setting up the game"""
print("Aliyahs reading game.'\n")
begin = input("do you want to start? yes or no.\n\n")
if begin == "yes":
dictee()
def dictee():
"""Show random words and ask for input."""
words_correct = 0
words_wrong = 0
vocabulary = ['kip', 'hok', 'bal', 'muis', 'gat'
]
words_passed = []
while True:
if vocabulary == []:
print("\n\nThose were all the words.")
print("Words correct: %d" % words_correct)
print("words wrong: %d" % words_wrong)
one_more_time = input("Do you want to go again? yes or no")
if one_more_time == "no":
print("See you next time.")
input("\nPush enter to close.")
sys.exit()
else:
main()
word = random.choice(vocabulary)
print('\x1b[2J')
print("{}".format(word))
print("\n\n")
words_passed.append("{}".format(word))
vocabulary.remove("{}".format(word))
answer = input("Write the word you saw:\n\n")
check()
def check():
'''Cross check word shown with answer given'''
if answer == word:
print("Nice")
words_correct += 1
else:
print("2bad")
words_wrong += 1
try_again = input("\n\nContinue? yes or no\n ")
if try_again.lower() == "no":
exit_game()
else:
dictee()
def exit_game():
'''summarize results and exit after pushing enter'''
print("Words correct: %d" % words_correct)
print("Words wrong: %d" % words_wrong)
input("\nPress Enter to exit.")
sys.exit()
if __name__ == "__main__":
main()
香港专业教育学院只是在这里做了一些更改,并运行它并没有出现错误,因为我不知道如何键入才能得到正确的结果。无论如何,所有更改都与global
值相关并重新定义。
# say these outside all the functions, in the main block
words_correct = 0
words_wrong = 0
vocabulary = ['kip', 'hok', 'bal', 'muis', 'gat']
words_passed = []
def dictee():
global word, answer
..... #same bunch of codes
def check():
global answer, words_correct, words_wrong
.... #same bunch of codes
我们为什么要说global
?基本上是因为当我们定义变量时,它们要么在局部范围内定义,要么在全局范围内定义,所以在主块(所有功能之外)定义的变量在全局范围内,而内部功能块在局部范围内。在全局范围内定义的变量可以在任何地方访问,而在本地范围内的变量只能在其定义的内部访问。
我们必须在哪里使用global
?我们说的是全局变量,定义变量或重新定义变量,或者至少这是我所知道的。我们需要说出global
声明变量的位置,例如,a = 'good'
还需要说说global
是否要更改它,a = 'bad'
或者a += 'day'
是因为要给它赋一个新值。在主块上使用所有函数之外的全局变量是没有用的。
我们为什么要申报words_correct
和words_wrong
以外的所有功能?这是因为如果您在内部声明并将其值设置为0 dictee()
,则每次运行该函数时,这些变量的值都将更改为0,这意味着score始终为0或1,因此我们只在其中定义一次主块。相同的逻辑适用于两个list(vocabulary
和words_passed
),每次函数运行时,它们都会将列表重置为完整的单词列表,因此,要消除该问题,只需在主块中对其进行一次定义。
我还认为,在这里使用参数可能需要重新构造代码,因为您需要相互调用这两个函数。
请注意,我们仅global
在函数上说,在外部函数中,所有定义的变量都对全局范围开放,并且可以从代码中的任何位置进行访问。
PS:这只是我对4个月跨度的了解,如果我在任何地方都做错了,请纠正我,谢谢:D
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句