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

Python打印自定义起始字符的字母金字塔代码问题求助

Python字母金字塔图案代码修改方案

修改逻辑说明

  • 新增输入校验,保证起始字符为大小写字母,同时自动识别输入字符的大小写区间,适配两种输入
  • 每行开始时重置字符计数偏移,实现行内循环独立的要求,行与行的字符计数互不影响
  • 通过对26取模的方式计算当前要打印的字符,打印到Z或z后自动从起始字符开始循环,不会输出非字母字符

修改后完整代码

c = input("Enter a character - ")
# 校验输入为字母
assert c.isalpha(), "起始字符必须输入大小写字母"
start_ord = ord(c)
is_upper = c.isupper()
# 确定当前大小写区间的基准ASCII值
base_ord = ord('A') if is_upper else ord('a')
# 计算起始字符相对于基准值的偏移
start_offset = start_ord - base_ord
# 大小写字母总长度都是26
ALPHA_TOTAL = 26

def pattern(n):
    for i in range(n):
        # 每行重置偏移,保证行内循环独立
        current_off = start_offset
        for j in range(i+1):
            ch = chr(base_ord + current_off % ALPHA_TOTAL)
            print(ch, end=" ")
            current_off += 1
        print()

n = int(input("Enter the no. of rows - "))
pattern(n)

测试示例

测试1:输入起始字符为A,行数为7

输出结果:

A 
A B 
A B C 
A B C D 
A B C D E 
A B C D E F 
A B C D E F G 

测试2:输入起始字符为Y,行数为4

输出结果:

Y 
Y Z 
Y Z A 
Y Z A B 

内容的提问来源于stack exchange,提问作者Param Dhingana

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 22:54:02