python九九乘法表代码

时间:2025-02-13 16:19:00 单机游戏

使用嵌套循环打印九九乘法表

```python

for i in range(1, 10):

for j in range(1, i + 1):

print(f"{i} * {j} = {i * j}", end="\t")

print()

```

或者使用更简洁的写法:

```python

for i in range(1, 10):

print('\t'.join([f"{j} * {i} = {i * j}" for j in range(1, i + 1)]))

```

将九九乘法表写入文件

```python

with open('multiplication_table.txt', 'w') as f:

for i in range(1, 10):

for j in range(1, i + 1):

f.write(f"{i} * {j} = {i * j}\t")

f.write("\n")

```

反向输出乘法表

```python

for x in range(9, 0, -1):

for y in range(1, x + 1):

print(f"{y} * {x} = {x * y}", end="\t")

print()

```

使用字符串格式化

```python

for i in range(1, 10):

row = ''

for j in range(1, i + 1):

row += f"{j} * {i} = {i * j:<4}"

print(row)

```

基础双重循环法

```python

for i in range(1, 10):

for j in range(1, i + 1):

print(f"{j} * {i} = {i * j}", end='\t')

print()

```

列表推导式写法

```python

for i in range(1, 10):

print('\t'.join([f"{j} * {i} = {i * j}" for j in range(1, i + 1)]))

```

这些方法都可以实现九九乘法表的输出,你可以根据自己的喜好选择其中一种或多种方法来使用。