You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

满足while循环条件时递归仍触发?Python测验程序问题求助

解决Python随机测验程序循环无法终止的问题

你的代码核心问题在于递归调用quiz()导致的多层循环嵌套,以及全局变量Number的混乱逻辑。当抽到重复题目时,递归调用会开启新的函数执行上下文,而原外层的while循环并未终止;当内层递归把Number加到10后,外层循环仍会继续运行,最终出现"提问满10题后程序不停止"的情况。

下面提供两种简洁的修复方案:

方法一:用random.sample直接生成不重复随机索引(推荐)

这是最简洁高效的实现方式,一次性生成10个不重复的随机索引,彻底避免重复判断和递归的混乱:

import random

questions = [
    "Python is a coding language \n [1] True \n [2] False",
    "There are this many coding languages \n [1] 5 \n [2] 3 \n [3] 17 \n [4] Over 500 \n",
    "question 3", "question 4", "question 5",
    "question 6", "question 7", "question 8", "question 9", "question 10"
]

answers = ["1", "1", "1", "1", "1", "1", "1", "1", "1", "1"]

def quiz():
    # 生成10个不重复的随机索引,范围0-9
    random_indices = random.sample(range(10), 10)
    score = 0
    for idx in random_indices:
        print(questions[idx])
        user_answer = input("请输入答案:")
        if user_answer == answers[idx]:
            print("correct")
            score += 1
        else:
            print("wrong")
    print(f"测验结束,你的得分:{score}/10")

quiz()

方法二:修复原代码的递归与逻辑问题

如果想保留原有思路,可去掉递归,改用简单的重复判断,并将全局变量改为局部变量避免上下文混乱:

import random

questions = [
    "Python is a coding language \n [1] True \n [2] False",
    "There are this many coding languages \n [1] 5 \n [2] 3 \n [3] 17 \n [4] Over 500 \n",
    "question 3", "question 4", "question 5",
    "question 6", "question 7", "question 8", "question 9", "question 10"
]

answers = ["1", "1", "1", "1", "1", "1", "1", "1", "1", "1"]

def quiz():
    asked_questions = []
    number = 0
    score = 0
    while number != 10:
        randomnumber = random.randint(0,9)
        # 直接判断题目是否已被提问
        if randomnumber not in asked_questions:
            asked_questions.append(randomnumber)
            print(questions[randomnumber])
            answer = input("")
            number += 1
            if answer == answers[randomnumber]:
                print("correct")
                score += 1
            else:
                print("wrong")
    print(f"测验结束,你的得分:{score}/10")

quiz()

关键修复点说明:

  • 移除递归调用,改用in操作符直接判断题目是否重复,逻辑更清晰
  • 将全局变量改为函数内部局部变量,避免多层函数上下文导致的变量值混乱
  • 新增得分统计功能,增强程序实用性

内容的提问来源于stack exchange,提问作者Thyme Travler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 00:20:32