0

I'm trying to write a program that reads 2 positive integers (m and n), and then print the n first positive integers of m using only while loop.

Here is the original question

Write a program in the Python 3.x language that reads two positive integers, m and n, and print the first n positive integers that are multiples of m.

And the output of the code should look like:

Type a positive integer for m: 9 
Type a positive integer for n: 5 
The first 5 positive integers multiples of 9 are:
9
18
27
36
45

So I have done so far:

m = int(input("Type a integer for m: "))
n = int(input("Type a integer for n: "))
i = 1
print()
print("The first ",n,"positive integers multiples of ", m," are:")
while i <= n:
    m = m * i
    print(m)
    i = i + 1

I wanna understand how to fix this one and I realize that using for or if it's gonna be easier to do that

petezurich
  • 9,280
  • 9
  • 43
  • 57
  • 4
    In this case it's fairly obvious what the issue is, but in the future please describe what the problem with the code is. Does it throw an exception? Does it produce incorrect output? Nobody wants to guess or have to run the code to find out. See also [mcve]. – Aran-Fey Mar 17 '19 at 09:18
  • 1
    To follow up Aran-Fey's comment. What output do you get? – Martin Bonner supports Monica Mar 17 '19 at 09:19
  • You might also want to consider what happens if I enter '-15' for n – Martin Bonner supports Monica Mar 17 '19 at 09:20
  • Or if I input `"fifteen"` and `"twentytwo"` - see [asking-the-user-for-input-until-they-give-a-valid-response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Patrick Artner Mar 17 '19 at 09:21

2 Answers2

2

your problem is in this line

m = m * i

you are caching an intermediate value and then multiplying that in the next iteration, so the first time you are multiplying your m but the next iteration you are multiplying the previous intermediate value instead of the original m
you can change your loop this this:

while i <= n:
    print(m * i)  #  you don't need to save the intermediate result, you can just print it
    i = i + 1
Nullman
  • 4,179
  • 2
  • 14
  • 30
0

Nullman's asnwer is the right one, anyways here is your code corrected, just in case it may help you understand better the error:

m = 9
n = 5
i = 1
print()
print("The first ",n,"positive integers multiples of ", m," are:")
while i <= n:
    multiple = m * i
    print(multiple)
    i = i + 1

You cannot use if, but you could indeed use for:

m = 9
n = 5
i = 1
print()
print("The first ",n,"positive integers multiples of ", m," are:")
for i in range(1, n + 1):
    multiple = m * i
    print(multiple)
    i = i + 1
dzang
  • 2,160
  • 2
  • 12
  • 21
  • Thanks dzang. Think I understood the problem. I cannot lost the value of a because it is important, so I define a new variable called multiple and let the m value remains the same. – highentropy1915 Mar 17 '19 at 20:38