打印20个素数

2024-04-20 12:41:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我能生成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个数


Tags: andtheinfor数字betweenupperlower
3条回答

如果你所说的新行是指你的问题所在的跳转线 打印(num,end='')

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

打印将在每个打印数字后跳转一行

而不是:

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")

相关问题 更多 >