Diamond Pattern in Python Using For Loop

Diamond Pattern in Python

To create a diamond pattern in Python using a for loop, use this simple piece of code:

h = eval(input("Enter diamond's height: "))

for x in range(h):
    print(" " * (h - x), "*" * (2*x + 1))
for x in range(h - 2, -1, -1):
    print(" " * (h - x), "*" * (2*x + 1))

Then run the program. For example, here is a diamond output of height 7:

How Does It Work

The diamond pattern using for loop in Python is a common beginner question in Python courses. Make sure you understand how it works.

In the above solution, the program asks user input for the desired height of the diamond.

The Two Loops that Make Up the Diamond

Then there are two for loops that construct the diamond.

The first loop prints the “upper half” of the diamond.

For example, if the height of the diamond is 5, the upper loop prints the lines 0, 1, 2, 3, 4 read from the top:

for x in range(h):
    print(" " * (h - x), "*" * (2*x + 1))

The second for loop prints the “lower half” of the diamond.

For example, if the height of the diamond is 5, the lower loop prints the lines 3, 2, 1, 0 starting from the end of the top half of the diamond:

for x in range(h - 2, -1, -1):
    print(" " * (h - x), "*" * (2*x + 1))

The Number of Asterisks and Rows of the Diamond

The Upper Half of the Diamond

If you look at the diamond, in the upper half, the number of asterisks grows by 1, 3, 5, 7... So if x is the row number of the diamond starting from the top, 2x+1 is the number of asterisks in that row.

To compensate for the increase in asterisks, the number of blank spaces on the left must decrease the further we go. So the number of white spaces is h-x. (No white spaces are printed on the right.)

The Lower Half of the Diamond

In the lower half, the number of asterisks decreases by ..., 7, 5, 3, 1 In other words, if x is the row number of the diamond starting from the middle of the diamond, 2x+1 is the number of asterisks in that row.

To compensate for the decrease in asterisks, the number of blank spaces on the left must increase the lower we go. So the number of white spaces is h-x.(No white spaces are printed on the right.)

Conclusion

Thanks for reading. I hope you enjoy it.

Happy coding!

Further Reading

50 Python Interview Questions with Answers

50+ Buzzwords of Web Development

Share on facebook
Facebook
Share on google
Google+
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on pinterest
Pinterest

Leave a Comment

Your email address will not be published. Required fields are marked *