简体   繁体   中英

I am new to python and I am wondering why this while loop isn't working

It is meant to find all the factors for a number, can someone help me? the error that its giving me is that it cant divide by zero, but it shouldn't be doing that by that point.

factored = False

number_s = input("What is the number\n")
number = (int(number_s))

while factored == False:
    factor_number = number
    factored_number = number / factor_number
    if factored_number == 0:
        break



    decimal = isinstance(factored_number, int)

    if decimal == False and factored_number <= number:
        print(factored_number)
        number = factored_number - 1
    else:
        pass

    if factored_number == number:
       break

You have to check if the number is zero before you preform the operation. For example

factored = False

number_s = input("What is the number\n")
number = (int(number_s))

while factored == False:
    factor_number = number
    #notice we are checking the user's number is == 0 before we even divide it.
    if factor_number == 0:
        break
    factored_number = number / factor_number




    decimal = isinstance(factored_number, int)

    if decimal == False and factored_number <= number:
        print(factored_number)
        number = factored_number - 1
    else:
        pass

    if factored_number == number:
       break

I also hope you know there are much easier ways of doing this. For example, using modulus operation % . Here's an implementation using that.

x = 10
for i in range(1, x + 1):
       if x % i == 0:
           print(i)

output

1
2
5
10

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