0

I've tried to make my code efficient by reducing the number of loops/print functions compared with my solution in c. My code works, but check50 isn't happy with it -- apparently an extra space is printed per line? Anyone able to spot the issue?

from cs50 import get_int

height = get_int("Height: ")

if height > 7 or height < 1:
    print("no thanks")
    height = get_int("Height: ")
else:
    for i in range(height):
        j = i + 1 
        spaces = height - j
        print(f" " * spaces, "#" * (i + 1), "", "#" * j)

2 Answers 2

1

Look at the print line:

    print(f" " * spaces, "#" * (i + 1), "", "#" * j)

Python will print a space after each element (ie, each item separated from the next by a comma). That means that it's printing the spaces, followed by an extra space. It's also printing a space after the first group of #s. Interestingly, the "" isn't printing a space, but one is printed after that. So, the two spaces in the middle are printed, just out of sheer luck.

You need to rewrite this line to concatenate everything together so that all the extra spaces are not printed. Review the class material or google how to concatenate strings in python. ;-)

1
  • Ah amazing, thank you so much! I had previously put in '+' for concatenation which threw up some errors, but I've just tried it again and everything went green :D
    – AbbiePBC
    Commented Feb 2, 2021 at 16:11
1

There are multiple issues with the code. The height has to be between 1 and 8 inclusive. Your code will not allow a height of 8. Also, the user should be asked for the height until a proper number is given. Then, the program should print the two half pyramids. In your code, if there is a wrong input, then you question them once more and then exit. Also, while printing the pyramids, there should be a space between the two pyramids. In your code, there is no space between the pyramids. I would suggest that you translate your c code to python without removal of loops so that it works.

Hope this helps. If it does then please check the tickmark.

1
  • Hi, thanks for this - I've corrected the height <8 part, and the asking of the user, although this doesn't affect the check50 tests. There actually is a space between the pyramids with this code though. The issue isn't with this -- it's with the extra space printed per line that I can't seem to get rid of.
    – AbbiePBC
    Commented Feb 2, 2021 at 12:34

You must log in to answer this question.

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