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)
INPUT:
250
OUTPUT:
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 thedef
keyword is used to define a function and theprint_factors
function is used to print the factors of the variablex
. - After which we declare a
print
function which will display the statement("\nThe factors of",x,"are:")
, wherex
holds the factors. - We declare a
for
loop where therange
for the variablei
is(1, x + 1)
after which we declare anif
statement with the conditionx % i == 0:
. That is followed by aprint
statement which will display the values of variablei
. - In the above lines of code, the
for
loop will iterate until the values within the given range are used in theif
statement where if the condition is satisfied, it will display the values obtained using theprint
statement. - Here we give the user the option to enter the values and the input values are scanned using the
input
function and are stored in the variablenum
with the statements/strings("Enter the integer:" )
, we use theint
function and declare the input value as an integer value. - We print the values of the variable
num
using the functionprint_factors(num)
.
NOTE:
- 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.