'Code is accepting input other than 1 through 8 and it's not printing out as expected

Here is the expected output something like this:

I don't seem to understand what's wrong with this code, it's accepting input other than 1 through 8, and also it's not printing out as expected.

I'm supposed to be printing an inverted pattern of hashes that forms a triangle but don't really know what went wrong.

here is the code

from cs50 import get_int

while True:
    n = get_int("Height: ")
    if n < 1 or n > 8:
        break

for i in range(n):
    for space in range(n-1):
        print(" ", end="")

        for j in range(i):
            print("#", end="")
            print()

I think there's something obviously wrong with the logic used



Solution 1:[1]

You have few mistakes.

Two main problems are:

  • you have to check n >= 1 and n <= 8 or shorter 1 <= n <= 8
  • you have wrong indentations (and indentions are very important in Python).

This version

while True:
    n = int(input("Height: "))
    if 1 <= n <= 8:
        break

for i in range(n):

    # ---
    
    for space in range(n-1):
        print(" ", end="")

    # ---

    for j in range(i):
        print("#", end="")

    # ---
        
    print()

gives

Height: 5
    
    #
    ##
    ###
    ####

so it is almost good.

Now it needs different values in ranges:

  • first range needs range(1, n+1) instead of range(n)
  • second range needs variable i instead of value 1 - range(n-i)
while True:    
    n = int(input("Height: "))
    if 1 <= n <= 8:
        break

for i in range(1, n+1):
    
    # ---

    for space in range(n-i):
        print(" ", end="")

    # ---

    for j in range(i):
        print("#", end="")

    # ---
        
    print()

And now it gives

Height: 5
    #
   ##
  ###
 ####
#####

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1