๐ Python Pattern Challenge — Day 26 | Binary Number Pattern
Python pattern printing is a fun way to improve your loops, number sequences, and logical thinking. For Day 26, let's try a simple but interesting pattern using only 1 and 0.
This pattern alternates between 1 and 0 in every row, creating a growing binary-style sequence.
๐ฏ Today's Challenge
Write a Python program to print the following pattern:
Can you create this pattern using the cleanest Python code? ๐
Solution 1 — Using Nested for Loops
n = 6 for i in range(1, n + 1): print(" " * (n - i), end="") for j in range(i): print(1 if j % 2 == 0 else 0, end=" ") print()
How It Works
1. Controlling the rows
for i in range(1, n + 1):This loop creates six rows, increasing the number of elements in each row.
2. Managing the spacing
print(" " * (n - i), end="")This adds spaces before each row to give the pattern a pyramid-like appearance.
3. Alternating between 1 and 0
print(1 if j % 2 == 0 else 0, end=" ")The condition checks whether the position j is even or odd.
If j is even, it prints 1.
If j is odd, it prints 0.
This creates the alternating sequence:
1Solution 2 — Using String Multiplication
for i in range(1, 7): row = " ".join(str(j % 2) for j in range(i)) print(" " * (6 - i) + row.replace("0", "1", 1))
This approach is less straightforward because the replacement operation affects the first zero. For a reliable solution, prefer the nested-loop version above.
Solution 3 — Using a Function
def binary_pattern(n):
for i in range(1, n + 1):
row = []
for j in range(i):
row.append(str(1 if j % 2 == 0 else 0))
print(" " * (n - i) + " ".join(row))
binary_pattern(6)Using a function makes the pattern reusable. You can call binary_pattern(10) to print ten rows.
⚡ Short & Clean Code
for i in range(1, 7): print(" " * (6 - i), end="") print(*[1 if j % 2 == 0 else 0 for j in range(i)])
Just a few lines are enough to generate the complete pattern!
๐ Challenge Yourself
Can you modify today's pattern?
Start every row with 0 instead of 1.
Print the pattern in reverse order.
Create the same pattern using a while loop.
Generate a left-aligned version without spaces.
Take the number of rows using input().
Try a pattern where each row alternates between 0 and 1, but starts with the opposite digit.
Share your solution in the comments! ๐
26 Days. 26 Patterns. Stronger Python Logic. ๐๐ฅ
Learn • Practice • Grow with CLCODING ๐
.png)


0 Comments:
Post a Comment