1

I am trying to print something like this

*
* *
* * *
* * * *

Here is my code

while 1:
    n=int(input("Enter the N"))
    if n<3:
        print("Wrong Input")
        continue
    else:
        for i in range(1,n+1):
            for j in range(1,i+1):
                print("x")

I refer to this question but I am not able to achieve this. Can you please help me how can I achieve this? Thank you

Community
  • 1
  • 1
Bhavik Joshi
  • 2,557
  • 6
  • 24
  • 48

2 Answers2

4

Example:

for i in range(5): 
     print('* '* i)

*
* *
* * *
* * * *

EDIT

Or you could use map functions which is faster:

print('\n'.join(map(lambda x: '* ' * x, range(5))))

Timing

In [25]: %timeit print('\n'.join(map(lambda x: '* ' * x, range(5))))
1000 loops, best of 3: 289 us per loop

In [26]: %timeit for i in range(5): print('* '*i)
1000 loops, best of 3: 444 us per loop
Anton Protopopov
  • 30,354
  • 12
  • 88
  • 93
1

Or something like this as well might work:

>>> n = 5
>>> s = '\n'.join('*' * i for i in range(5))
>>> print(s)

*
**
***
****

Or wrap it in a function definition and pass it any character you want with any number you need:

>>> def my_print(c, n):
        s = '\n'.join(c * i for i in range(n+1))
        return s

>>> my_string = my_print('^', 10)
>>> print(my_string)


^
^^
^^^
^^^^
^^^^^
^^^^^^
^^^^^^^
^^^^^^^^
^^^^^^^^^
^^^^^^^^^^
Iron Fist
  • 10,739
  • 2
  • 18
  • 34