使用for语句输出*号构成一个几何形状,可以是方形、菱形、圆形、心形等。 例如: * *** ***** *** *
时间: 2024-04-19 11:21:48 浏览: 89
使用for语句输出*号构成不同的几何形状可以通过嵌套循环来实现。下面是几种常见的几何形状的示例代码:
1. 方形:
```python
size = 5 # 方形的边长
for i in range(size):
for j in range(size):
print("*", end=" ")
print()
```
2. 菱形:
```python
size = 5 # 菱形的边长
for i in range(size):
for j in range(size - i - 1):
print(" ", end="")
for j in range(2 * i + 1):
print("*", end="")
print()
for i in range(size - 2, -1, -1):
for j in range(size - i - 1):
print(" ", end="")
for j in range(2 * i + 1):
print("*", end="")
print()
```
3. 圆形:
```python
import math
radius = 5 # 圆形的半径
for i in range(-radius, radius + 1):
for j in range(-radius, radius + 1):
if math.sqrt(i ** 2 + j ** 2) <= radius:
print("*", end=" ")
else:
print(" ", end=" ")
print()
```
4. 心形:
```python
size = 10 # 心形的大小
for y in range(size, -size, -1):
for x in range(-size, size + 1):
if (x * 0.04) ** 2 + (y * 0.1) ** 2 - 1 <= 0:
print("*", end="")
else:
print(" ", end="")
print()
```
阅读全文