【发布时间】:2016-01-16 06:11:57
【问题描述】:
首先,我是 Python 新手。我正在尝试使用模运算% 来确定一个数字,比如 167 是否是质数。
例如,
让167 % n = some value i
当167 % 1 和167 % 167 时,它应该返回0,对于range(2,166) 中的n,它应该给出167 % n 的余数。我遇到的问题是我试图在167 % n 为n = 1 ~ 167 打印余数,但不知道如何获取列表索引的值(应该是余数)。
所以,这就是我所拥有的:
L = [] #creates empty list
i=0 #initialize i?
for i in range(1, 168) :
if 167 % i == 0 :
print ("There is no remainder")
else :
167 % i == x # x should be the value of the remainder
L[i].append(x) #attempting to add x ... to the indices of a list.
print(L[x]) #print values of x.
如果我可以使用while循环就更好了,那应该会更清楚。因此,虽然 i 从 1 到 167 迭代,但它应该将结果 x 添加到列表的索引中,我想打印这些结果。
有什么推荐的吗?任何帮助表示赞赏!非常感谢。
【问题讨论】:
标签: python python-3.x while-loop