0

Looks like similar questions were asked but I'm having problems with the Python version. Output looks fine on the surface but apparently the program is printing an extra spaces. I have played with the loop and variable S over and over and can't seem to get rid of the extra spaces without throwing off the structure of the pyramid. Any idea which element needs to be changed (while keeping the structure intact)?

import cs50 as cs

# introduces variables

n = 0
p = 0
h = 0

# prompts user for height of pyramid until he enters value between 0 and 23

while (h <= 0 or h > 23):
print("Height: ")
h = cs.get_int()

s = h - n - 1

# print spaces in increments of 1, and # in decrements of one for each
# increment of 1 in height,  and new line with number of instances not
# to exceed height

for n in range(n, h):
    n = n + 1
    for s in range(0, s + 1):
        print(" ", end="")
        s = s - 1
    for p in range(0, n + 1):
       print("#", end="")
       p = p + 1
    print("")

Output from Check50:

:) mario.py exists.
:) rejects a height of -1
:( handles a height of 0 correctly
    did not find EOF
:( handles a height of 1 correctly
    expected "##\n", not " ##\n"
:( handles a height of 2 correctly
    expected " ##\n###\n", not " ##\n ###\n"
:( handles a height of 23 correctly
    expected " ...", not " ..."
:( rejects a height of 24, and then accepts a height of 2
    expected " ##\n###\n", not " ##\n ###\n"
:) rejects a non-numeric height of "foo"
:) rejects a non-numeric height of ""

Program output:

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

Thank you!

3
  • Could you rewrite your code to use more than one letter per variable, and not use variables as loop counters that already existed outside of the loop (so not for s in range(0, s + 1))? Also, loop variables shouldn't be changed within the loop. As you're constantly reusing variable names, it's really hard to understand anything. – Blauelf Jan 22 '18 at 9:25
  • It works now that I replaced the for s in range(0, s + 1): to for s in range(1, s + 1): and declared s within the nested loop. In retrospect should have used a placeholder instead of s. I see how it's bad practice. Thank you for your help. – Dani Jan 23 '18 at 3:49
  • range(0, s + 1) returns an iterable that yields the numbers from 0 to s. Each iteration of the for loop, the loop variable is assigned another of the numbers. That's where the increment happens (it's basically set on entering the loop), the s = s + 1 shouldn't do anything. In earlier versions of Python, range would just generate a list that for then would work on. – Blauelf Jan 23 '18 at 9:11

You must log in to answer this question.

Browse other questions tagged .