INTRODUCTION
Remember division with remainders. If we divide 13 by 4, we get 3 and remainder 1:
Sometimes when you divide one number by another, you get a remainder of zero. For example:
If the remainder of the division is zero, then in the above example we will call 5 the factor (divisor) of 15.
EXAMPLE
We will write factors (dividers, divisors) of the number 12:
PYTHON CODE
num = input("Enter a positive natural number: ")
try:
num = float(num)
if num <= 0 or not num.is_integer():
print("Error: Entered number is not a positive natural number.")
else:
factors = []
for i in range(1, int(num) + 1):
if num % i == 0:
factors.append(i)
print("The factors of", int(num), "are:", factors)
except ValueError:
print("Error: Entered value is not a number.")
HOW THE CODE WORKS?
- The program gets a number from the user using a function input.
- If the number is less than or equal to zero or not an integer, the program displays an appropriate error message.
- If the number is valid, the program creates an empty list ‘factors’ which will hold the divisors of the number.
- The program loops through the integers from 1 to the number entered by the user (inclusive) using a for loop. Checks whether the entered number is divisible without remainder by the current number in the iteration. If so, the current number is added to the factors list.
- After reviewing all the numbers, the program displays the divisors of the entered number on the screen.
Dodaj komentarz