Python轻松实现九九乘法表,多种方向随意切换,代码超简单!
在Python中,实现九九乘法表非常简单。下面是一个简洁的代码示例,可以根据需要轻松切换方向:
```python
def print_multiplication_table(direction='vertical'):
for i in range(1, 10):
if direction == 'horizontal':
for j in range(1, 10):
print(f"{ij:2d}", end=" ")
print()
else: 默认垂直方向
for j in range(1, i+1):
print(f"{ij:2d}", end=" ")
print()
调用函数,默认垂直方向
print_multiplication_table()
调用函数,水平方向
print_multiplication_table('horizontal')
```
在这个代码中,`print_multiplication_table` 函数接受一个参数 `direction`,用于控制九九乘法表的打印方向。默认为垂直方向,如果传入 `'horizontal'`,则打印水平方向的九九乘法表。