0
How do I print a multiplication table neatly?
I want to print a multiplication table from 1 to 5 so it looks like this: 1 x 1 = 1 1 x 2 = 2 ... 5 x 5 = 25 Whatâs the simplest way to do that with loops?
3 Réponses
+ 3
Once again, please provide an example of your attempt.
The idea though is to use nested loops (one for a and one for b in a x b = c).
+ 3
Aleksei Radchenkov provided the basis for a oneliner
print('\n'.join(f"{a} x {b} = {a * b}" for a in range(1, 6) for b in range(1, 6)))
+ 1
SAIFULLAHI KHAMISU
for your example, maybe this?
for a in range(1,6):
for b in range(1,6):
print(a, 'x', b, ' = ', a*b)
print() #optional, just for extra blank line
BroFar
nice one-liner, I can't resist tweaking it a bit more for a more prettified version.
#for Python 3.12+:
print(*(f" {a:>2} x {b:>2} = {(a * b):>3}{'\n' if b<10 else '\n\n'}" for a in range(1, 11) for b in range(1, 11)), end='')
#for Sololearn, Python < 3.12 can't include '\n' in f-string. so i have to assign '\n' to a variable, resulting in 2 lines, unfortunately:
nl = '\n'
print(*(f" {a:>2} x {b:>2} = {(a * b):>3}{'' if b<10 else nl}" for a in range(1, 11) for b in range(1, 11)), sep='\n', end='')