Are you printing an additional character at the beginning of each line? – main error left aligned pyramid

Question:

I’m currently at pset6 from cs50, mario-less. My code compiles and prints the left aligned pyramid as the problem asks, but when I do a check50, most of them fail. What is the problem?

from cs50 import get_int

# Ask user for input
n = get_int("Height: ")

# While loop to check condition
while n < 1 or n > 8:
    print("Invalid number ")
    n = get_int("Enter another number: ")

# One for loop to prin left sided piramid
for j in range(1, n + 1):
    spaces = n - j + 1
    print(" " * spaces + "#" * j)
Asked By: stefanp

||

Answers:

As it currently stands, for n == 5 your code will print:

     #
    ##
   ###
  ####
 #####

However, we want to avoid that extra space at the start of every line and get:

    #
   ##
  ###
 ####
#####

So just reduce the number of spaces you are adding by 1:

# One for loop to print left sided pyramid
for j in range(1, n + 1):
    spaces = n - j
    print(" " * spaces + "#" * j)
Answered By: Andrew McClement

I did cs50 a while ago and my answer was something like yours (we probably based it on the C code we did prior). But thinking about it now, another way to do this with the help of fstrings would be like this:

n = int(input('height: ')
c = 1
for i in range(n):
    print(f'{" "*(n-1)}{"#"*c}')
    n -= 1
    c += 1
Answered By: FelixOakz
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.