如何修复判断列表中数字是否为质数的Python程序?
Hey there! Let's get your Prime Numbers Game working properly. The code you shared only has the initial welcome messages—we need to add three key components: user input handling, a prime-checking function, and logic to iterate through your list and report results.
Step 1: Complete the Input Collection
First, we need to safely gather 5 integers from the user and store them in a list. We'll add error handling to make sure the user enters valid numbers:
print("Hello User, this is the Prime Numbers Game!") print("You will be required to input 5 numbers, and the game will check which are primes.") # Initialize empty list to store user's numbers number_list = [] # Collect 5 valid integers from the user for i in range(5): while True: try: # Get input and convert to integer num = int(input(f"Enter number {i+1}: ")) number_list.append(num) break # Exit loop if input is valid except ValueError: print("Whoops, that's not a whole number. Please try again!")
Step 2: Build a Reliable Prime-Checking Function
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Here's an efficient function to check for primes:
def is_prime(n): # Numbers ≤ 1 are not primes if n <= 1: return False # 2 is the only even prime if n == 2: return True # All even numbers > 2 are not primes if n % 2 == 0: return False # Check odd divisors up to the square root of n (optimization) max_divisor = int(n**0.5) + 1 for d in range(3, max_divisor, 2): if n % d == 0: return False return True
Step 3: Iterate Through the List and Check Primes
Finally, loop through the stored numbers, use our function to check each one, and print the results:
# Check each number and display results print("\nHere's the verdict:") for num in number_list: if is_prime(num): print(f"✅ {num} is a prime number!") else: print(f"❌ {num} is NOT a prime number.")
Why Your Original Code Wasn't Working
Your initial code only printed welcome messages—there was no logic to collect user input, no way to check for primes, and no loop to process the list. This is why it seemed like nothing was happening after the opening text.
Bonus Tips
- If you want to let users input any number of values instead of exactly 5, you can modify the input loop to stop when the user enters a non-number or a specific keyword like "done".
- The prime-checking function is optimized to skip even numbers after checking 2, which makes it much faster for large values.
内容的提问来源于stack exchange,提问作者Oliver Belfort

