Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)
closed by

How would I print out a number triangle in python utilizing a loop-based program? It's anything but a schoolwork assignment or anything it's simply an activity from the book I have been attempting to do yet have not actually approached. The triangle should print out resembling this:

1

2 2

3 3 3

4 4 4 4

5 5 5 5 5

6 6 6 6 6 6

closed

4 Answers

0 votes
by (15.4k points)
selected by
 
Best answer
To print a number triangle in Python using a loop-based program, you can follow a simple approach. Here's an example code snippet that achieves the desired output:

rows = 6  # Number of rows in the triangle

for i in range(1, rows + 1):  # Iterate over each row

    for j in range(i):  # Repeat the number i for each column in the row

        print(i, end=" ")  # Print the number followed by a space

    print()  # Move to the next line after printing the row

In this code, we use two nested for loops. The outer loop iterates over each row, starting from 1 and going up to the specified number of rows (rows). The inner loop repeats the number i for each column in the row, where i corresponds to the current row number. We use the print() function with end=" " to print the number followed by a space, and then call print() again without any arguments to move to the next line and start a new row.
0 votes
by (26.4k points)

Kindly check the below code:

for i in range(7):

    print (str(i) + " ")*i

Output:

1  

2 2  

3 3 3  

4 4 4 4  

5 5 5 5 5  

6 6 6 6 6 6  

Are you looking for a good python tutorial? Join the python course fast and gain more knowledge in python.

Watch this video tutorial for more information.

0 votes
by (25.7k points)

code for the above question is:

rows = 6  # Number of rows in the triangle

for i in range(1, rows + 1):  # Iterate over each row

    for j in range(i):  # Repeat the number i for each column in the row

        print(i, end=" ")  # Print the number followed by a space

    print()  # Move to the next line after printing the row

0 votes
by (19k points)
To print a number triangle in Python using a loop-based program, you can use the following code:

rows = 6

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

    print((str(i) + " ") * i)

This code iterates over each row and prints the number i repeated i times, separated by a space. The range(1, rows + 1) function is used to generate the sequence of numbers from 1 to rows. The print() function is called with the expression (str(i) + " ") * i to print the numbers in the desired pattern.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Mar 23, 2021 in Python by Rekha (2.2k points)
0 votes
1 answer
0 votes
1 answer
asked Jul 8, 2019 in Python by Sammy (47.6k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...