How to print star pattern in python

Patterns can be printed in python using simple for loops. First outer loop is used to handle the number of rows and the Inner nested loop is used to handle the number of columns. Manipulating the print statements, different number patterns, alphabet patterns, or star patterns can be printed. 

Some of the Patterns are shown in this article. 

  • Simple pyramid pattern

Python3

def pypart[n]:

    for i in range[0, n]:

        for j in range[0, i+1]:

            print["* ",end=""]

        print["\r"]

n = 5

pypart[n]

Output

* 
* * 
* * * 
* * * * 
* * * * * 

Approach 2: Using List in Python 3, this could be done in a simpler way

Python

def pypart[n]:

    myList = []

    for i in range[1,n+1]:

        myList.append["*"*i]

    print["\n".join[myList]]

n = 5

pypart[n]

Output

*
**
***
****
*****

Approach 3: Using recursion

Python3

def pypart[n]:

    if n==0:

        return

    else:

        pypart[n-1]

        print["* "*n]

n = 5

pypart[n]

Output

* 
* * 
* * * 
* * * * 
* * * * * 

Approach 4: Using while loop 

Python3

n=5

i=1;j=0

while[i

Chủ Đề