Estonia_girl Estonia_girl - 6 months ago 198
Python Question

Python multiplication table with while loops only

my task is to create a multiplication table looking like this where the user is asked to put in two numbers between 1 and 9. (in the picture the user put in "rows=3" "col=5").

I can't get my top row right, is it a way to make my code better?
"better" I mean like make the whole thing with only 2 while loops?

EDIT: I forgot to mention ONLY with WHILE loops, not with "for".

row=int(input("number of rows:"))
col=int(input("number of cols:"))
x=1
m=1
amount=col
while amount>0:
print("%5d"%m, end="")
m=m+1
amount-=1
print()
while x<(row+1):
y=1
print(x, end="")
while y<(col+1):
print("%4d"%(x*y), end="")
y=y+1
print("\n")
x=x+1

Answer

Juste manage all the table in heart of the loops. You can also have only one loop with a while i*j <=row*col if better is the minimum of loops. But for loop is the best solution for this problem.

row,col=3,5
i=0
while i <= row :
    j=0
    while j <= col:
        if i+j==0 : print('{:4s}'.format(''),end='') #corner
        elif i*j==0 : print('{:4d}'.format(i+j),end='') # border
        else : print('{:4d}'.format(i*j),end='') # table
        j=j+1   
    print()
    i=i+1
Comments