编写程序,实现输入整数n,输出由数字组成的三角形(如下图,n=5),并在此基础上修改,使之能输出数字菱形。 + + + +1 + + +1+2+1 + +1+2+3+2+1 1+2+3+4+3+2
时间: 2023-11-18 15:02:53 浏览: 102
输入数字输出菱形
以下是Python实现输入整数n,输出由数字组成的三角形和数字菱形的代码:
```python
# 输出数字三角形
n = int(input("请输入一个不大于10的正整数n:"))
for i in range(1, 2*n):
if i <= n:
for j in range(1, i+1):
print(j, end=" ")
else:
for j in range(1, 2*n-i+1):
print(j, end=" ")
print()
# 输出数字菱形
n = int(input("请输入一个不大于10的正整数n:"))
for i in range(1, 2*n):
if i <= n:
for j in range(1, i+1):
print(j, end=" ")
else:
for j in range(1, 2*n-i+1):
print(j, end=" ")
print()
for i in range(1, 2*n):
if i <= n:
for j in range(1, n-i+1):
print(" ", end=" ")
for j in range(n-i+1, n):
print(j, end=" ")
for j in range(n, i+n):
print(n*2-j+i-1, end=" ")
for j in range(i+n, 2*n):
print(" ", end=" ")
else:
for j in range(1, i-n+1):
print(" ", end=" ")
for j in range(i-n+1, n):
print(j, end=" ")
for j in range(n, i):
print(n*2-j+i-1, end=" ")
for j in range(i, 2*n):
print(" ", end=" ")
print()
```
阅读全文