Print patterns in Python | Part - 1

05 min read

Task: Write a code to print the following pattern in Python:

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

Solution:

n=5 
for i in range(0, n): # from i=0 to i=n incremented by one in each successive iteration
for j in range(0, i+1): # from j=i to j=i+1 incremented by one in each successive iteration
print("* ",end="") # print * and give a space
print("\r") # end every row in the end



Task: Write a code to print the following pattern in Python:

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

Solution:

n=5

k=2*n - 2

for
i in range(0, n):
      for j in range(0, k):
            print(end=" ")                  #printing as per the requirment
      k -= 2                                # decrement k value by 2 in each iteration
      for j in range(0, i+1):
            print("* ", end="")              # print stars, each time it prints something it leaves a space
      print("\r")                            #end every row

 


Task: Write a code to print the following pattern in Python:

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

Solution:

n=5
k=2*n - 2
for i in range(0, n):
      for in range(0, k):
            print(end=" ")                  #printing as per the requirment
      k -= 1                                # decrement k value by 1 in each iteration
      for in range(0, i+1):
            print("* ", end="")              # print stars 
      print("\r")                            #end every row
 
 


Task: Write a code to print the following pattern in Python:

1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5
Solution:

n=5 # 5 rows
num = 1 # start with 1
for i in range(0, n):
  num = 1 #re-assigning the starting number
for j in range(0, i+1):
print(num, end=" ") # print the number and give a space
  num +=1 # increment the number by 1 each time
  print("\r") # end the rows

POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error