I have the following code:
prime_numbers = [number for number in range(2, 101)
if all(number % div != 0
for div in range(2, int(number**0.5) + 1))]
How would I add a print statement for number?
UPDATE:Thank you everyone who responded except of course the people who downvoted. This is obviously lousy code. I know that. It was a question a student asked and I wanted to provide a complete explanation. I believe, if you are going to use this code the best way to adjust it is as follows:
primes = []
[primes. Append(number)
for number in range(2, 101)
if all(number %
div != 0 for div in range(2, int(number**0.5) + 1))]
print(primes)
>Solution :
Technically since the truthiness of print(number) is False (print() returning None), you can enjoy it’s effect and use an or to get the result in the list still.
prime_numbers = [
print(number) or number
for number
in range(2, 101)
if all(
number % div != 0
for div
in range(2, int(number**0.5) + 1)
)
]
print(prime_numbers)
Giving you:
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
However, comprehensions are discouraged for side effects like this (at least by me). You might want to just use a more traditional for loop.
See also: Is it Pythonic to use list comprehensions for just side effects?