连续打印 20 个质数

Print 20 prime numbers in a row

我能够生成 1000 个素数,但无法在新行上打印这些数字

lower = 1
upper = 1000
print("The prime numbers between", lower, "and", upper, "are:")
for num in range(lower + 1, upper + 1):
  if (num % 2) != 0 and (num % 3) != 0:
    print(num,end='')
  elif num//2 == 1:
    print(num,end='')

我的项目是打印 0 到 1000 之间的质数,同时将 1000 个质数的列表分成每行 20 个数

如果新行是指您的问题所在的跳转线 打印(数字,结束='')

end = '' 表示您要在 num 变量后添加的内容,以修复添加 end = '\n'

每次打印num

后打印会跳行

而不是:

print(num,end='')

使用:

print(num,end='\n')

或者只是:

print(num) # Default end is '\n' 

注意:

print()

Definition and Usage The print() function prints the specified message to the screen, or other standard output device.

The message can be a string, or any other object, the object will be converted into a string before written to the screen.

Syntax:

print(object(s), separator=separator, end=end, file=file, flush=flush)

Parameter Values:

object(s) : Any object, and as many as you like. Will be converted to string before printed

sep : 'separator' (Optional) Specify how to separate the objects, if there is more than one. Default is ' '

end : 'end' (Optional) Specify what to print at the end. Default is '\n' (line feed)

file : (Optional) An object with a write method. Default is sys.stdout

flush : (Optional) A Boolean, specifying if the output is flushed (True) or buffered (False). Default is False

并不是所有的 素数 实际上都是 prime.
您需要在所需数字后附加一个换行符 (\n) 以在新行上打印它。
我还将 primescomposites 分开,例如:

lower, upper = 1, 1000
primes, composites = [], []

for number in range(lower + 1, upper + 1):
    for i in range(2, number):
        if (number % i) == 0:
            composites.append(number)
            break
    else:
        primes.append(number)

print("primes")
for prime in primes:
    print(prime,end='\n')

print("composites")
for composite in composites:
    print(composite,end='\n')

print("List of prime numbers: https://en.wikipedia.org/wiki/List_of_prime_numbers")