Write a Python program to accept a positive integer n from the user and then print the following pattern using nested loops. For example, if n = 5, the output should be:

*

* *

* * *

* * * *

* * * * *

Answer:

Answer by student

n = int(input( "Enter a positive integer: " ))

for i in range( 1 , n+ 1 ):

  for j in range(i):

    print( "*" , end= " " )

  print()

Detailed answer by teachoo

-lock-

  • To print the pattern, we need to use nested loops . A nested loop is a loop inside another loop. The inner loop executes for each iteration of the outer loop.
  • We first ask the user to enter a positive integer n and store it in a variable n using the input() and int() functions.
  • Then we use a for loop to iterate from 1 to n using the range() function. The variable i represents the current row number and also the number of stars to be printed in that row.
  • Inside the for loop, we use another for loop to iterate from 0 to i-1 using the range() function. The variable j represents the current column number and is not used for any other purpose.
  • Inside the inner loop, we print a star followed by a space using the print() function with the end parameter set to " " . This means that the next print statement will not start from a new line but from the same line with a space after the star.
  • After the inner loop ends, we print a newline using the print() function without any argument. This means that the next print statement will start from a new line.
  • This way, we print n rows of stars with an increasing number of stars in each row.

So, the correct answer is:

n = int(input( "Enter a positive integer: " ))

for i in range( 1 , n+ 1 ):

  for j in range(i):

    print( "*" , end= " " )

  print()

-endlock-

Remove Ads Share on WhatsApp
Davneet Singh's photo - Co-founder, Teachoo

Made by

Davneet Singh

Davneet Singh is an IIT Kanpur graduate and has been teaching for 16+ years. At Teachoo, he breaks down Maths, Science and Computer Science into simple steps so students understand concepts deeply and score with confidence.

Many students prefer Teachoo Black for a smooth, ad-free learning experience.