0

Slightly embarrassed to be posting this as I could succesfully complete mario(less) in pset1 but apparently cannot replicate it in Python. My code is as follows:

h = int(input("h: ")) # get height
while h < 1 or h > 8:
    h = int(input("h: ")) # reprompt if outside range

for row in range(0, h, 1):

    for space in range(0, h-row-1, 1):

        print(" ", end="")

        for column in range(0, row+1, 1):

            print("#", end="")

        print("")

I believe that the issue is in the spacing part. If I remove the spacing part (the for loop and the print " " line) then I successfully produce a left-aligned pyramid. But I cannot get it to become right-aligned using proper spacing. This was my C code i was trying to replicate:

#include <stdio.h>
#include <cs50.h>
int main(void)
{
   int height, row, column, space;
   do
   {
      height = get_int("How high do you want your pyramid: ");
   }
   while (height < 1 || height > 80);

   for (row = 0; row < height; row++)
   {
      for (space = 0; space < height - row - 1; space++)
      {
         printf(" ");
      }
         for (column = 0; column <= row; column++)
         {
            printf("#");
         }
         printf("\n");
   }
}

Any help is appreciated! And please, if you're explaining, err on the side of over-explaining and patronising because I am a rank beginner. Thank you!

1

When translating your original code from C to Python, you copied the indentation. That third for loop is not nested inside the second. In C, this doesn't matter because it ignores indentation and will follow the curly braces. In Python, though, the indentation means that the loop is nested, so your code is not as similar as it might appear.

In other words, remember that, because Python does not use semicolons or curly braces to denote the end of a function or line, line breaks and indentation tell it where things belong in the code. So, if things happen one after another, they must be at the same indentation level. Hopefully, that is enough of a hint to get you to fix the two places where this is the issue. :)

If it helps, feel free to mark this as accepted with the check, but if you have further questions, feel free to leave a comment here, and I can explain more.

1
  • Thank you this was very helpful! Looks like I need to be stricer with my indentation with Python. Jan 13 at 17:42

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .