簡體   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