Find the Factors of a Number (Solution)
00:00
I’m back over in a new file in IDLE and with a short task description. I want to display all the factors of a number chosen by the user. So I want to start by allowing the user to choose a number and assign that to a variable. num
is input()
by the user, where I’ll say "Enter
a positive integer"
.
00:22
And then I want to convert that to an integer, right? Because the input is going to be a string. So I’ll wrap that into a call to int()
. And keep in mind, in this current form, this is going to fail if the user inputs anything other than an integer.
00:35 So there’s ways that you could fix that, that you’ve seen before. I’m not going to do it right now. So let’s first get the basic functionality done of this. All right, so now I know that I want to go over all the numbers up to that specific number that the user inputs, and that sounds like a loop.
00:51
So we’ll start with a for
loop. for
every divisor
in a range()
that starts from 1
and goes up to the number that the user entered plus one.
01:04
Keep in mind that the range otherwise doesn’t include the number that you need, so I’m going to say num + 1
. And now I want to do something in here.
01:13 Let’s put in a comment for now: I want to figure out what’s the factor,
01:19 which numbers are factors.
01:24
And you’ve actually done something like that before, and you’ve used the modulo operator (%
) for it. So it can say if
the num
that is entered %
the divisor
01:37
is equal to 0
—that means there’s no remainder—then you want to print out the message, and the message is going to be that whatever that number is, that it’s currently looping over is a factor of the number that the user put in. You can do that using an f-string:
01:59
f"{divisor} is a factor of {num}"
. Okay, this looks good to me. Let’s give it a spin.
02:14
Save it. Enter a positive integer, so I’m going to say 12
, like in the example. And then you can see 1
, 2
, 3
, 4
, 6
, and 12
are all factors of 12
.
02:24 And that’s the same output that we’ve already seen in the task description. We can try something else. Let’s run it again.
02:34
Positive integer 6
. 1
, 2
, 3
, and 6
are all factors of 6
. Great. So this is a possible solution that works.
02:43 Keep in mind that if the user inputs something that isn’t a positive integer, then this is not going to work. So you could enhance this little program by putting in some error handling, for example. But for now, I’m happy with this solution.
02:58
So, I’ll just clean up the comment here, and let’s move over here. Here’s the possible solution. The code is a little more concise, so num
is the input("Enter a positive integer: ")
converted to an integer.
03:12
And then for divisor in range(1, num + 1):
if num % divisor
has no remainder, then print out this message. And that’s it. Ian, we solved the challenge. Yippee!
Become a Member to join the conversation.