如何在Python的repeatChar函数中使用print的end参数生成平行四边形
修改方案
题目给定的repeatChar函数核心逻辑是直接打印字符,不返回字符串,通过print的end=''参数保证多次打印的字符在同一行展示,你之前把repeatChar的返回值拼接成字符串的用法不符合要求。
正确的修改步骤
- 首先把
repeatChar函数恢复为题目给定的实现,不要自己改成返回字符串的版本 - 主函数中取消
output字符串拼接逻辑,每一行内容调用repeatChar打印完成后,单独调用一次无参数的print()实现换行(无参数的print默认输出换行符)
修改后完整可运行代码
def repeatChar(numRepeats, outputChar): ''' output the outputChar numRepeats times on the same line ''' for colNo in range(numRepeats): print(outputChar, end='') # print outputChar and stay on the same line (don't go to next line) def main(): print("This program will output a parallelogram.") side = int(input("How long do you want each side to be? ")) char = input("Please enter the character you want it to be made of: ") # 输出上半部分三角形 for topTriangle in range(1, side + 1): repeatChar(topTriangle, char) print() # 整行打印完成后换行 # 输出下半部分三角形 for btmTriangle in range(1, side + 1): repeatChar(btmTriangle, " ") repeatChar((side - btmTriangle), char) print() # 整行打印完成后换行 main()
原错误原因说明
你之前尝试把repeatChar里的end改成'\n'会导致每个字符打印完就换行,输出会变成竖排的字符,自然不符合平行四边形的格式要求。现在的实现保证了同一行的所有字符打印时都不换行,整行打印完成后再统一换行,就可以输出符合预期的平行四边形效果。
内容的提问来源于stack exchange,提问作者Tempest
相关产品推荐
相关产品推荐

