Python Code to Print Factors of a Given Number Using a While Loop

Write a python program to print the factors of a given number using a while loop:

This code will print all the factors of a given number using a while loop.

    Simple code:

    num = int(input("Enter a number: "))
    i = 1
    
    while(i <= num):
        if(num % i == 0):
            print(i)
        i += 1

    Code with explanation:

    # Ask the user to enter a number and store it in the variable 'num'
    num = int(input("Enter a number: "))
    
    # Initialize a variable 'i' to 1
    i = 1
    
    # Use a while loop to iterate through all the numbers from 1 to 'num'
    while(i <= num):
        # Check if the current number is a factor of 'num' using the modulus operator
        if(num % i == 0):
            # If it is a factor, print it
            print(i)
            
        # Move to the next number
        i += 1

    Explanation:

    • The program prompts the user to enter a number using the input() function and stores it in the variable ‘num’.
    • A while loop is used to iterate through all the numbers from 1 to ‘num’ (inclusive). At each iteration, the current number is checked if it is a factor of ‘num’ using the modulus operator. If it is a factor, it is printed using the print() function.
    • Finally, the loop moves to the next number by incrementing the ‘i’ variable by 1.
    Was this helpful?
    YesNo

    Related Articles:

    Recent Articles:

    0 0 votes
    Article Rating
    Subscribe
    Notify of
    0 Comments
    Inline Feedbacks
    View all comments
    0
    Would love your thoughts, please comment.x
    ()
    x