Write a program that asks the user to enter a number and prints out all the divisors of that number. [Hint: the % operator is used to tell if a number is divisible by something. See Section 3.2.]
number = int(input("Enter a number: "))
print("The divisors of", number, "are:")
for i in range(1, number+1):
if number % i == 0:
print(i)
This code first prompts the user for a number and stores it in the variable number
. It then uses a for loop to iterate over the range from 1 to number
(inclusive) and checks if number
is divisible by each number in the range using the modulus operator (%
). If number
is divisible by the current number, it prints that number.
You could name this code "divisor_printer" or something similar.
Here is an example of the output of the code I provided:
Enter a number: 20
The divisors of 20 are:
1
2
4
5
10
20
This is what the user would see if they entered 20 when prompted for the number. The divisors of 20 are 1, 2, 4, 5, 10, and 20, so these numbers are printed by the program.
Here is another example of the output:
Enter a number: 7
The divisors of 7 are:
1
7
In this example, the user entered 7 as the number. The divisors of 7 are 1 and 7, so these numbers are printed by the program.
Note that the output will vary depending on the number the user inputs. The program will print all the divisors of the number the user inputs.
0 Comments