一位学习 Python 的新手在编写一个叫做“Quizzer”的程序时遇到了问题。这个程序可以从术语和答案列表中随机生成问题。这位新手在编写生成问题函数时遇到了困难,这个函数需要生成四个选项,其中一个选项是正确的,而其他三个是随机选择的。为了确保选出的随机选项不是正确答案,而且彼此不同,他添加了几项检查。
这位新手在经过反复尝试后,终于让程序正常工作了。但是过了一段时间后,他再次测试程序时,又遇到了相同的错误信息。他尝试撤销所有更改,但仍然无法解决问题。经过几番折腾后,程序又开始正常工作了。但是,不久之后,它又停止工作了。
2、解决方案
经过对代码的分析,以下列出了导致问题的原因以及相应的解决方案:
-
**错误:**term_list = […]
-
**原因:**该语句将 term_list 变量定义为一个列表。
- 当用户输入与 term_list 长度相同的试题数量时,test_term = term_list 语句会将 term_list 变量赋值给 test_term 变量。
- 这意味着 test_term 和 term_list 变量指向相同的列表。
- 因此,对 test_term 变量的任何修改都会同时反映在 term_list 变量上,反之亦然。
- 可以通过创建一个新列表并将 term_list 的元素复制到这个新列表中,而不是直接将 term_list 赋值给 test_term,来避免这个问题。
-
**错误:**list_scrambler(unscrambled_list):
-
**原因:**该函数会修改 test_terms 列表。
- 当用户输入与 term_list 长度相同的试题数量时,test_term = term_list 语句会将 term_list 变量赋值给 test_term 变量。
- 这意味着 test_term 和 term_list 变量指向相同的列表。
- 因此,对 test_terms 变量的任何修改都会同时反映在 term_list 变量上,反之亦然。
- 可以通过创建一个新列表并将 term_list 的元素复制到这个新列表中,而不是直接将 term_list 赋值给 test_term,来避免这个问题。
代码示例
# 修复后的代码
def gen_test(amount=len(term_list)):
found_starter = False
test_terms = []
while found_starter == False:
#pick a random starting point in the terms to see if it is suitable
start_point = random.randint(1, len(term_list))
if amount == len(term_list):
#if user inputs max amount of questions possible, just take the term list
test_terms = term_list
found_starter = True
elif len(term_list) - (start_point + amount) >= 0:
#if it is suitable, then append the terms to the test questions
for x in xrange(start_point,start_point+amount):
test_terms.append(term_list[x])
found_starter = True
else:
return test_terms
def list_scrambler(unscrambled_list):
new_list = [] # Create a new list to store the scrambled terms
while unscrambled_list: # While there are still terms in the original list
transfer_var = random.randint(0, len(unscrambled_list)-1) # Get a random index
new_list.append(unscrambled_list[transfer_var]) # Add the term at that index to the new list
del unscrambled_list[transfer_var] # Delete the term from the original list
return new_list
# 以下代码保持不变
def gen_question(picked_term, question_num=1, total_amount=len(test_terms)):
...
通过以上解决方案,可以修复程序中出现的偶发性错误,确保它能够正常运行。