为什么我的Python代码无法找到数字的所有除数?

时间:2019-06-09 19:00:56

标签: python-3.x

我觉得我有正确的代码来确定所请求数字的除数,但我的代码实际上不会打印出数字。

我尝试使用for循环和while循环编写此代码,但问题似乎出在打印数字上。

n = int(input("Let's find the divisor, type in a number: "))
x = 1
print("The divisors for this number are: ")

def divisor(n):
    for x in range(1, n+1):
        if n % x == 0:
            print(x)

我希望将给定数字的除数打印出来。 而是,它们没有被打印。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

定义后,您需要调用divisor(n)函数。因此,您可以在定义divisor()之后调用print命令,或者将初始代码放入函数中,然后在脚本末尾调用该函数,以便在执行任何操作之前先遍历所有代码。 我还添加了一条try / except语句,以确认输入为int()。

def main():
    in_num = input("Let's find the divisor, please type in a number: ")
    # Get input number from user and assign to variable "in_num"
    valid_num = confirm_int_input(in_num)
    # Call the confirm_int_input() function to confirm the input is an int() with the "in_num" variable.

    even_numbers = divisor(valid_num)
    # Call the divisor() function to get all the evenly divisible numbers and assign it to the variable "even_numbers"
    print('The evenly divisible numbers of "', valid_num, '" are: ', even_numbers, sep='')
    # Print "even_numbers" with an explanation.

def confirm_int_input(test_int):
    try:
        valid_int = int(test_int)
        # Validate input can be a type int()
        return valid_int
    except ValueError:
        # Input can't be converted to valid int() so print an error.
        print('Error, "', test_int, '" is not a valid integer.', sep='')
        quit()
        # Stop the script.

def divisor(num):
    even_divisors = ''
    for divide_by in range(1, num + 1):
    # For loop to check all possible even divisor combinations.
        if num % divide_by == 0:
        # if num is exactly divisible by 0 then:
            even_divisors += '\n' + str(divide_by)
            # str() of all evenly divisible numbers (new line before each one).
            # This could also be substituted for a list or something like that.
    return even_divisors
    # return the evenly divisible numbers str() to the main function.

main()
# Call the main function.