148k views
1 vote
Elements of Computer Programming

Problem . Write a script that displays the following triangle pattern. Ask the user for the number of levels you want in your triangle. Use for loops to generate the pattern. Display all asterisks (*) with a single statement of the form print('*', end='')

User Savner
by
7.6k points

1 Answer

0 votes

Final answer:

To create a triangle pattern in Python, prompt the user for the number of triangle levels, use a for loop to iterate through each level, and print spaces and asterisks in the correct sequence using print('*', end='').

Step-by-step explanation:

Creating a Triangle Pattern in Python

To create a triangle pattern using Python, you can use nested for loops. First, you ask the user for the number of levels for the triangle, storing it in a variable, say 'levels'. Next, you use a for loop to iterate through each level, printing spaces ' ' for padding and asterisks '*' for the actual level. The inner loop handles the number of asterisks to print on each level. The form print('*', end='') allows you to print asterisks without a newline at the end.

Python Script Example

Here is a basic example:

levels = int(input("Enter the number of levels for the triangle: "))
for i in range(levels):
for j in range(levels - i - 1):
print(' ', end='')
for k in range(i + 1):
print('*', end=' ')
print()

The number of spaces decreases with each level whereas the number of asterisks increases, thus creating a right-aligned triangle pattern. It's important to note that the programming concepts used here are not exclusive to Python and can be implemented in other programming languages like Modula-3, ANSI Scheme, or Squeak.

User Jeroen Jacobs
by
7.4k points