在python语法下,请你用while循环和for循环两种方式,绘制一个等腰三角形的字符画
时间: 2024-10-24 19:14:08 浏览: 26
当然可以。在Python中,我们可以使用`while`循环和`for`循环结合字符串拼接的方式来绘制等腰三角形。这里我将分别演示这两种方法:
**使用while循环的方式:**
```python
n = int(input("请输入等腰三角形的高度:"))
i = 1
while i <= n:
print(' ' * (n - i) + '*' * (2 * i - 1)) # 两边空格和中间星号的数量会随着循环减少而变化
i += 1
```
**使用for循环的方式:**
```python
def draw_triangle(n):
for i in range(1, n+1): # 从1到n,包括n
spaces = ' ' * (n - i)
stars = '*' * (2 * i - 1)
print(spaces + stars)
draw_triangle(int(input("请输入等腰三角形的高度:")))
```
运行以上代码后,会提示用户输入三角形的高度,然后按照指定高度绘制出等腰三角形。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20250102104920.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)