如何在for循环中将多个数字放在一行中

for i in range(2, 101):

if i > 1: # Prime numbers are greater than 1

    for j in range(2, i):

        if (i % j) == 0:

            print(i,"is a composite number")

            break

        else:

            print(i,"is a prime number")

程序运行如下:


2 is a prime number

3 is a prime number

4 is a composite number

5 is a prime number

6 is a composite number

7 is a prime number

8 is a composite number

9 is a composite number

10 is a composite number

...


我的问题是:我们如何将合数放在同一行而质数放在一行


换句话说,如何做这样的事情:


4,6... is all composite numbers



2,3,5... is all prime numbers


慕慕森
浏览 384回答 1
1回答

跃然一笑

您可以将它们存储在列表中:primes = []composites = []for i in range(2, 101):    if i > 1: # Prime numbers are greater than 1        for j in range(2, i):            if (i % j) == 0:                composites.append(i)                break        else:            primes.append(i)print("Composites: ", *composites)print("Primes: ", *primes)其中唯一花哨的部分是splat. 通过写 print("Composites: ", *composites)与*不带我们打印[]托架。给出:Composites:  4 6 8 9 10 12 14 15 16 18 20 21 22 24 25 26 27 28 30 32 33 34 35 36 38 39 40 42 44 45 46 48 49 50 51 52 54 55 56 57 58 60 62 63 64 65 66 68 69 70 72 74 75 76 77 78 80 81 82 84 85 86 87 88 90 91 92 93 94 95 96 98 99 100Primes:  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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python