Find the Factors of a Number (Solution)
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.
input() by the user, where I’ll say
a positive integer".
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.
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:
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.
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.
Become a Member to join the conversation.