Python打印三角形异常:输入超出阈值仍输出三角形求助
问题修复方案
你的问题核心是错误提示后没阻止后续打印代码执行——不管输入的行数是否合法,下面的for循环都会无条件运行。
最简单的修复方式是把打印三角形的代码放到if-elif的else分支里,只有当行数在1到20之间时才执行打印逻辑:
if rows < 1: print('Invalid input value. The numbers of rows cannot be less than 1.') elif rows > 20: print('Invalid input value. The numbers of the rows cannot be greater than 20.') else: # 仅输入合法时执行打印 for i in range(rows): for j in range((rows - i) - 1): print(end=" ") for j in range(i + 1): print("*", end=" ") print()
如果是脚本场景,也可以在错误提示后直接终止程序(需要导入sys模块):
import sys if rows < 1: print('Invalid input value. The numbers of rows cannot be less than 1.') sys.exit() elif rows > 20: print('Invalid input value. The numbers of the rows cannot be greater than 20.') sys.exit() # 输入合法时才执行打印 for i in range(rows): for j in range((rows - i) - 1): print(end=" ") for j in range(i + 1): print("*", end=" ") print()
第一种用else分支的写法更贴合Python逻辑,无需额外导入模块,优先推荐。
内容的提问来源于stack exchange,提问作者user20083173
相关产品推荐
相关产品推荐

