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()
优化说明
- 把
dice_roll_input的递归改成while True循环,避免递归深度问题,同时增加错误输入提示,提升用户体验 - 修正了拼写错误,让注释和提示文本更规范
- 核心的循环逻辑保持不变,依然能实现你需要的「重复执行直到点数大于1」的效果
内容的提问来源于stack exchange,提问作者Darko Zlatarek
相关产品推荐
相关产品推荐

