打印菱形python
时间: 2023-11-21 20:55:59 浏览: 90
以下是两种Python打印菱形的例子:
1.使用双重循环打印菱形
```python
n = 5
for i in range(n):
for j in range(n - i):
print(" ", end="")
for k in range(2 * i + 1):
print("*", end="")
print()
for i in range(n - 1, -1, -1):
for j in range(n - i):
print(" ", end="")
for k in range(2 * i + 1):
print("*", end="")
print()
```
2.使用字符串居中打印菱形
```python
s = '*'
for i in range(1, 8, 2):
print((s * i).center(7))
for i in reversed(range(1, 6, 2)):
print((s * i).center(7))
```
相关问题
打印空心菱形python
以下是打印空心菱形的Python代码:
```
n = int(input("请输入菱形大小: ")) # 获取菱形大小
# 打印上半部分
for i in range(n):
for j in range(n-i-1):
print(" ", end="")
for j in range(2*i+1):
if j==0 or j==2*i or i==n-1:
print("*", end="")
else:
print(" ", end="")
print()
# 打印下半部分
for i in range(n-2, -1, -1):
for j in range(n-i-1):
print(" ", end="")
for j in range(2*i+1):
if j==0 or j==2*i or i==n-1:
print("*", end="")
else:
print(" ", end="")
print()
```
通过输入菱形的大小,可以打印出相应大小的空心菱形。例如,当输入5时,打印出如下图案:
```
*
* *
* *
* *
* *
* *
* *
* *
*
```
打印菱形字母python代码
以下是打印菱形字母的 Python 代码:
```python
n = int(input("Enter the number of rows: "))
for i in range(1, n+1):
print(" "*(n-i) + "* "*i)
for i in range(n-1, 0, -1):
print(" "*(n-i) + "* "*i)
```
运行代码后,程序会要求输入行数,然后打印出对应的菱形。例如,输入 5,则打印出如下菱形:
```
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
```
阅读全文