简体   繁体   中英

print factors of a number in python

I'm trying to print the factors of the number 20 in python so it goes: 20 10 5 4 2 1

I realize this is a pretty straightforward question, but I just had a question about some specifics in my attempt. If I say:

def factors(n):
    i = n
    while i < 0:
        if n % i == 0:
            print(i)
        i-= 1

When I do this it only prints out 20. I figure there's something wrong when I assign i=n and then decremented i, is it also affecting n? How does that work? Also I realize this could probably be done with a for loop but when I use a for loop I can only figure out how to print the factors backwards so that I get: 1, 2, 5, 10.... Also I need to do this using just iteration. Help?

Note: This isn't a homework question I'm trying to relearn python on my own since it's been a while so I feel pretty silly being stuck on this question :(

while i < 0:

This will be false right from the start, since i starts off positive, presumably. You want:

while i > 0:

In words, you want to "start i off at n , and decrement it while it is still greater than 0, testing for factors at each step".


>>> 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开始(或者在其他情况下更多)

Hope my answer helps!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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