Printing Prime Numbers in Python
In an attempt to list prime numbers from 1 to 100, a Python user encountered an issue where the output displayed odd numbers instead of primes. To address this, we'll delve into the issue and provide a revised solution.
The initial code, as shown below, iterates over numbers from 1 to 100, and for each number, it checks if it is divisible by any number from 2 to itself:
<code class="python">for num in range(1, 101): for i in range(2, num): if num % i == 0: break else: print(num) break</code>
The problem with this approach lies in the nested loop's termination criteria. Once a number is found to be divisible by a factor i, the inner loop breaks and the print(num) statement is executed. However, the outer loop then starts checking the same number with the next value of i.
To resolve this, we need to update the loop to check divisibility by all numbers from 2 to the square root of num. If none of these divisors divides num, it is likely prime. The corrected code would be:
<code class="python">for num in range(2, 101): prime = True for i in range(2, int(num**0.5) + 1): if num % i == 0: prime = False break if prime: print(num)</code>
This solution efficiently detects prime numbers by iteratively checking divisibility by smaller factors. As a result, the output will accurately display the prime numbers from 1 to 100.
The above is the detailed content of How to Correctly Print Prime Numbers in Python: Resolving an Issue with Odd Output. For more information, please follow other related articles on the PHP Chinese website!