分别使用程序语句和列表推导编程实现如下要求: (两者都用到才能得满分,只做1个只能得一半分) 输出如下所示 * 号矩阵 学号为奇数的是做如下所示 * * * * * * * * * 学号为偶数的是做如下所示 * * * * * * * * *
时间: 2023-08-01 16:09:37 浏览: 58
使用 Python 语言回答:
程序语句实现:
```python
# 输出奇数学号的 * 号矩阵
if int(input("请输入你的学号:")) % 2 == 1:
for i in range(5):
for j in range(5):
if i == j or i + j == 4:
print("*", end=" ")
else:
print(" ", end=" ")
print()
# 输出偶数学号的 * 号矩阵
else:
for i in range(5):
for j in range(5):
if i == 0 or i == 4 or j == 0 or j == 4 or i + j == 4 or i == j:
print("*", end=" ")
else:
print(" ", end=" ")
print()
```
列表推导实现:
```python
# 输出奇数学号的 * 号矩阵
if int(input("请输入你的学号:")) % 2 == 1:
matrix = [["*" if i == j or i + j == 4 else " " for j in range(5)] for i in range(5)]
for row in matrix:
print(" ".join(row))
# 输出偶数学号的 * 号矩阵
else:
matrix = [["*" if i == 0 or i == 4 or j == 0 or j == 4 or i + j == 4 or i == j else " " for j in range(5)] for i in range(5)]
for row in matrix:
print(" ".join(row))
```
阅读全文