为什么 Python 不让我打印一个空格?



我正在编写一个python代码,使用"#"钥匙作为积木。该程序首先询问用户对楼梯高度的偏好,然后再"构建"相应高度的楼梯。然而,每当我的程序生成阶梯时,它似乎永远无法在正确的位置得到最上面的台阶。就好像它忽略了空格,我不知道该怎么做。

程序的第一个版本是这样的:

height = int(input("enter height: "))
for x in range(height):
print("#"*(x+1))

非常简单的东西。下面是代码过程的一个示例:

enter height: 5
#
##
###
####
#####

接下来,我想挑战自己。我想看看是否可以创建一个程序,将楼梯反过来建造,就像下面这样:

enter height: 5
#
##
###
####
#####
下面是我为生成这种类型的楼梯而编写的代码:
count = 1
height = int(input("enter height: "))
space = height - 1
if height < count:
print("invalid height")
elif height == count:
print("#")
else:
for x in range(height):
print((" " * space) + ("#" * count))
space -= 1
count += 1
下面是代码过程的一个示例:
enter height: 5
#
##
###
####
#####

正如你所看到的,除了最上面的台阶,其余的楼梯都很完美。我不明白为什么会发生这种事。我试图改变代码,但我似乎永远无法使顶部的步骤移动到正确的位置。就像Python不能识别空格一样,这很奇怪,因为楼梯的其余部分都很好。

一种修复方法是在获取高度后添加一个print语句。Python的输入会在输入后清理新的行字符,但正如注释中建议的那样,可能会发生一些进一步的空白删除。

count = 1
height = int(input("enter height: "))
print(height)
space = height - 1
if height < count:
print("invalid height")
else:
for x in range(height):
print((space * " ") + ("#" * count))
space -= 1
count += 1

同样值得注意的是,额外的elif被删除了。你的循环适用于基本情况。