Theo Boston
Theo Boston

Reputation: 21

Multiplication Tables in Python

this is my code right now:

loop_count = 1
for i in range(mystery_int):
    for x in range(1,mystery_int):
        print(x*loop_count, end=" ")
    print (loop_count)
    loop_count+=1

this is what it is supposed to print:

1   2   3   4   5
2   4   6   8   10
3   6   9   12  15
4   8   12  16  20
5   10  15  20  25

But it prints:

1 2 3 4 1
2 4 6 8 2
3 6 9 12 3
4 8 12 16 4
5 10 15 20 5

Upvotes: 0

Views: 159

Answers (3)

fferri
fferri

Reputation: 18950

the range for x should be range(1,mystery_int+1), and you also incorrectly print loop_count at the end of each line (which I replaced with the empty string, just to produce a newline).

loop_count = 1
for i in range(mystery_int):
    for x in range(1,mystery_int+1):
        print(x*loop_count, end=" ")
    print('')
    loop_count+=1

Note that the loop_count variable is not really needed. You could write the program as:

for i in range(1,mystery_int+1):
    for x in range(1,mystery_int+1):
        print(x*i, end=" ")
    print('')

or even better as:

for i in range(1,mystery_int+1):
    print(*[x*i for x in range(1,mystery_int+1)], sep=" ")

Upvotes: 0

prophet-five
prophet-five

Reputation: 559

you are running on two for loops in addition to using another counter, i would recommend sticking only to the loops:

for i in range(1,mystery_int+1):
    for x in range(1,mystery_int+1):
        print(i*x, end=" ")
    print("") # new line

Upvotes: -1

Austin
Austin

Reputation: 26037

You need to range till mystery_int + 1 because in range, second argument is exclusive. So, for example, range(1,6) gives numbers from 1 to 5.

Also, I added an empty print() which basically adds a newline to match with desired output. Using end='\t' further aligns output properly.

loop_count = 1
mystery_int = 5

for i in range(mystery_int):
    for x in range(1, mystery_int + 1):
        print(x * loop_count, end='\t')
    print()
    loop_count += 1

Upvotes: 3

Related Questions