In this python tutorial, you will learn how to Display Factors of a Number using the if statement and for loop along with the different operators of the python programming language.
How to Display Factors of a Number?
Let’s take a look at the source code , here the values are given as input by the user in the code, the if statement and for loop along with the assignment operators carry out the function.RUN CODE SNIPPET
# Python Program to find the factors of a number def print_factors(x): print("\nThe factors of",x,"are:") for i in range(1, x + 1): if x % i == 0: print(i) num = int(input("Enter the integer: ")) print_factors(num)
Enter the first integer: The factors of 250 are: 1 2 5 10 25 50 125 250
- At the start, we use
def print_factors(x)where the
defkeyword is used to define a function and the
print_factorsfunction is used to print the factors of the variable
- After which we declare a
("\nThe factors of",x,"are:"), where
xholds the factors.
- We declare a
forloop where the
rangefor the variable
(1, x + 1)after which we declare an
ifstatement with the condition
x % i == 0:. That is followed by a
- In the above lines of code, the
forloop will iterate until the values within the given range are used in the
ifstatement where if the condition is satisfied, it will display the values obtained using the
- Here we give the user the option to enter the values and the input values are scanned using the
inputfunction and are stored in the variable
numwith the statements/strings
("Enter the integer:" ), we use the
intfunction and declare the input value as an integer value.
- We print the values of the variable
numusing the function
- The function def is the keyword for defining a function in python.
- The if statements evaluates whether an expression is true or false. If a condition is true, the “if” statement is executed otherwise, its goes to the next line of code.
- The colon : at the end of the if statement tells Python that the next line of code should only be run if the condition is true.
- The modulus operator (%) is used to compute the reminder.
- The == equality operator is a comparison operator which returns True is the two items are equal and returns False if not equal.
- The statement for the input function are enclosed in single quotes and parenthesis.
- The \n in the code indicates a new line or the end of a statement line or a string.
- The print statement is followed by a period, to initiate the format function.
- The print statement/string to be displayed in enclosed in double quotes.