如何修改Python代码将倒序哈希三角形改为正序输出
实现递增哈希三角形的代码修改方案
给定的line函数
def line(num=int, word=str): if word == "": print("*" * num) else: print(word[0] * num)
现有代码
def line(num=int, word=str): if word == "": print("*" * num) else: print(word[0] * num) def triangle(size): # You should call function line here with proper parameters while size > 0: line(size, "#") size -= 1
当前输出
###### ##### #### ### ## #
期望输出
# ## ### #### ##### ######
修改方案
问题核心是循环方向错误:当前代码从size递减到1,导致输出从最长到最短。要实现递增效果,需从1开始循环到指定的size。
修改后的triangle函数(while循环版)
def triangle(size): current = 1 while current <= size: line(current, "#") current += 1
更简洁的for循环版
def triangle(size): for current in range(1, size + 1): line(current, "#")
修改后,每次调用line时传入的num参数从1逐步递增到size,即可输出符合预期的递增哈希三角形。
内容的提问来源于stack exchange,提问作者Wolfie
相关产品推荐
相关产品推荐

