繁体   English   中英

在python中打印数字的因子

[英]print factors of a number in 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循环来完成的,但是当我使用for循环时,我只能弄清楚如何向后打印因子,这样我就可以得到:1、2、5、10 ...我也需要仅使用迭代即可做到这一点。 救命?

注意:这不是我要自己重新学习python的作业问题,因为已经有一段时间了,所以我觉得很愚蠢地被困在这个问题上:(

while i < 0:

从一开始这将是错误的,因为大概i是从积极开始的。 你要:

while i > 0:

换句话说,您想要“从i开始,从n开始,然后在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

while条件应该是i > 0而不是i < 0因为它永远不会满足它,因为我从20开始(或者在其他情况下更多)

希望我的回答有帮助!

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM