You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何不使用嵌套循环,仅用while循环打印1-5倒直角数字金字塔

单层while循环打印1-5倒直角数字金字塔实现方案

约束符合说明

  • 全程仅使用单层while循环,无嵌套逻辑,满足要求
  • 输出效果与需求指定的倒直角数字金字塔完全匹配

实现思路

按照给定提示设计逻辑:

  1. 定义两个变量:当前需打印的数字current_num = 1,当前行数字重复打印次数print_count = 5
  2. while循环执行条件设置为current_num <= 5,覆盖1到5的数字范围
  3. 每次循环直接拼接对应数量的数字字符串打印,完成后print_count减1、current_num加1进入下一轮循环

完整代码

# 初始化变量
current_num = 1
print_count = 5

# 单层while循环实现
while current_num <= 5:
    print(f"{current_num} " * print_count)
    print_count -= 1
    current_num += 1

输出结果

1 1 1 1 1 
2 2 2 2 
3 3 3 
4 4 
5 

内容的提问来源于stack exchange,提问作者Divij Anwesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 04:36:04