Why doesn't Python let me print a blank space?

Question:

I am writing a python code that prints out stairs, using the "#" key as blocks. The program first asks the user for their preferred height for the stairs, before ‘building’ stairs of the height.Howver, whenever my program generates stairs, it can never seem to get the top step in the right place. It’s as if it’s ignoring the blank spaces and I don’t know what to do.

My first version of my program looked like this:

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

Very simple stuff. Here is an example of the code process:

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

Next, I wanted to challenge myself. I wanted to see if I could create a program that would build the stairs the other way around, like the following:

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

Here is the code I have written to generate this type of stairs:

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

Here is an example of the code process:

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

As you can see, save for the top step, the rest of the stairs are perfect. I don’t understand why this has happened. I have tried to change up the code but I can never seem to make the top step move to the correct position. It’s like Python doesn’t recognise blank spaces, which is strange because the rest of the stairs are fine.

Asked By: Scorch

||

Answers:

One fix is to add a print statement after getting the height. Python’s input sanitizes the new line character after the input but as suggested in the comments, there may be some further whitespace removal happening.

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

Also to note, the extra elif was removed. Your loop works for the base case.

Answered By: AbeCoull
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.