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

Python新手求助:如何重复执行函数直到骰子点数大于1?

实现骰子重复投掷直到点数大于1的解决方案

你的代码其实已经正确实现了「重复执行直到骰子点数大于1」的逻辑——attack_python函数里的while dice == 1循环就是核心:只要骰子结果是1,就会重复执行输入验证、投掷骰子、结果判断的流程,直到掷出大于1的点数为止。

不过代码里有几个可以优化的细节,让它更健壮:

  • dice_roll_input用递归处理用户错误输入,多次错误输入可能触发Python的递归深度限制,换成循环更稳妥
  • 修正注释和提示文本里的拼写错误(Askes→Asks,more then→more than)

改进后的代码如下:

from random import randint


def dice_roll_input():
    '''
    Asks the user to type "roll" to run the function that
    simulates rolling the dice.
    '''
    print('Roll more than "1" to kill the python.\n')
    while True:
        dice_conf = input('Type "roll" to roll the dice\n')
        if dice_conf == 'roll':
            break
        print('Invalid input, please try again.\n')


def roll_dice():
    '''
    Simulates rolling the dice and returning the result.
    '''
    random_dice = randint(1,6)
    return random_dice


def kill_python(dice):
    '''
    Based on the dice roll, either python gets killed or
    it dodges the attack and user needs to roll again.
    '''
    if dice == 1:
        print(f'You rolled: {dice} \n')
        print('Python dodged your attack. Try again.\n')
    else:
        print(f'You rolled: {dice} \n')
        print('You killed the python!')


def attack_python():
    '''
    Function to loop through dice rolls until dice>1.
    '''
    dice = 1
    while dice == 1:
        dice_roll_input()
        dice = roll_dice()
        kill_python(dice)


def main():
    """
    Run all program functions
    """
    attack_python()
    

main()

优化说明

  1. 把dice_roll_input的递归改成while True循环,避免递归深度问题,同时增加错误输入提示,提升用户体验
  2. 修正了拼写错误,让注释和提示文本更规范
  3. 核心的循环逻辑保持不变,依然能实现你需要的「重复执行直到点数大于1」的效果

内容的提问来源于stack exchange,提问作者Darko Zlatarek

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 10:21:05