fredrick
fredrick

Reputation: 11

Python Looping To Produce Output On Separate Lines

I am new to programming and was trying to create a program in python that creates a staircase with size based on the user input. The program should appear as shown below:

Favorable Output

This is the code I have so far;

steps = int(input('How many steps? '))
print('__')
for i in range(steps):
  n = steps+i
  print(' '*(n-2) + '|_')
print('_'*n + '|')

This is what my output is;

My Output

Note - The horizontal lines are underscores '_' and the vertical lines are the pipe character '|'.

Upvotes: 1

Views: 105

Answers (5)

Yusuf Pisan
Yusuf Pisan

Reputation: 1

Not sure what your exact question is. The patter of steps is:

  • Step 1 -> 4 blanks
  • Step 2 -> 6 blanks
  • Step 3 -> 8 blanks
  • Step n -> 2 + (2 * n) blanks

    steps = int(input('How many steps? '))

Upvotes: 0

AChampion
AChampion

Reputation: 30268

It is simpler to consider that n is the current step and given the step size (2) then you just need 2n for your placement:

steps = 5
print('__')
for n in range(1, steps):
    print(' '*n*2 + '|_')
print('_'*steps*2 + '|')

Output:

__
  |_
    |_
      |_
        |_
__________|

You can abstract this to take any step size, e.g.:

steps = 5
size = 4
print('_'*size)
for n in range(1, steps):
    print(' '*n*size + '|' + '_'*(size-1))
print('_'*steps*size + '|')

Output:

____
    |___
        |___
            |___
                |___
____________________|

Upvotes: 0

Jonathan Liu
Jonathan Liu

Reputation: 93

To get the correct amount of steps, you have to change the for loop to:

for i in range(steps-1):

This is because you want to print the |_'s one less time than there are steps; your "top" step __ already counts as one step.

The whole thing (changed some other things to make the formatting better):

steps = int(input('How many steps? '))
print('__')
for i in range(steps-1):
    print(' '*(2+2*i) + '|_')
print('_'*2*steps + '|')

Output:

output

Upvotes: 1

Mikael
Mikael

Reputation: 554

You can do it via while. counter = 0 while counter < steps: Create_stairs() increase counter

Upvotes: 0

user7141836
user7141836

Reputation:

def stairs(steps):
    print("__")
    length = 1
    for i in range(steps):
        length += 1
        print("%s|_" % (" "*(length+i)),)
    print("%s|" % ("_"*(length+steps+1)),)

stairs(4)

Output:

__
  |_
    |_
      |_
        |_
__________|

Upvotes: 0

Related Questions