程序重复执行三次后出现响应异常:附Python赌博游戏完整代码
Hey Patrick, let's break down why your script starts acting wonky after three executions and fix those issues for good.
First, Let's Identify the Root Causes
From looking at your code, there are a few key issues that are causing the "response异常" (unexpected behavior) you're seeing:
1. Floating-Point Precision Chaos
You're using a float to track currency, and 0.2 is a value that can't be represented perfectly in binary floating-point. After three deductions of 0.2, your currency variable won't be a clean 4.4 — it'll be something like 4.399999999999999. This tiny error can throw off logic checks later, making the program behave unpredictably.
2. No Handling for Invalid Inputs
If you type anything other than an uppercase Y, the script just loops back to the input prompt without any feedback. So if you accidentally type y (lowercase) or yes, it looks like the program is frozen — that's a common "unresponsive" trigger.
3. No Exit Path When You Choose to Stop
When you input N, the script doesn't break out of the while loop. It just keeps asking you to gamble forever, which definitely feels like an error.
Here's the Fixed Version of Your Code
I've addressed all the above issues and cleaned up the code a bit for readability:
from random import randint # Track currency in cents (integers!) to avoid floating-point errors # 5.0 USD = 500 cents currency = 500 while currency > 0: # Normalize input: strip spaces + convert to uppercase start = input("Do you wish to gamble? Y/N ").strip().upper() if start == "Y": # Deduct 20 cents (0.2 USD) for playing currency -= 20 # Roll three dice in one clean line dice_rolls = [randint(1, 6) for _ in range(3)] # Print each roll for roll in dice_rolls: print(roll) # Check for duplicates using a set (fewer elements = duplicates exist) if len(set(dice_rolls)) < 3: # Add 100 cents (1.0 USD) for winning currency += 100 print("You win...") # Show current balance in USD for clarity print(f"Current balance: {currency / 100:.2f} USD") elif start == "N": # Exit the loop and show final balance when user quits print(f"Thanks for playing! Final balance: {currency / 100:.2f} USD") break else: # Tell user they entered something invalid instead of silent looping print("Oops, invalid input! Please enter Y or N.")
What Changed & Why?
- Fixed floating-point errors: By using integers to track cents instead of floats for dollars, we eliminate all precision issues. We only convert back to dollars when displaying the balance.
- Input robustness:
.strip().upper()ensures the script recognizesy,Y,Y, etc., and gives clear feedback for invalid inputs. - Proper exit logic: Typing
Nnow ends the program gracefully instead of looping infinitely. - Cleaner code: Used list comprehensions for dice rolls and a set to check duplicates — this makes the code easier to read and maintain.
内容的提问来源于stack exchange,提问作者Patrick Cake

