def check_divisor(number):
number = abs(number)
divisors = []
for i in range(1, number + 1):
if number % i == 0:
divisors.append(i)
return divisors
number = int(input("Enter an integer: "))
divisors = check_divisor(number)
print(f"The divisors of {number} are: {divisors}")
Code Explanation
1. Function Definition
def check_divisor(number):
def: Declares a new function.
check_divisor: The name of the function, which checks for all divisors of a given number.
number: Input parameter representing the number for which divisors are to be found.
2. Taking Absolute Value
number = abs(number)
abs(number): Returns the absolute value of the number (i.e., removes the negative sign if the number is negative).
Example: If number = -12, abs(-12) becomes 12.
This ensures that the logic for finding divisors works even if the input is a negative number.
3. Initializing an Empty List
divisors = []
divisors: An empty list to store all divisors of the given number.
4. Iterating Through Potential Divisors
for i in range(1, number + 1):
for i in range(1, number + 1):
Starts a loop to check all numbers (i) from 1 to number (inclusive).
range(1, number + 1): Generates all integers from 1 to number.
5. Checking for Divisors
if number % i == 0:
number % i: Computes the remainder when number is divided by i.
If the remainder is 0, it means i is a divisor of number.
6. Adding Divisors to the List
python
Copy code
divisors.append(i)
divisors.append(i): Adds the number i to the divisors list if it is a divisor of number.
7. Returning the List of Divisors
return divisors
return divisors: Returns the complete list of divisors after the loop finishes.
8. Taking User Input
number = int(input("Enter an integer: "))
input("Enter an integer: "): Displays a prompt and reads the user’s input as a string.
int(): Converts the string input into an integer.
number: Stores the user-provided number.
9. Calling the Function and Printing the Result
divisors = check_divisor(number)
print(f"The divisors of {number} are: {divisors}")
check_divisor(number): Calls the check_divisor function with the user-provided number.
divisors: Stores the list of divisors returned by the function.
print(f"..."): Displays the result in a user-friendly format using an f-string.
#source code --> clcoding.com
0 Comments:
Post a Comment