Python如何随机调用列表内函数?输出[None, None, None]是何原因
问题说明
- 你写
questions = [a(), b(), c()]时,函数名后加圆括号会让Python立刻执行这三个函数,而不是把函数存到列表里等待后续调用——这就是你没看到随机效果、程序一运行就按固定顺序把三道题全出了的原因。 - Python中如果函数没有用
return语句指定返回值,执行完后会默认返回None。你定义的a、b、c三个函数都只有打印操作、没有返回值,所以三个函数执行完后,questions列表里存的就是三个None,最后调用random.sample抽样再打印,自然就输出了[None, None, None]。
修正方案
最小改动版本
只需要调整两处:一是存题目列表时去掉函数后的括号,把函数对象本身存入列表;二是拿到随机排序的题目序列后,再逐个调用执行函数。
import random print("Here are some questions for you, answer true or false.") input("Press 'Enter' if you would like to continue.") def a(): answer = input("1) not False: ") print("Correct!") if answer == 'true' else print("Wrong!") def b(): answer = input("2) not True: ") print("Correct!") if answer == "false" else print ("Wrong!") def c(): answer = input("3) True or False: ") print("Correct!") if answer == "true" else print ("Wrong!") # 注意这里去掉了函数后的括号,不立刻执行函数 questions = [a, b, c] # 随机打乱题目顺序 random_questions = random.sample(questions, len(questions)) # 逐个调用题目函数 for q in random_questions: q()
注意:这个版本里题号是写死在每个函数里的,打乱顺序后显示的题号和实际出题顺序不匹配,适合题量少的时候临时用。
易维护版本(推荐)
不用为每道题单独写函数,把题目内容、正确答案统一存在列表里,后续加新题只要往列表里加元素就行,还能自动按出题顺序生成题号,不会出现序号错乱的问题:
import random print("Here are some questions for you, answer true or false.") input("Press 'Enter' if you would like to continue.") # 题库:每一项是(题目描述, 正确答案),加新题直接往这里追加即可 question_bank = [ ("not False", "true"), ("not True", "false"), ("True or False", "true"), # 后续加题直接往下补,比如: # ("True and False", "false"), # ("True and True", "true"), ] # 随机打乱题库顺序 random.shuffle(question_bank) # 遍历出题,自动生成连续序号 for index, (q_text, correct_ans) in enumerate(question_bank, start=1): user_ans = input(f"{index}) {q_text}: ").strip() print("Correct!") if user_ans == correct_ans else print("Wrong!")
内容的提问来源于stack exchange,提问作者rumblingThunder
相关产品推荐
相关产品推荐

