I am making a product table that the user gives an input to determine its size.
The columns are labeled AZ The rows are labeled by Numbers with a "|"next to it.
The program prints all headers correctly. The only issue is, the product table is printed the same amount of times as the input along the rows.
See attached image for my attempt with an input of '3'. The black product table on the image with an input of '4' is how the answer should be formatted.
def get_pro_tab():
n = int(input('Please enter a positive integer: '))
print("(Don't go too crazy)")
print()
#letters
print(' ',end='')
for letter in range(n):
print('{0:4}'.format(chr(65 + letter)),end=' ')
print()
#margins
marigin = 0
for number in range(1, n+1):
print(str(number)+ "|", end='')
#numbers
prod = 0
for y in range(1, n+1):
for z in range(1, n+1):
prod = y * z
print('{0:4}'.format(str(prod)), end=' ')
print('\n')
I think you just had one extra loop in your code. I just commented it out, now I think it works:
def get_pro_tab():
n = int(input('Please enter a positive integer: '))
print("(Don't go too crazy)")
print()
#letters
print(' ',end='')
for letter in range(n):
print('{0:4}'.format(chr(65 + letter)),end=' ')
print()
#margins
marigin = 0
for number in range(1, n+1):
print(str(number)+ "|", end='')
#numbers
prod = 0
#for y in range(1, n+1):
for z in range(1, n+1):
prod = number * z
print('{0:4}'.format(str(prod)), end=' ')
print()
For input 5 this prints:
A B C D E
1|1 2 3 4 5
2|2 4 6 8 10
3|3 6 9 12 15
4|4 8 12 16 20
5|5 10 15 20 25
If you like, you can make your life even a bit easier by using the format strings like:
def get_pro_tab():
n = int(input('Please enter a positive integer: '))
print("(Don't go too crazy)")
print()
#letters
print(' ',end='')
for letter in range(n):
print('{0:>4s}'.format(chr(65 + letter)),end=' ')
print()
#margins
marigin = 0
for number in range(1, n+1):
print(str(number)+ "|", end='')
#numbers
prod = 0
#for y in range(1, n+1):
for z in range(1, n+1):
prod = number * z
print('{0:4d}'.format(prod), end=' ')
print()
If you run this, with the same input, you get:
A B C D E
1| 1 2 3 4 5
2| 2 4 6 8 10
3| 3 6 9 12 15
4| 4 8 12 16 20
5| 5 10 15 20 25
Ok, I know, beauty lies in the eye of the beholder, but to me it looks more appealing if the numbers are aligned to the right. But again it was just a very small modification of your code.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.