Write a program to print the following pattern in Python
Write a program to print the following pattern in Python
Here is a simple Python program that prints the desired pattern:
def print_pattern(n):
for i in range(n, -1, -1):
for j in range(i+1):
print("*", end=" ")
print()
n = int(input("Enter the number of rows: "))
print_pattern(n)
Let's break down this code:
Theprint_pattern
function takes an integer n
as input. This is the number of rows you want in your pattern. Inside the function, we have a nested loop structure: The outer loop runs from n
to 0
, decrementing by 1
each time (range(n, -1, -1)
). The inner loop runs from i+1
to 0
, incrementing by -1
each time (range(i+1)
). Inside the nested loops, we print a string of i+1
asterisks ("* "
repeated i+1
times), separated by spaces. The end=" "
argument in the print
function makes it print everything on one line. Finally, the program asks the user to input the number of rows they want and calls the print_pattern
function with that number.
For example, if you enter 4
, the output will be:
* * * *
This pattern is a simple way to represent a pyramid-like structure. The outer loop controls how many lines we print, and the inner loop determines how many asterisks are printed on each line.
If you're new to Python or programming in general, it might be helpful to understand how loops work, as well as what the range
function does. There are plenty of resources available online that can help with those topics!
How to print 1 12 123 1234 12345 in Python?
To print the sequence of numbers from 1 to 12345, you can use a for loop in Python. Here's one way to do it:
for i in range(1, 12346): # Note: The end value is exclusive in the range function.
if len(str(i)) == 1:
print(i)
elif len(str(i)) == 2:
print(i, end=' ')
elif len(str(i)) == 3:
print(f'{i} ', end='')
else:
print(f'{i}n', end='')
When you run this code, it will print the numbers from 1 to 12345 in a format similar to:
1
2 3
4 5 6
...
99
100
101 102 103
...
1099
1100
1101 1102
...
11111
11112 11113
...
12345
As you can see, the program separates numbers into different groups based on their length. If a number has one digit (like 1), it just prints that number. If it has two digits (like 12), it prints them separated by a space. For three-digit numbers (like 123), it prints them with a space between each pair of digits. And finally, for four or more digit numbers (like 1234 or 12345), it prints them on separate lines.
This is just one way to solve the problem. There are many other ways you could do it, depending on your personal preference and the specific requirements of your project.