Python Craps游戏输出异常求助:无法得到预期结果
Python Craps游戏输出异常问题修复
问题根源分析
- 骰子范围错误:
rollDice函数中random.randint(1,7)会生成1-7的数,而标准骰子是1-6,应改为random.randint(1,6)。 - 条件判断逻辑错误:
- 整数
sum与字符串(如'2')比较,永远不相等,导致胜负判断完全错误; - 逻辑或写法错误,
if sum == '2' or '3' or '12'等价于if (sum == '2') or True or True,永远为真,正确写法应为sum == 2 or sum == 3 or sum == 12。
- 整数
- 重复调用函数导致重复输出:
determine_win_or_lose中多次调用determinePointValueResult(sum),每次调用都会重新掷骰子并输出;- 主循环中三次调用
determine_win_or_lose(x,y),导致同一局游戏重复执行三次,产生重复输出。
determinePointValueResult逻辑错误:- 初始
sum等于传入的point,循环条件sum !=7 and sum !=point不成立,直接跳过循环; - 判断
sum == '7'使用字符串,应改为整数7。
- 初始
修正后的代码
import random def rollDice(): roll_1 = random.randint(1, 6) # 修正骰子范围为1-6 roll_2 = random.randint(1, 6) return roll_1, roll_2 def determine_win_or_lose(dice1, dice2): sum_dice = dice1 + dice2 print(f"You rolled {dice1} + {dice2} = {sum_dice}") # 修正条件判断:使用整数比较,正确逻辑或写法 if sum_dice == 2 or sum_dice == 3 or sum_dice == 12: return 0 elif sum_dice == 7 or sum_dice == 11: return 1 else: print(f"Point is {sum_dice}") # 仅调用一次函数并保存结果,避免重复掷骰 result = determinePointValueResult(sum_dice) return result def determinePointValueResult(point): while True: x, y = rollDice() sum_dice = x + y print(f"You rolled {x} + {y} = {sum_dice}") if sum_dice == point: return 1 elif sum_dice == 7: return 0 #==== MAIN ===== win = 0 lose = 0 game = int(input("How many games do you want to play > ")) for i in range(game): x, y = rollDice() # 仅调用一次函数并保存结果,避免重复执行 game_result = determine_win_or_lose(x, y) if game_result == 1: print("You win") win += 1 elif game_result == 0: print("You lose") lose += 1 print(f"Game results: {win} wins and {lose} losses")
修正说明
- 重命名
sum为sum_dice,避免与内置函数sum冲突; - 使用f-string简化输出格式,更易读;
determinePointValueResult改为无限循环,直到掷出point或7,逻辑更清晰;- 所有函数仅调用一次并保存结果,彻底解决重复输出问题;
- 修正所有类型匹配问题,确保整数与整数比较。
内容的提问来源于stack exchange,提问作者Songline
相关产品推荐
相关产品推荐

