Python连续质数生成脚本故障排查:从3开始后陷入无限循环无法生成下一个质数
Let's break down the issues in your code step by step:
1. Count Gets Reset Every Loop
The biggest problem is that you initialize count = 3 inside the while True loop. That means every time the loop repeats, count goes back to 3—so even when you increment it after the user inputs "Yes", the next iteration resets it to 3 again. That's why you can't get past the number 3.
2. Incorrect Prime Checking Logic
Your current prime check only tests the first divisor (2) and makes a decision immediately. For example:
- For 9, since 9%2=1 (not 0), your code would incorrectly print "9 is a prime number" and break, without checking if 3 divides it.
- Also, for 3, the code should print "3 is a prime number" (since 3%2=1), so your mention of it printing "3 is not a prime number" might be a typo, but regardless, the logic is flawed.
3. Unused game_on Variable
You set game_on = True at the start and game_on = False at the end, but this variable isn't used anywhere in your loop condition or logic. It's unnecessary and can be removed.
Corrected Code
Here's a fixed version of your script that works as intended:
def prime_number(): count = 3 # Initialize count outside the while loop so it persists while True: is_prime = True # Check divisibility from 2 up to the square root of count (inclusive) for num in range(2, int(count ** 0.5) + 1): if count % num == 0: is_prime = False break if is_prime: print(f'{count} is a prime number') # Ask user only after finding a prime question = input("Would you like to see another prime number? Please enter Yes or No: ").strip().lower() if question != "yes": break # Move to next number regardless of whether current count was prime count += 1 prime_number()
Key Improvements:
- Persistent Count:
countis initialized outside thewhileloop, so it keeps incrementing instead of resetting. - Proper Prime Check: We test all divisors from 2 up to the square root of
count(since factors larger than the square root would have corresponding factors smaller than it). If any divisor dividescount, it's not prime. - User-Friendly Input: We convert the input to lowercase and strip whitespace, so responses like "yes", "YES", or " Yes " all work.
- Only Ask After Prime: We only prompt the user when we've found and printed a prime number, which aligns with your desired flow.
How It Works:
- Starts checking from 3.
- For each number, checks if it's prime by testing divisibility up to its square root.
- If it's prime, prints it and asks the user if they want another.
- If the user says "Yes", increments
countand continues checking for the next prime. - If the user says anything else, exits the loop.
内容的提问来源于stack exchange,提问作者paddyusa

