Diamonds

Tags: tiny, artistic, beginner

This program features a small algorithm for drawing ASCII-art diamonds of various sizes. It contains functions for drawing either an outline or filled-in-style diamond of the size you dictate. These functions are good practice for a beginner; try to understand the pattern behind the diamond drawings as they increase in size.

diamonds.py
 1r"""Diamonds, by Al Sweigart al@inventwithpython.com
 2Draws diamonds of various sizes.
 3View this code at https://nostarch.com/big-book-small-python-projects
 4                           /\       /\
 5                          /  \     //\\
 6            /\     /\    /    \   ///\\\
 7           /  \   //\\  /      \ ////\\\\
 8 /\   /\  /    \ ///\\\ \      / \\\\////
 9/  \ //\\ \    / \\\///  \    /   \\\///
10\  / \\//  \  /   \\//    \  /     \\//
11 \/   \/    \/     \/      \/       \/
12Tags: tiny, beginner, artistic"""
13
14def main():
15    print('Diamonds, by Al Sweigart al@inventwithpython.com')
16
17    # Display diamonds of sizes 0 through 6:
18    for diamondSize in range(0, 6):
19        displayOutlineDiamond(diamondSize)
20        print()  # Print a newline.
21        displayFilledDiamond(diamondSize)
22        print()  # Print a newline.
23
24
25def displayOutlineDiamond(size):
26    # Display the top half of the diamond:
27    for i in range(size):
28        print(' ' * (size - i - 1), end='')  # Left side space.
29        print('/', end='')  # Left side of diamond.
30        print(' ' * (i * 2), end='')  # Interior of diamond.
31        print('\\')  # Right side of diamond.
32
33    # Display the bottom half of the diamond:
34    for i in range(size):
35        print(' ' * i, end='')  # Left side space.
36        print('\\', end='')  # Left side of diamond.
37        print(' ' * ((size - i - 1) * 2), end='')  # Interior of diamond.
38        print('/')  # Right side of diamond.
39
40
41def displayFilledDiamond(size):
42    # Display the top half of the diamond:
43    for i in range(size):
44        print(' ' * (size - i - 1), end='')  # Left side space.
45        print('/' * (i + 1), end='')  # Left half of diamond.
46        print('\\' * (i + 1))  # Right half of diamond.
47
48    # Display the bottom half of the diamond:
49    for i in range(size):
50        print(' ' * i, end='')  # Left side space.
51        print('\\' * (size - i), end='')  # Left side of diamond.
52        print('/' * (size - i))  # Right side of diamond.
53
54
55# If this program was run (instead of imported), run the game:
56if __name__ == '__main__':
57    main()

https://inventwithpython.com/bigbookpython/project16.html