用Python打印一个数的因子
我想在Python中打印出数字20的因数,结果应该是这样:
20
10
5
4
2
1
我知道这个问题很简单,但我对我尝试的某些细节有些疑问。如果我这样写:
def factors(n):
i = n
while i < 0:
if n % i == 0:
print(i)
i-= 1
这样做的时候,它只打印出20。我觉得在把i设为n,然后让i减小的时候,可能也影响到了n,这个是怎么回事呢?
还有,我知道其实可以用for循环来做,但我只会让它反向打印因数,结果是:1, 2, 5, 10……
另外,我需要用迭代的方式来完成这个。能帮帮我吗?
注意:这不是作业问题,我只是想自己重新学习Python,因为有一段时间没碰了,所以在这个问题上卡住我觉得挺尴尬的 :(
3 个回答
0
希望我的回答能帮到你!
#The "while True" program allows Python to reject any string or characters
while True:
try:
num = int(input("Enter a number and I'll test it for a prime value: "))
except ValueError:
print("Sorry, I didn't get that.")
continue
else:
break
#The factor of any number contains 1 so 1 is in the list by default.
fact = [1]
#since y is 0 and the next possible factor is 2, x will start from 2.
#num % x allows Python to see if the number is divisible by x
for y in range(num):
x = y + 2
if num % x is 0:
fact.append(x)
#Lastly you can choose to print the list
print("The factors of %s are %s" % (num, fact))
0
这里的意思是,while循环的条件应该写成 i > 0
,而不是 i < 0
。因为如果你把条件写成 i < 0
,那这个条件永远不会成立,因为i一开始是20(在其他情况下可能更大)。
1
while i < 0:
这个一开始就会是假的,因为i
一开始是正数,假设是这样。你想要的是:
while i > 0:
用简单的话说,你想要“把i
的初始值设为n
,然后在它大于0的时候不断减小,同时在每一步检查一下是否是因数”。
>>> def factors(n):
... i = n
... while i > 0: # <--
... if n % i == 0:
... print(i)
... i-= 1
...
>>> factors(20)
20
10
5
4
2
1