|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
每日完成作业,打印星号,
- temp = input("请输入一个整数数字:")
- n =int(temp)
- while n > 0:
- i = n-1
- j = n
- while i > 0:
- print(" ",end="")
- i = i -1
- while j > 0:
- print("*",end="")
- j = j - 1
- print()
- n = n-1
-
复制代码
当输入数字n的数值较大时,上述代码逐次打印,十分缓慢,改进如下:
- # 获取用户输入的有效正整数
- while True:
- try:
- total_rows = int(input("请输入一个正整数:"))
- if total_rows <= 0:
- print("输入必须大于0,请重新输入。")
- else:
- break
- except ValueError:
- print("输入无效,请输入一个整数。")
- # 使用列表推导式创建图案的每一行
- pattern = []
- for current_row in range(total_rows, 0, -1):
- spaces = " " * (current_row - 1)
- stars = "*" * current_row
- pattern.append(spaces + stars)
- # 使用换行符连接列表并一次性打印
- print("\n".join(pattern))
复制代码 |
|