Write a program to Find Factors of Number in Python
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | # Python Program to find the factors of a number # define a function def print_factors(x): # This function takes a number and prints the factors print("The factors of",x,"are:") for i in range(1, x + 1): if x % i == 0: print(i) #to take input from the user num = int(input("Enter a number: ")) print_factors(num) |
This Python program finds the factors of a given number.
The program defines a function print_factors(x)
that takes a number as an argument and prints out all the factors of that number. The function starts by using a for loop to iterate through the range of numbers from 1 to the input number (x+1).
In each iteration, the function checks if the current number (i) is a factor of x by using the modulo operator (%
) to check if the remainder of x divided by i is zero. If the condition is true, the current number (i) is printed as a factor of x.
The main program then prompts the user to enter a number and assigns it to the variable num
. Then it calls the print_factors(num)
function and prints out all the factors of the number entered.
For example, if the user enters the number 45
, the output would be:
![](https://i0.wp.com/www.code4example.com/wp-content/uploads/2019/07/python-examples-28.png?resize=652%2C235&ssl=1)