方法一:使用for循环和条件判断
```python
def print_diamond(num):
if num % 2 == 0:
print("请输入奇数行数")
return
half = (num + 1) // 2
for i in range(half + 1):
spaces = ' ' * (half - i)
stars = '*' * (2 * i + 1)
print(spaces + stars)
for i in range(half - 1, -1, -1):
spaces = ' ' * (half - i)
stars = '*' * (2 * i + 1)
print(spaces + stars)
示例
print_diamond(5)
```
方法二:直接输出空心菱形
```python
def print_diamond(n):
for i in range(n):
print(' ' * (n - i - 1) + '*' * (2 * i + 1))
for i in range(n - 2, -1, -1):
print(' ' * (n - i - 1) + '*' * (2 * i + 1))
示例
print_diamond(5)
```
方法三:使用输入获取菱形大小
```python
num = int(input("请输入菱形的大小(奇数):"))
if num % 2 == 0:
print("请输入奇数行数")
exit()
half = (num + 1) // 2
for i in range(half + 1):
spaces = ' ' * (half - i)
stars = '*' * (2 * i + 1)
print(spaces + stars)
for i in range(half - 1, -1, -1):
spaces = ' ' * (half - i)
stars = '*' * (2 * i + 1)
print(spaces + stars)
```
这些方法都可以实现空心菱形的打印,你可以根据自己的需求和喜好选择合适的方法。