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

如何在Python的while循环中每执行指定次数调用一次函数?

实现每N次循环触发特定操作(退出询问)

当然可以实现这个需求!核心思路是用一个计数器追踪循环执行的次数,当次数达到你设定的阈值(比如10次)时,再触发退出询问的逻辑。我帮你调整了代码,同时修正了原代码里的几个小问题:

关键修改点

  • 新增loop_count计数器变量,每次循环递增,通过loop_count % 10 == 0判断是否达到10次循环
  • 修正了索引越界问题:原代码的random.randint(1,30)会访问超出列表长度的索引,改成动态获取列表长度更稳妥
  • 避免使用exit作为变量名(会覆盖Python内置函数),换成exit_choice
  • 忽略答案的大小写,提升用户体验
  • 移除了原代码中多余的for循环(它会重复询问4次退出,不符合你的需求)

修改后的完整代码

import random

print("Welcome to Latin Learner v1")
wordtype = raw_input("What would you like to learn (nouns verbs everything)? ")

if wordtype == "nouns":
    declension = raw_input("Declension 1-5? ")
    if declension == "1":
        exit_choice = "no"
        loop_count = 0
        # 提前定义列表,避免每次循环重复创建
        noun1L = ["ancilla","aqua","cena","copiae","cura","dea","domina","epistula","femina","filia","hora","ianua","insula","ira","nauta","patria","pecunia","poena","porta","puella","regina","Roma","silva","taberna","terra","turba","via","victoria","villa","vita"]
        noun1E = ["slave-girl or slave-woman","water","dinner or meal","forces or troops","care or worry","goddess","mistress","letter","woman","daughter","hour","door","island or block of flats","anger","sailor","country or homeland","money","punishment","gate","girl","queen","Rome","wood","shop or inn","ground or land or country","crowd","street or road or way","victory","house or country villa","life"]
        
        while "no" in exit_choice:
            loop_count += 1
            # 生成0到列表最后一个索引的随机数,避免越界
            wordno = random.randint(0, len(noun1L)-1)
            answer = raw_input(f"What's the English for '{noun1L[wordno]}'? ")
            
            # 忽略大小写比较答案
            if noun1E[wordno].lower() == answer.lower():
                print("Correct! 🎉")
            else:
                print(f"Incorrect. The right answer is: {noun1E[wordno]}")
            
            # 每10次循环才询问是否退出
            if loop_count % 10 == 0:
                exit_choice = raw_input("\nWould you like to quit? (yes/no) ").lower()
            else:
                # 未到次数时,默认继续循环
                exit_choice = "no"

额外说明

如果你想改成每5次循环就询问退出,只需要把loop_count % 10 == 0改成loop_count % 5 == 0即可,非常灵活。

内容的提问来源于stack exchange,提问作者lord septomus

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:21:20