一个for循环,用于在不重复打印功能的情况下打印一次字典项



我是Python和Stackoverflow的新手,如果我的格式很糟糕,而且我不擅长enlish,我很抱歉。但我对这个代码有问题。

print('Displays prime numbers from 1 to N.')
n = int(input('Please enter a value of n: '))
for n in range(1, n + 1):
if n >= 1:
for i in range(2, n):
if (n % i) == 0:
break
else:
print('They are',n,end=' ')

代码运行时的结果如下:

Displays prime numbers from 1 to N.
Please enter a value of n:40
They are 1 They are 2 They are 3 They are 5 They are 7 They are 11 They are 13 They are 17 They are 19 They are 23 They are 29 They are 31 They are 37

但我想要这样:

Displays prime numbers from 1 to N.
Please enter a value of n:40
They are 1 2 3 5 7 11 13 17 19 23 29 31 37

如果您完全决定不在循环中多次使用print函数,则可以设置一个标志来确定是否打印前两个单词。像这样:

print('Displays prime numbers from 1 to N.')
n = int(input('Please enter a value of n: '))
first = 'They are '
for n in range(1, n + 1):
if n >= 1:
for i in range(2, n):
if (n % i) == 0:
break
else:
print(first + str(n), end=' ')
if len(first) > 0:
first = ''

以下解决方案可能会帮助您

print('Displays prime numbers from 1 to N.')
n = int(input('Please enter a value of n: '))
num = [] # Create empty list
for n in range(1, n + 1):
if n >= 1:
for i in range(2, n):
if (n % i) == 0:
break
else:
num.append(n)
# Write the print statement outside of the loop and use .join() function and for loop 
#to print each element of the list look like the output you have posted 
#
print('They are'," ".join(str(x) for x in num))

输出:

Displays prime numbers from 1 to N.
Please enter a value of n: 40
They are 1 2 3 5 7 11 13 17 19 23 29 31 37

相关内容

最新更新